Skip to content

Commit 613d3d4

Browse files
refactor: avoid unnecessary .expect()s for empty HeaderMap (#768)
* Avoid unnecessary .expect()s for empty HeaderMap This change removes the Result::expect() calls in the constructors for an empty HeaderMap. These calls were provably not going to fail at runtime but rustc's inliner wasn't smart enough to figure that out: strings analysis of compiled binaries showed that the error message to the expect() still showed up in generated code. There are no behavioral differences as a result of this change. * Move new_empty() body into `Default` impl This gives us one fewer named method since we can use default() in place of new_empty(). It preserves the property that `HeaderMap::new()` constrains the generic type to `T=HeaderValue`.
1 parent 181f73c commit 613d3d4

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

src/header/map.rs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -445,8 +445,21 @@ impl HeaderMap {
445445
/// assert!(map.is_empty());
446446
/// assert_eq!(0, map.capacity());
447447
/// ```
448+
#[inline]
448449
pub fn new() -> Self {
449-
HeaderMap::try_with_capacity(0).unwrap()
450+
Self::default()
451+
}
452+
}
453+
454+
impl<T> Default for HeaderMap<T> {
455+
fn default() -> Self {
456+
HeaderMap {
457+
mask: 0,
458+
indices: Box::new([]), // as a ZST, this doesn't actually allocate anything
459+
entries: Vec::new(),
460+
extra_values: Vec::new(),
461+
danger: Danger::Green,
462+
}
450463
}
451464
}
452465

@@ -501,13 +514,7 @@ impl<T> HeaderMap<T> {
501514
/// ```
502515
pub fn try_with_capacity(capacity: usize) -> Result<HeaderMap<T>, MaxSizeReached> {
503516
if capacity == 0 {
504-
Ok(HeaderMap {
505-
mask: 0,
506-
indices: Box::new([]), // as a ZST, this doesn't actually allocate anything
507-
entries: Vec::new(),
508-
extra_values: Vec::new(),
509-
danger: Danger::Green,
510-
})
517+
Ok(Self::default())
511518
} else {
512519
let raw_cap = match to_raw_capacity(capacity).checked_next_power_of_two() {
513520
Some(c) => c,
@@ -2164,12 +2171,6 @@ impl<T: fmt::Debug> fmt::Debug for HeaderMap<T> {
21642171
}
21652172
}
21662173

2167-
impl<T> Default for HeaderMap<T> {
2168-
fn default() -> Self {
2169-
HeaderMap::try_with_capacity(0).expect("zero capacity should never fail")
2170-
}
2171-
}
2172-
21732174
impl<K, T> ops::Index<K> for HeaderMap<T>
21742175
where
21752176
K: AsHeaderName,

0 commit comments

Comments
 (0)