pub struct Extensions { /* private fields */ }Expand description
A type-indexed bag of arbitrary values carried by a Context.
This is how work threaded through a context accumulates live state that the
backend generic doesn’t model: a request id set by an HTTP layer, a policy
decision recorded by an authorization check, a database or cache client to be
reused downstream, a logger or span. Each value is keyed by its own Rust
type, so there is at most one value per type and reads are fully typed —
no string keys, no downcasting at the call site. This is the same pattern as
http::Extensions.
Values must be Send + Sync + 'static so the context (and everything it
carries) can cross await points and move between threads.
use ash_domain::Extensions;
#[derive(Debug, PartialEq)]
struct RequestId(String);
let mut ext = Extensions::new();
ext.insert(RequestId("abc-123".into()));
assert_eq!(ext.get::<RequestId>(), Some(&RequestId("abc-123".into())));
assert!(ext.get::<u64>().is_none());Implementations§
Source§impl Extensions
impl Extensions
Sourcepub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T>
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T>
Insert a value, keyed by its type. Returns the previous value of the same type, if one was present.
Sourcepub fn get<T: Send + Sync + 'static>(&self) -> Option<&T>
pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T>
Borrow the value of type T, if one is present.
Sourcepub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
Mutably borrow the value of type T, if one is present.
Sourcepub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T>
pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T>
Remove and return the value of type T, if one is present.
Sourcepub fn merge(&mut self, other: Extensions)
pub fn merge(&mut self, other: Extensions)
Move every value out of other into this bag, consuming it.
A type present in both is overwritten by other’s value: the bag
being merged in is the newer, more specific one (a handler’s scratch
merging back into the request context), so it wins.
use ash_domain::Extensions;
#[derive(Debug, PartialEq)] struct Timing(u64);
#[derive(Debug, PartialEq)] struct Tag(&'static str);
let mut parent = Extensions::new();
parent.insert(Timing(1));
parent.insert(Tag("parent"));
let mut scratch = Extensions::new();
scratch.insert(Timing(99));
parent.merge(scratch);
assert_eq!(parent.get::<Timing>(), Some(&Timing(99))); // scratch wins
assert_eq!(parent.get::<Tag>(), Some(&Tag("parent"))); // untouched