diff --git a/actix-http/src/extensions.rs b/actix-http/src/extensions.rs index 2ed3973bf..b169c464d 100644 --- a/actix-http/src/extensions.rs +++ b/actix-http/src/extensions.rs @@ -104,6 +104,22 @@ impl Extensions { .and_then(|boxed| boxed.downcast_mut()) } + pub fn get_or_insert(&mut self, value: T) -> &mut T { + self.map + .entry(TypeId::of::()) + .or_insert(Box::new(value)) + .downcast_mut() + .expect("extensions map to always contain value T") + } + + 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 to always contain value T") + } + /// Remove an item from the map of a given type. /// /// If an item of this type was already stored, it will be returned. diff --git a/actix-web/CHANGES.md b/actix-web/CHANGES.md index cee14dc4b..eeb3bd471 100644 --- a/actix-web/CHANGES.md +++ b/actix-web/CHANGES.md @@ -5,6 +5,7 @@ - On Windows, an error is now returned from `HttpServer::bind()` (or TLS variants) when binding to a socket that's already in use. - Update `brotli` dependency to `7`. - Minimum supported Rust version (MSRV) is now 1.75. +- Added `Extensions::get_or_insert` and `Extensions::get_or_insert_with` ## 4.9.0