Skip to main content

serenade_http/
attributes.rs

1//! Request attributes bag (route params, request-scoped values).
2
3use std::any::Any;
4use std::collections::HashMap;
5use std::fmt::{Debug, Formatter};
6
7/// Heterogeneous map keyed by string. Values must be `Send + Sync`.
8#[derive(Default)]
9pub struct AttributeBag {
10    values: HashMap<String, Box<dyn Any + Send + Sync>>,
11}
12
13impl AttributeBag {
14    /// Empty bag.
15    #[must_use]
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Stores `value` under `key`, replacing any previous entry.
21    pub fn insert<T: Any + Send + Sync>(&mut self, key: impl Into<String>, value: T) {
22        self.values.insert(key.into(), Box::new(value));
23    }
24
25    /// Borrows a value of type `T` stored at `key`.
26    #[must_use]
27    pub fn get<T: Any + Send + Sync>(&self, key: &str) -> Option<&T> {
28        self.values.get(key).and_then(|value| value.downcast_ref())
29    }
30
31    /// Mutably borrows a value of type `T` stored at `key`.
32    pub fn get_mut<T: Any + Send + Sync>(&mut self, key: &str) -> Option<&mut T> {
33        self.values
34            .get_mut(key)
35            .and_then(|value| value.downcast_mut())
36    }
37
38    /// Removes and returns a value of type `T` stored at `key`.
39    #[must_use]
40    pub fn remove<T: Any + Send + Sync>(&mut self, key: &str) -> Option<T> {
41        let boxed = self.values.remove(key)?;
42        boxed.downcast().ok().map(|value| *value)
43    }
44
45    /// Whether `key` is present (any type).
46    #[must_use]
47    pub fn contains(&self, key: &str) -> bool {
48        self.values.contains_key(key)
49    }
50
51    /// Number of entries.
52    #[must_use]
53    pub fn len(&self) -> usize {
54        self.values.len()
55    }
56
57    /// Whether the bag is empty.
58    #[must_use]
59    pub fn is_empty(&self) -> bool {
60        self.values.is_empty()
61    }
62}
63
64impl Debug for AttributeBag {
65    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("AttributeBag")
67            .field("keys", &self.values.keys().collect::<Vec<_>>())
68            .finish()
69    }
70}