add get_or_insert and get_or_insert_with for Extensions

This commit is contained in:
Ákos Vandra-Meyer 2025-01-31 09:29:21 +01:00
parent 91e29c0ce4
commit d57d5f3461
2 changed files with 17 additions and 0 deletions

View File

@ -104,6 +104,22 @@ impl Extensions {
.and_then(|boxed| boxed.downcast_mut()) .and_then(|boxed| boxed.downcast_mut())
} }
pub fn get_or_insert<T: 'static>(&mut self, value: T) -> &mut T {
self.map
.entry(TypeId::of::<T>())
.or_insert(Box::new(value))
.downcast_mut()
.expect("extensions map to always contain value T")
}
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 to always contain value T")
}
/// Remove an item from the map of a given type. /// Remove an item from the map of a given type.
/// ///
/// If an item of this type was already stored, it will be returned. /// If an item of this type was already stored, it will be returned.

View File

@ -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. - 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`. - Update `brotli` dependency to `7`.
- Minimum supported Rust version (MSRV) is now 1.75. - Minimum supported Rust version (MSRV) is now 1.75.
- Added `Extensions::get_or_insert` and `Extensions::get_or_insert_with`
## 4.9.0 ## 4.9.0