diff --git a/src/byte_str.rs b/src/byte_str.rs index dec222b5..181ced9e 100644 --- a/src/byte_str.rs +++ b/src/byte_str.rs @@ -43,7 +43,7 @@ impl ByteStr { } } // Invariant: assumed by the safety requirements of this function. - ByteStr { bytes: bytes } + ByteStr { bytes } } } diff --git a/src/extensions.rs b/src/extensions.rs index 18ba04c5..3764a558 100644 --- a/src/extensions.rs +++ b/src/extensions.rs @@ -61,7 +61,7 @@ impl Extensions { /// ``` pub fn insert(&mut self, val: T) -> Option { self.map - .get_or_insert_with(|| Box::new(HashMap::default())) + .get_or_insert_with(Box::default) .insert(TypeId::of::(), Box::new(val)) .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed)) } @@ -82,7 +82,7 @@ impl Extensions { self.map .as_ref() .and_then(|map| map.get(&TypeId::of::())) - .and_then(|boxed| (&**boxed).as_any().downcast_ref()) + .and_then(|boxed| (**boxed).as_any().downcast_ref()) } /// Get a mutable reference to a type previously inserted on this `Extensions`. @@ -101,7 +101,7 @@ impl Extensions { self.map .as_mut() .and_then(|map| map.get_mut(&TypeId::of::())) - .and_then(|boxed| (&mut **boxed).as_any_mut().downcast_mut()) + .and_then(|boxed| (**boxed).as_any_mut().downcast_mut()) } /// Get a mutable reference to a type, inserting `value` if not already present on this @@ -138,10 +138,10 @@ impl Extensions { ) -> &mut T { let out = self .map - .get_or_insert_with(|| Box::new(HashMap::default())) + .get_or_insert_with(Box::default) .entry(TypeId::of::()) .or_insert_with(|| Box::new(f())); - (&mut **out).as_any_mut().downcast_mut().unwrap() + (**out).as_any_mut().downcast_mut().unwrap() } /// Get a mutable reference to a type, inserting the type's default value if not already present diff --git a/src/header/map.rs b/src/header/map.rs index a0f6996f..fa56bedc 100644 --- a/src/header/map.rs +++ b/src/header/map.rs @@ -654,7 +654,7 @@ impl HeaderMap { assert!(cap <= MAX_SIZE, "header map reserve over max capacity"); assert!(cap != 0, "header map reserve overflowed"); - if self.entries.len() == 0 { + if self.entries.is_empty() { self.mask = cap as Size - 1; self.indices = vec![Pos::none(); cap].into_boxed_slice(); self.entries = Vec::with_capacity(usable_capacity(cap)); @@ -1092,22 +1092,22 @@ impl HeaderMap { danger, Entry::Vacant(VacantEntry { map: self, - hash: hash, + hash, key: key.into(), - probe: probe, - danger: danger, + probe, + danger, }), Entry::Occupied(OccupiedEntry { map: self, index: pos, - probe: probe, + probe, }), Entry::Vacant(VacantEntry { map: self, - hash: hash, + hash, key: key.into(), - probe: probe, - danger: danger, + probe, + danger, }) ) } @@ -1209,7 +1209,7 @@ impl HeaderMap { ValueDrain { first: Some(old), - next: next, + next, lt: PhantomData, } } @@ -1333,7 +1333,7 @@ impl HeaderMap { if danger || num_displaced >= DISPLACEMENT_THRESHOLD { // Increase danger level - self.danger.to_yellow(); + self.danger.set_yellow(); } index @@ -1415,7 +1415,7 @@ impl HeaderMap { // backward shift deletion in self.indices // after probe, shift all non-ideally placed indices backward - if self.entries.len() > 0 { + if !self.entries.is_empty() { let mut last_probe = probe; let mut probe = probe + 1; @@ -1462,9 +1462,9 @@ impl HeaderMap { assert!(self.entries.len() < MAX_SIZE, "header map at capacity"); self.entries.push(Bucket { - hash: hash, - key: key, - value: value, + hash, + key, + value, links: None, }); } @@ -1524,7 +1524,7 @@ impl HeaderMap { if load_factor >= LOAD_FACTOR_THRESHOLD { // Transition back to green danger level - self.danger.to_green(); + self.danger.set_green(); // Double the capacity let new_cap = self.indices.len() * 2; @@ -1532,7 +1532,7 @@ impl HeaderMap { // Grow the capacity self.grow(new_cap); } else { - self.danger.to_red(); + self.danger.set_red(); // Rebuild hash table for index in self.indices.iter_mut() { @@ -1855,7 +1855,7 @@ where type Error = Error; fn try_from(c: &'a HashMap) -> Result { - c.into_iter() + c.iter() .map(|(k, v)| -> crate::Result<(HeaderName, T)> { let name = TryFrom::try_from(k).map_err(Into::into)?; let value = TryFrom::try_from(v).map_err(Into::into)?; @@ -1992,7 +1992,7 @@ impl Default for HeaderMap { } } -impl<'a, K, T> ops::Index for HeaderMap +impl ops::Index for HeaderMap where K: AsHeaderName, { @@ -2042,7 +2042,7 @@ fn append_value( Some(links) => { let idx = extra.len(); extra.push(ExtraValue { - value: value, + value, prev: Link::Extra(links.tail), next: Link::Entry(entry_idx), }); @@ -2054,7 +2054,7 @@ fn append_value( None => { let idx = extra.len(); extra.push(ExtraValue { - value: value, + value, prev: Link::Entry(entry_idx), next: Link::Entry(entry_idx), }); @@ -2461,9 +2461,9 @@ impl<'a, T> VacantEntry<'a, T> { /// ``` pub fn insert(self, value: T) -> &'a mut T { // Ensure that there is space in the map - let index = - self.map - .insert_phase_two(self.key, value.into(), self.hash, self.probe, self.danger); + let index = self + .map + .insert_phase_two(self.key, value, self.hash, self.probe, self.danger); &mut self.map.entries[index].value } @@ -2488,13 +2488,13 @@ impl<'a, T> VacantEntry<'a, T> { /// ``` pub fn insert_entry(self, value: T) -> OccupiedEntry<'a, T> { // Ensure that there is space in the map - let index = - self.map - .insert_phase_two(self.key, value.into(), self.hash, self.probe, self.danger); + let index = self + .map + .insert_phase_two(self.key, value, self.hash, self.probe, self.danger); OccupiedEntry { map: self.map, - index: index, + index, probe: self.probe, } } @@ -2900,7 +2900,7 @@ impl<'a, T> OccupiedEntry<'a, T> { /// assert_eq!("earth", map["host"]); /// ``` pub fn insert(&mut self, value: T) -> T { - self.map.insert_occupied(self.index, value.into()) + self.map.insert_occupied(self.index, value) } /// Sets the value of the entry. @@ -2926,7 +2926,7 @@ impl<'a, T> OccupiedEntry<'a, T> { /// assert_eq!("earth", map["host"]); /// ``` pub fn insert_mult(&mut self, value: T) -> ValueDrain<'_, T> { - self.map.insert_occupied_mult(self.index, value.into()) + self.map.insert_occupied_mult(self.index, value) } /// Insert the value into the entry. @@ -2953,7 +2953,7 @@ impl<'a, T> OccupiedEntry<'a, T> { pub fn append(&mut self, value: T) { let idx = self.index; let entry = &mut self.map.entries[idx]; - append_value(idx, entry, &mut self.map.extra_values, value.into()); + append_value(idx, entry, &mut self.map.extra_values, value); } /// Remove the entry from the map. @@ -3131,12 +3131,12 @@ impl<'a, T> Iterator for ValueDrain<'a, T> { // Exactly 1 (&Some(_), &None) => (1, Some(1)), // 1 + extras - (&Some(_), &Some(ref extras)) => { + (&Some(_), Some(extras)) => { let (l, u) = extras.size_hint(); (l + 1, u.map(|u| u + 1)) } // Extras only - (&None, &Some(ref extras)) => extras.size_hint(), + (&None, Some(extras)) => extras.size_hint(), // No more (&None, &None) => (0, Some(0)), } @@ -3147,7 +3147,7 @@ impl<'a, T> FusedIterator for ValueDrain<'a, T> {} impl<'a, T> Drop for ValueDrain<'a, T> { fn drop(&mut self) { - while let Some(_) = self.next() {} + for _ in self.by_ref() {} } } @@ -3186,7 +3186,7 @@ impl Pos { debug_assert!(index < MAX_SIZE); Pos { index: index as Size, - hash: hash, + hash, } } @@ -3220,34 +3220,25 @@ impl Pos { impl Danger { fn is_red(&self) -> bool { - match *self { - Danger::Red(_) => true, - _ => false, - } + matches!(*self, Danger::Red(_)) } - fn to_red(&mut self) { + fn set_red(&mut self) { debug_assert!(self.is_yellow()); *self = Danger::Red(RandomState::new()); } fn is_yellow(&self) -> bool { - match *self { - Danger::Yellow => true, - _ => false, - } + matches!(*self, Danger::Yellow) } - fn to_yellow(&mut self) { - match *self { - Danger::Green => { - *self = Danger::Yellow; - } - _ => {} + fn set_yellow(&mut self) { + if let Danger::Green = *self { + *self = Danger::Yellow; } } - fn to_green(&mut self) { + fn set_green(&mut self) { debug_assert!(self.is_yellow()); *self = Danger::Green; } @@ -3456,7 +3447,7 @@ mod as_header_name { } fn as_str(&self) -> &str { - ::as_str(*self) + ::as_str(self) } } @@ -3510,7 +3501,7 @@ mod as_header_name { } fn as_str(&self) -> &str { - *self + self } } diff --git a/src/header/name.rs b/src/header/name.rs index ecf0ad23..e00e229d 100644 --- a/src/header/name.rs +++ b/src/header/name.rs @@ -1258,7 +1258,7 @@ impl HeaderName { }; } - if name_bytes.len() == 0 || name_bytes.len() > super::MAX_HEADER_NAME_LEN || { + if name_bytes.is_empty() || name_bytes.len() > super::MAX_HEADER_NAME_LEN || { let mut i = 0; loop { if i >= name_bytes.len() { @@ -1269,6 +1269,12 @@ impl HeaderName { i += 1; } } { + // TODO: When msrv is bumped to larger than 1.57, this should be + // replaced with `panic!` macro. + // https://blog.rust-lang.org/2021/12/02/Rust-1.57.0.html#panic-in-const-contexts + // + // See the panics section of this method's document for details. + #[allow(clippy::no_effect)] ([] as [u8; 0])[0]; // Invalid header name } @@ -1284,7 +1290,7 @@ impl HeaderName { pub fn as_str(&self) -> &str { match self.inner { Repr::Standard(v) => v.as_str(), - Repr::Custom(ref v) => &*v.0, + Repr::Custom(ref v) => &v.0, } } @@ -1516,10 +1522,7 @@ impl<'a> HdrName<'a> { fn custom(buf: &'a [u8], lower: bool) -> HdrName<'a> { HdrName { // Invariant (on MaybeLower): follows from the precondition - inner: Repr::Custom(MaybeLower { - buf: buf, - lower: lower, - }), + inner: Repr::Custom(MaybeLower { buf, lower }), } } @@ -1554,7 +1557,7 @@ impl<'a> From> for HeaderName { }, Repr::Custom(maybe_lower) => { if maybe_lower.lower { - let buf = Bytes::copy_from_slice(&maybe_lower.buf[..]); + let buf = Bytes::copy_from_slice(maybe_lower.buf); // Safety: the invariant on MaybeLower ensures buf is valid UTF-8. let byte_str = unsafe { ByteStr::from_utf8_unchecked(buf) }; diff --git a/src/header/value.rs b/src/header/value.rs index 1260074e..b7978cac 100644 --- a/src/header/value.rs +++ b/src/header/value.rs @@ -3,6 +3,7 @@ use bytes::{Bytes, BytesMut}; use std::convert::TryFrom; use std::error::Error; use std::fmt::Write; +use std::hash::{Hash, Hasher}; use std::str::FromStr; use std::{cmp, fmt, mem, str}; @@ -17,7 +18,7 @@ use crate::header::name::HeaderName; /// To handle this, the `HeaderValue` is useable as a type and can be compared /// with strings and implements `Debug`. A `to_str` fn is provided that returns /// an `Err` if the header value contains non visible ascii characters. -#[derive(Clone, Hash)] +#[derive(Clone)] pub struct HeaderValue { inner: Bytes, is_sensitive: bool, @@ -85,6 +86,12 @@ impl HeaderValue { let mut i = 0; while i < bytes.len() { if !is_visible_ascii(bytes[i]) { + // TODO: When msrv is bumped to larger than 1.57, this should be + // replaced with `panic!` macro. + // https://blog.rust-lang.org/2021/12/02/Rust-1.57.0.html#panic-in-const-contexts + // + // See the panics section of this method's document for details. + #[allow(clippy::no_effect)] ([] as [u8; 0])[0]; // Invalid header value } i += 1; @@ -122,6 +129,7 @@ impl HeaderValue { /// assert!(val.is_err()); /// ``` #[inline] + #[allow(clippy::should_implement_trait)] pub fn from_str(src: &str) -> Result { HeaderValue::try_from_generic(src, |s| Bytes::copy_from_slice(s.as_bytes())) } @@ -191,6 +199,13 @@ impl HeaderValue { /// /// This function does NOT validate that illegal bytes are not contained /// within the buffer. + /// + /// ## Panics + /// In a debug build this will panic if `src` is not valid UTF-8. + /// + /// ## Safety + /// `src` must contain valid UTF-8. In a release build it is undefined + /// behaviour to call this with `src` that is not valid UTF-8. pub unsafe fn from_maybe_shared_unchecked(src: T) -> HeaderValue where T: AsRef<[u8]> + 'static, @@ -617,6 +632,12 @@ impl Error for ToStrError {} // ===== PartialEq / PartialOrd ===== +impl Hash for HeaderValue { + fn hash(&self, state: &mut H) { + self.inner.hash(state); + } +} + impl PartialEq for HeaderValue { #[inline] fn eq(&self, other: &HeaderValue) -> bool { @@ -629,7 +650,7 @@ impl Eq for HeaderValue {} impl PartialOrd for HeaderValue { #[inline] fn partial_cmp(&self, other: &HeaderValue) -> Option { - self.inner.partial_cmp(&other.inner) + Some(self.cmp(other)) } } @@ -699,7 +720,7 @@ impl PartialOrd for [u8] { impl PartialEq for HeaderValue { #[inline] fn eq(&self, other: &String) -> bool { - *self == &other[..] + *self == other[..] } } diff --git a/src/method.rs b/src/method.rs index 88a6813f..2d44085f 100644 --- a/src/method.rs +++ b/src/method.rs @@ -147,10 +147,7 @@ impl Method { /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.1) /// for more words. pub fn is_safe(&self) -> bool { - match self.0 { - Get | Head | Options | Trace => true, - _ => false, - } + matches!(self.0, Get | Head | Options | Trace) } /// Whether a method is considered "idempotent", meaning the request has @@ -468,6 +465,6 @@ mod test { assert_eq!(Method::from_str("wOw!!").unwrap(), "wOw!!"); let long_method = "This_is_a_very_long_method.It_is_valid_but_unlikely."; - assert_eq!(Method::from_str(&long_method).unwrap(), long_method); + assert_eq!(Method::from_str(long_method).unwrap(), long_method); } } diff --git a/src/request.rs b/src/request.rs index d53188bb..293c598c 100644 --- a/src/request.rs +++ b/src/request.rs @@ -434,7 +434,7 @@ impl Request { pub fn new(body: T) -> Request { Request { head: Parts::new(), - body: body, + body, } } @@ -452,10 +452,7 @@ impl Request { /// ``` #[inline] pub fn from_parts(parts: Parts, body: T) -> Request { - Request { - head: parts, - body: body, - } + Request { head: parts, body } } /// Returns a reference to the associated HTTP method. diff --git a/src/response.rs b/src/response.rs index c2ba6222..0cc925ce 100644 --- a/src/response.rs +++ b/src/response.rs @@ -253,7 +253,7 @@ impl Response { pub fn new(body: T) -> Response { Response { head: Parts::new(), - body: body, + body, } } @@ -274,10 +274,7 @@ impl Response { /// ``` #[inline] pub fn from_parts(parts: Parts, body: T) -> Response { - Response { - head: parts, - body: body, - } + Response { head: parts, body } } /// Returns the `StatusCode`. diff --git a/src/status.rs b/src/status.rs index 8d9d5870..1f619ee1 100644 --- a/src/status.rs +++ b/src/status.rs @@ -71,7 +71,7 @@ impl StatusCode { /// ``` #[inline] pub fn from_u16(src: u16) -> Result { - if src < 100 || src >= 1000 { + if !(100..1000).contains(&src) { return Err(InvalidStatusCode::new()); } @@ -267,7 +267,7 @@ impl FromStr for StatusCode { impl<'a> From<&'a StatusCode> for StatusCode { #[inline] fn from(t: &'a StatusCode) -> Self { - t.clone() + t.to_owned() } } @@ -542,7 +542,7 @@ impl Error for InvalidStatusCode {} // A string of packed 3-ASCII-digit status code values for the supported range // of [100, 999] (900 codes, 2700 bytes). -const CODE_DIGITS: &'static str = "\ +const CODE_DIGITS: &str = "\ 100101102103104105106107108109110111112113114115116117118119\ 120121122123124125126127128129130131132133134135136137138139\ 140141142143144145146147148149150151152153154155156157158159\ diff --git a/src/uri/authority.rs b/src/uri/authority.rs index f41ddd19..dab6dcd0 100644 --- a/src/uri/authority.rs +++ b/src/uri/authority.rs @@ -238,7 +238,7 @@ impl Authority { pub fn port(&self) -> Option> { let bytes = self.as_str(); bytes - .rfind(":") + .rfind(':') .and_then(|i| Port::from_str(&bytes[i + 1..]).ok()) } @@ -253,7 +253,7 @@ impl Authority { /// assert_eq!(authority.port_u16(), Some(80)); /// ``` pub fn port_u16(&self) -> Option { - self.port().and_then(|p| Some(p.as_u16())) + self.port().map(|p| p.as_u16()) } /// Return a str representation of the authority @@ -434,7 +434,7 @@ impl<'a> TryFrom<&'a [u8]> for Authority { // Preconditon on create_authority: copy_from_slice() copies all of // bytes from the [u8] parameter into a new Bytes - create_authority(s, |s| Bytes::copy_from_slice(s)) + create_authority(s, Bytes::copy_from_slice) } } @@ -486,7 +486,7 @@ impl fmt::Display for Authority { fn host(auth: &str) -> &str { let host_port = auth - .rsplitn(2, '@') + .rsplit('@') .next() .expect("split always has at least 1 item"); diff --git a/src/uri/mod.rs b/src/uri/mod.rs index 806fbc20..6ef2dc8e 100644 --- a/src/uri/mod.rs +++ b/src/uri/mod.rs @@ -245,10 +245,8 @@ impl Uri { if src.path_and_query.is_none() { return Err(ErrorKind::PathAndQueryMissing.into()); } - } else { - if src.authority.is_some() && src.path_and_query.is_some() { - return Err(ErrorKind::SchemeMissing.into()); - } + } else if src.authority.is_some() && src.path_and_query.is_some() { + return Err(ErrorKind::SchemeMissing.into()); } let scheme = match src.scheme { @@ -269,9 +267,9 @@ impl Uri { }; Ok(Uri { - scheme: scheme, - authority: authority, - path_and_query: path_and_query, + scheme, + authority, + path_and_query, }) } @@ -322,7 +320,7 @@ impl Uri { return Ok(Uri { scheme: Scheme::empty(), - authority: authority, + authority, path_and_query: PathAndQuery::empty(), }); } @@ -651,7 +649,7 @@ impl Uri { /// assert_eq!(uri.port_u16(), Some(80)); /// ``` pub fn port_u16(&self) -> Option { - self.port().and_then(|p| Some(p.as_u16())) + self.port().map(|p| p.as_u16()) } /// Get the query string of this `Uri`, starting after the `?`. @@ -743,7 +741,7 @@ impl TryFrom for Uri { } } -impl<'a> TryFrom> for Uri { +impl TryFrom> for Uri { type Error = InvalidUri; #[inline] @@ -813,9 +811,9 @@ impl From for Parts { }; Parts { - scheme: scheme, - authority: authority, - path_and_query: path_and_query, + scheme, + authority, + path_and_query, _priv: (), } } @@ -859,7 +857,7 @@ fn parse_full(mut s: Bytes) -> Result { return Ok(Uri { scheme: scheme.into(), - authority: authority, + authority, path_and_query: PathAndQuery::empty(), }); } @@ -876,7 +874,7 @@ fn parse_full(mut s: Bytes) -> Result { Ok(Uri { scheme: scheme.into(), - authority: authority, + authority, path_and_query: PathAndQuery::from_shared(s)?, }) } @@ -966,8 +964,8 @@ impl PartialEq for Uri { } if let Some(query) = self.query() { - if other.len() == 0 { - return query.len() == 0; + if other.is_empty() { + return query.is_empty(); } if other[0] != b'?' { diff --git a/src/uri/path.rs b/src/uri/path.rs index a3f229f5..341ba2e6 100644 --- a/src/uri/path.rs +++ b/src/uri/path.rs @@ -101,7 +101,7 @@ impl PathAndQuery { Ok(PathAndQuery { data: unsafe { ByteStr::from_utf8_unchecked(src) }, - query: query, + query, }) } @@ -294,7 +294,7 @@ impl<'a> TryFrom<&'a str> for PathAndQuery { } } -impl<'a> TryFrom> for PathAndQuery { +impl TryFrom> for PathAndQuery { type Error = InvalidUri; #[inline] fn try_from(vec: Vec) -> Result { diff --git a/src/uri/scheme.rs b/src/uri/scheme.rs index bd23c043..c33ec41a 100644 --- a/src/uri/scheme.rs +++ b/src/uri/scheme.rs @@ -132,7 +132,7 @@ impl PartialEq for Scheme { match (&self.inner, &other.inner) { (&Standard(Http), &Standard(Http)) => true, (&Standard(Https), &Standard(Https)) => true, - (&Other(ref a), &Other(ref b)) => a.eq_ignore_ascii_case(b), + (Other(a), Other(b)) => a.eq_ignore_ascii_case(b), (&None, _) | (_, &None) => unreachable!(), _ => false, } @@ -185,10 +185,7 @@ impl Hash for Scheme { impl Scheme2 { pub(super) fn is_none(&self) -> bool { - match *self { - Scheme2::None => true, - _ => false, - } + matches!(*self, Scheme2::None) } } diff --git a/tests/header_map_fuzz.rs b/tests/header_map_fuzz.rs index ed80986e..40db0494 100644 --- a/tests/header_map_fuzz.rs +++ b/tests/header_map_fuzz.rs @@ -89,8 +89,8 @@ impl Fuzz { } Fuzz { - seed: seed, - steps: steps, + seed, + steps, reduce: 0, } } @@ -121,7 +121,7 @@ impl AltMap { let action = self.gen_action(weight, rng); Step { - action: action, + action, expect: self.clone(), } } @@ -156,21 +156,14 @@ impl AltMap { let val = gen_header_value(rng); let old = self.insert(name.clone(), val.clone()); - Action::Insert { - name: name, - val: val, - old: old, - } + Action::Insert { name, val, old } } fn gen_remove(&mut self, rng: &mut StdRng) -> Action { let name = self.gen_name(-4, rng); let val = self.remove(&name); - Action::Remove { - name: name, - val: val, - } + Action::Remove { name, val } } fn gen_append(&mut self, rng: &mut StdRng) -> Action { @@ -182,11 +175,7 @@ impl AltMap { let ret = !vals.is_empty(); vals.push(val.clone()); - Action::Append { - name: name, - val: val, - ret: ret, - } + Action::Append { name, val, ret } } /// Negative numbers weigh finding an existing header higher