Skip to content

Commit f4cff03

Browse files
authored
Add Extensions::extend (#546)
1 parent 4fb67bc commit f4cff03

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# Unreleased
2+
3+
* Add `extend()` method to `Extension`.
4+
15
# 0.2.6 (December 30, 2021)
26

37
* Upgrade internal `itoa` dependency to 1.0.

src/extensions.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,39 @@ impl Extensions {
188188
.as_ref()
189189
.map_or(0, |map| map.len())
190190
}
191+
192+
/// Extends `self` with another `Extensions`.
193+
///
194+
/// If an instance of a specific type exists in both, the one in `self` is overwritten with the
195+
/// one from `other`.
196+
///
197+
/// # Example
198+
///
199+
/// ```
200+
/// # use http::Extensions;
201+
/// let mut ext_a = Extensions::new();
202+
/// ext_a.insert(8u8);
203+
/// ext_a.insert(16u16);
204+
///
205+
/// let mut ext_b = Extensions::new();
206+
/// ext_b.insert(4u8);
207+
/// ext_b.insert("hello");
208+
///
209+
/// ext_a.extend(ext_b);
210+
/// assert_eq!(ext_a.len(), 3);
211+
/// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
212+
/// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
213+
/// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
214+
/// ```
215+
pub fn extend(&mut self, other: Self) {
216+
if let Some(other) = other.map {
217+
if let Some(map) = &mut self.map {
218+
map.extend(*other);
219+
} else {
220+
self.map = Some(other);
221+
}
222+
}
223+
}
191224
}
192225

193226
impl fmt::Debug for Extensions {

0 commit comments

Comments
 (0)