crux_core/effects/routes/buffer.rs
1use std::sync::Mutex;
2
3use crate::{Request, capability::Operation};
4
5/// A route that simply collects requests for the caller to drain and handle.
6///
7/// Unlike [`Serialized`](super::Serialized) and [`Parked`](super::Parked), this
8/// lane does no FFI or id bookkeeping: the routing closure pushes each request
9/// with [`Buffer::push`], and the surrounding code later calls
10/// [`Buffer::drain`] to take and handle them. This is convenient for tests and
11/// for simple, synchronous in-process handlers.
12pub struct Buffer<Op: Operation> {
13 requests: Mutex<Vec<Request<Op>>>,
14}
15
16impl<Op: Operation> Default for Buffer<Op> {
17 fn default() -> Self {
18 Self {
19 requests: Mutex::default(),
20 }
21 }
22}
23
24impl<Op: Operation> Buffer<Op> {
25 /// Store a request for the caller to drain and handle.
26 ///
27 /// # Panics
28 ///
29 /// Panics if the internal mutex has been poisoned.
30 pub fn push(&self, request: Request<Op>) {
31 self.requests
32 .lock()
33 .expect("buffer route lock poisoned")
34 .push(request);
35 }
36
37 /// Take all currently buffered requests.
38 ///
39 /// # Panics
40 ///
41 /// Panics if the internal mutex has been poisoned.
42 #[must_use]
43 pub fn drain(&self) -> Vec<Request<Op>> {
44 self.requests
45 .lock()
46 .expect("buffer route lock poisoned")
47 .drain(..)
48 .collect()
49 }
50}