This commit is contained in:
Ákos Vandra-Meyer 2025-01-31 09:40:15 +01:00
parent d57d5f3461
commit d508164f51
1 changed files with 22 additions and 0 deletions

View File

@ -104,6 +104,17 @@ impl Extensions {
.and_then(|boxed| boxed.downcast_mut()) .and_then(|boxed| boxed.downcast_mut())
} }
/// Get a mutable reference or insert an item of a given type.
///
/// ```
/// # use actix_http::Extensions;
/// let mut map = Extensions::new();
/// assert_eq!(map.get::<Vec<u32>>(), None);
/// map.get_or_insert(Vec::<u32>::new()).push(1);
/// assert_eq!(map.get::<Vec<u32>>(), Some(vec![1]));
/// map.get_or_insert(Vec::<u32>::new()).push(2);
/// assert_eq!(map.get::<Vec<u32>>(), Some(vec![1,2]));
/// ```
pub fn get_or_insert<T: 'static>(&mut self, value: T) -> &mut T { pub fn get_or_insert<T: 'static>(&mut self, value: T) -> &mut T {
self.map self.map
.entry(TypeId::of::<T>()) .entry(TypeId::of::<T>())
@ -112,6 +123,17 @@ impl Extensions {
.expect("extensions map to always contain value T") .expect("extensions map to always contain value T")
} }
/// Get a mutable reference or insert an item of a given type calculated with the closure given.
///
/// ```
/// # use actix_http::Extensions;
/// let mut map = Extensions::new();
/// assert_eq!(map.get::<Vec<u32>>(), None);
/// map.get_or_insert_with(Vec::<u32>::new).push(1);
/// assert_eq!(map.get::<Vec<u32>>(), Some(vec![1]));
/// map.get_or_insert_with(Vec::<u32>::new).push(2);
/// assert_eq!(map.get::<Vec<u32>>(), Some(vec![1,2]));
/// ```
pub fn get_or_insert_with<T: 'static, F: FnOnce() -> T>(&mut self, default: F) -> &mut T { pub fn get_or_insert_with<T: 'static, F: FnOnce() -> T>(&mut self, default: F) -> &mut T {
self.map self.map
.entry(TypeId::of::<T>()) .entry(TypeId::of::<T>())