From 04533a15fa1652e047f51d439aa2fe7be8ccc1de Mon Sep 17 00:00:00 2001 From: Akos Vandra-Meyer Date: Sun, 9 Feb 2025 23:04:21 +0100 Subject: [PATCH] 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 --- actix-http/CHANGES.md | 1 + actix-http/src/extensions.rs | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/actix-http/CHANGES.md b/actix-http/CHANGES.md index 982add26a..23ebe43e1 100644 --- a/actix-http/CHANGES.md +++ b/actix-http/CHANGES.md @@ -5,6 +5,7 @@ ### Added - Add `header::CLEAR_SITE_DATA` constant. +- Add `Extensions::get_or_insert[_with]()` methods. ### Changed diff --git a/actix-http/src/extensions.rs b/actix-http/src/extensions.rs index 2ed3973bf..9c85caf37 100644 --- a/actix-http/src/extensions.rs +++ b/actix-http/src/extensions.rs @@ -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::>(), None); + /// + /// map.get_or_insert(Vec::::new()).push(1); + /// assert_eq!(map.get::>(), Some(&vec![1])); + /// + /// map.get_or_insert(Vec::::new()).push(2); + /// assert_eq!(map.get::>(), Some(&vec![1,2])); + /// ``` + pub fn get_or_insert(&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::>(), None); + /// + /// map.get_or_insert_with(Vec::::new).push(1); + /// assert_eq!(map.get::>(), Some(&vec![1])); + /// + /// map.get_or_insert_with(Vec::::new).push(2); + /// assert_eq!(map.get::>(), Some(&vec![1,2])); + /// ``` + pub fn get_or_insert_with T>(&mut self, default: F) -> &mut T { + self.map + .entry(TypeId::of::()) + .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.