From 4bd9746a0fa56ddc578ec5a8044e6c37390f3770 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 24 Jul 2017 15:22:58 -0700 Subject: [PATCH] fix(header): fix panic from headers.remove when typed doesn't match --- src/header/internals/item.rs | 32 +++++++++++++------------------- src/header/mod.rs | 6 ++++++ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs index b150cd3907..2e19beb943 100644 --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -57,13 +57,10 @@ impl Item { match self.typed.get(tid) { Some(val) => Some(val), None => { - match parse::(self.raw.as_ref().expect("item.raw must exist")) { - Ok(typed) => { - unsafe { self.typed.insert(tid, typed); } - self.typed.get(tid) - }, - Err(_) => None - } + parse::(self.raw.as_ref().expect("item.raw must exist")).and_then(|typed| { + unsafe { self.typed.insert(tid, typed); } + self.typed.get(tid) + }) } }.map(|typed| unsafe { typed.downcast_ref_unchecked() }) } @@ -71,12 +68,9 @@ impl Item { pub fn typed_mut(&mut self) -> Option<&mut H> { let tid = TypeId::of::(); if self.typed.get_mut(tid).is_none() { - match parse::(self.raw.as_ref().expect("item.raw must exist")) { - Ok(typed) => { - unsafe { self.typed.insert(tid, typed); } - }, - Err(_) => () - } + parse::(self.raw.as_ref().expect("item.raw must exist")).map(|typed| { + unsafe { self.typed.insert(tid, typed); } + }); } if self.raw.is_some() && self.typed.get_mut(tid).is_some() { self.raw = OptCell::new(None); @@ -86,10 +80,10 @@ impl Item { pub fn into_typed(self) -> Option { let tid = TypeId::of::(); - match self.typed.into_value(tid) { - Some(val) => Some(val), - None => parse::(self.raw.as_ref().expect("item.raw must exist")).ok() - }.map(|typed| unsafe { typed.downcast_unchecked() }) + let Item { typed, raw } = self; + typed.into_value(tid) + .or_else(|| raw.as_ref().and_then(parse::)) + .map(|typed| unsafe { typed.downcast_unchecked() }) } pub fn write_h1(&self, f: &mut Formatter) -> fmt::Result { @@ -117,9 +111,9 @@ impl Item { } #[inline] -fn parse(raw: &Raw) -> ::Result> { +fn parse(raw: &Raw) -> Option> { H::parse_header(raw).map(|h| { let h: Box
= Box::new(h); h - }) + }).ok() } diff --git a/src/header/mod.rs b/src/header/mod.rs index 27b661721c..bee26f22c6 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -863,6 +863,12 @@ mod tests { let mut headers = Headers::new(); headers.set(ContentLength(10)); assert_eq!(headers.remove(), Some(ContentLength(10))); + assert_eq!(headers.len(), 0); + + headers.set(ContentLength(9)); + assert_eq!(headers.len(), 1); + assert!(headers.remove::().is_none()); + assert_eq!(headers.len(), 0); } #[test]