mirror of
https://github.com/fafhrd91/actix-web
synced 2025-02-21 11:54:47 +01:00
Add Extensions::get_or_insert[_with]()
methods (#3561)
* add get_or_insert and get_or_insert_with for Extensions * add docs * fix doctest * docs: update changelog * chore: simplify get_or_insert --------- Co-authored-by: Rob Ede <robjtede@icloud.com>
This commit is contained in:
parent
a4eaa7f0bb
commit
04533a15fa
@ -5,6 +5,7 @@
|
||||
### Added
|
||||
|
||||
- Add `header::CLEAR_SITE_DATA` constant.
|
||||
- Add `Extensions::get_or_insert[_with]()` methods.
|
||||
|
||||
### Changed
|
||||
|
||||
|
@ -104,6 +104,46 @@ impl Extensions {
|
||||
.and_then(|boxed| boxed.downcast_mut())
|
||||
}
|
||||
|
||||
/// Inserts the given `value` into the extensions if it is not present, then returns a reference
|
||||
/// to the value in the extensions.
|
||||
///
|
||||
/// ```
|
||||
/// # 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 {
|
||||
self.get_or_insert_with(|| value)
|
||||
}
|
||||
|
||||
/// Inserts a value computed from `f` into the extensions if the given `value` is not present,
|
||||
/// then returns a reference to the value in the extensions.
|
||||
///
|
||||
/// ```
|
||||
/// # 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 {
|
||||
self.map
|
||||
.entry(TypeId::of::<T>())
|
||||
.or_insert_with(|| Box::new(default()))
|
||||
.downcast_mut()
|
||||
.expect("extensions map should now contain a T value")
|
||||
}
|
||||
|
||||
/// Remove an item from the map of a given type.
|
||||
///
|
||||
/// If an item of this type was already stored, it will be returned.
|
||||
|
Loading…
x
Reference in New Issue
Block a user