mini_serve/state.rs
1use std::ops::Deref;
2use std::sync::Arc;
3
4/// Shared application state passed to every request handler.
5///
6/// Wraps an `Arc<S>` for zero-allocation sharing across handlers. Handlers
7/// receive a clone of this wrapper (not a clone of `S`), which only increments
8/// the refcount. Dereferences transparently to `&S`.
9#[derive(Clone)]
10pub struct State<S>(Arc<S>);
11
12impl<S> State<S> {
13 /// Create a new state from a value, wrapping it in an `Arc`.
14 pub fn new(state: S) -> Self {
15 State(Arc::new(state))
16 }
17
18 /// Create a state from an existing `Arc`.
19 ///
20 /// Useful for sharing state between the app and background tasks without
21 /// allocating a second `Arc`.
22 pub fn from_arc(state: Arc<S>) -> Self {
23 State(state)
24 }
25
26 /// Extract a clone of the inner value.
27 ///
28 /// Only available if `S` implements `Clone`. This is generally not needed
29 /// in request handlers (dereference to `&S` instead); it's useful for
30 /// copying state into spawned background tasks.
31 pub fn inner(&self) -> S
32 where
33 S: Clone,
34 {
35 S::clone(&self.0)
36 }
37}
38
39impl<S> Deref for State<S> {
40 type Target = S;
41
42 fn deref(&self) -> &S {
43 &self.0
44 }
45}