diff --git a/src/byte_str.rs b/src/byte_str.rs index e83ff75d..c5d256b7 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/convert.rs b/src/convert.rs index aeee2219..682e0ed5 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -1,5 +1,5 @@ macro_rules! if_downcast_into { - ($in_ty:ty, $out_ty:ty, $val:ident, $body:expr) => ({ + ($in_ty:ty, $out_ty:ty, $val:ident, $body:expr) => {{ if std::any::TypeId::of::<$in_ty>() == std::any::TypeId::of::<$out_ty>() { // Store the value in an `Option` so we can `take` // it after casting to `&mut dyn Any`. @@ -13,5 +13,5 @@ macro_rules! if_downcast_into { // Run the $body in scope of the replaced val. $body } - }) + }}; } diff --git a/src/extensions.rs b/src/extensions.rs index 7e815df7..7c6e1503 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(Default::default) .insert(TypeId::of::(), Box::new(val)) .and_then(|boxed| { (boxed as Box) @@ -166,9 +166,7 @@ impl Extensions { /// ``` #[inline] pub fn is_empty(&self) -> bool { - self.map - .as_ref() - .map_or(true, |map| map.is_empty()) + self.map.as_ref().map_or(true, |map| map.is_empty()) } /// Get the numer of extensions available. @@ -184,28 +182,26 @@ impl Extensions { /// ``` #[inline] pub fn len(&self) -> usize { - self.map - .as_ref() - .map_or(0, |map| map.len()) + self.map.as_ref().map_or(0, |map| map.len()) } /// Extends `self` with another `Extensions`. /// /// If an instance of a specific type exists in both, the one in `self` is overwritten with the /// one from `other`. - /// + /// /// # Example - /// + /// /// ``` /// # use http::Extensions; /// let mut ext_a = Extensions::new(); /// ext_a.insert(8u8); /// ext_a.insert(16u16); - /// + /// /// let mut ext_b = Extensions::new(); /// ext_b.insert(4u8); /// ext_b.insert("hello"); - /// + /// /// ext_a.extend(ext_b); /// assert_eq!(ext_a.len(), 3); /// assert_eq!(ext_a.get::(), Some(&4u8)); diff --git a/src/header/map.rs b/src/header/map.rs index 13cbc3a3..cad04320 100644 --- a/src/header/map.rs +++ b/src/header/map.rs @@ -1,5 +1,5 @@ -use std::collections::HashMap; use std::collections::hash_map::RandomState; +use std::collections::HashMap; use std::convert::TryFrom; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::{FromIterator, FusedIterator}; @@ -8,8 +8,8 @@ use std::{fmt, mem, ops, ptr, vec}; use crate::Error; -use super::HeaderValue; use super::name::{HdrName, HeaderName, InvalidHeaderName}; +use super::HeaderValue; pub use self::as_header_name::AsHeaderName; pub use self::into_header_name::IntoHeaderName; @@ -224,7 +224,7 @@ enum Cursor { /// limit enables using `u16` to represent all offsets, which takes 2 bytes /// instead of 8 on 64 bit processors. /// -/// Setting this limit is especially benificial for `indices`, making it more +/// Setting this limit is especially beneficial for `indices`, making it more /// cache friendly. More hash codes can fit in a cache line. /// /// You may notice that `u16` may represent more than 32,768 values. This is @@ -640,9 +640,9 @@ impl HeaderMap { if cap > self.indices.len() { let cap = cap.next_power_of_two(); assert!(cap <= MAX_SIZE, "header map reserve over max capacity"); - assert!(cap != 0, "header map reserve overflowed"); + assert_ne!(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)); @@ -961,7 +961,9 @@ impl HeaderMap { let entries = &mut self.entries[..] as *mut _; let extra_values = &mut self.extra_values as *mut _; let len = self.entries.len(); - unsafe { self.entries.set_len(0); } + unsafe { + self.entries.set_len(0); + } Drain { idx: 0, @@ -992,7 +994,7 @@ impl HeaderMap { } else { ValueIter { map: self, - index: ::std::usize::MAX, + index: usize::MAX, front: None, back: None, } @@ -1081,22 +1083,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, }) ) } @@ -1152,7 +1154,7 @@ impl HeaderMap { danger, // Vacant { - drop(danger); // Make lint happy + let _ = danger; // Make lint happy let index = self.entries.len(); self.insert_entry(hash, key.into(), value); self.indices[probe] = Pos::new(index, hash); @@ -1193,14 +1195,12 @@ impl HeaderMap { let raw_links = self.raw_links(); let extra_values = &mut self.extra_values; - let next = links.map(|l| { - drain_all_extra_values(raw_links, extra_values, l.next) - .into_iter() - }); + let next = + links.map(|l| drain_all_extra_values(raw_links, extra_values, l.next).into_iter()); ValueDrain { first: Some(old), - next: next, + next, lt: PhantomData, } } @@ -1255,7 +1255,7 @@ impl HeaderMap { danger, // Vacant { - drop(danger); + let _ = danger; let index = self.entries.len(); self.insert_entry(hash, key.into(), value); self.indices[probe] = Pos::new(index, hash); @@ -1406,7 +1406,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; @@ -1453,9 +1453,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, }); } @@ -1595,9 +1595,8 @@ impl HeaderMap { fn remove_extra_value( mut raw_links: RawLinks, extra_values: &mut Vec>, - idx: usize) - -> ExtraValue -{ + idx: usize, +) -> ExtraValue { let prev; let next; @@ -1618,8 +1617,7 @@ fn remove_extra_value( (Link::Entry(prev), Link::Extra(next)) => { debug_assert!(raw_links[prev].is_some()); - raw_links[prev].as_mut().unwrap() - .next = next; + raw_links[prev].as_mut().unwrap().next = next; debug_assert!(extra_values.len() > next); extra_values[next].prev = Link::Entry(prev); @@ -1627,8 +1625,7 @@ fn remove_extra_value( (Link::Extra(prev), Link::Entry(next)) => { debug_assert!(raw_links[next].is_some()); - raw_links[next].as_mut().unwrap() - .tail = prev; + raw_links[next].as_mut().unwrap().tail = prev; debug_assert!(extra_values.len() > prev); extra_values[prev].next = Link::Entry(next); @@ -1703,8 +1700,8 @@ fn remove_extra_value( debug_assert!({ for v in &*extra_values { - assert!(v.next != Link::Extra(old_idx)); - assert!(v.prev != Link::Extra(old_idx)); + assert_ne!(v.next, Link::Extra(old_idx)); + assert_ne!(v.prev, Link::Extra(old_idx)); } true @@ -1716,9 +1713,8 @@ fn remove_extra_value( fn drain_all_extra_values( raw_links: RawLinks, extra_values: &mut Vec>, - mut head: usize) - -> Vec -{ + mut head: usize, +) -> Vec { let mut vec = Vec::new(); loop { let extra = remove_extra_value(raw_links, extra_values, head); @@ -1840,17 +1836,17 @@ impl FromIterator<(HeaderName, T)> for HeaderMap { /// assert_eq!(headers["X-Custom-Header"], "my value"); /// ``` impl<'a, K, V, T> TryFrom<&'a HashMap> for HeaderMap - where - K: Eq + Hash, - HeaderName: TryFrom<&'a K>, - >::Error: Into, - T: TryFrom<&'a V>, - T::Error: Into, +where + K: Eq + Hash, + HeaderName: TryFrom<&'a K>, + >::Error: Into, + T: TryFrom<&'a V>, + T::Error: Into, { 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)?; @@ -1987,7 +1983,7 @@ impl Default for HeaderMap { } } -impl<'a, K, T> ops::Index for HeaderMap +impl ops::Index for HeaderMap where K: AsHeaderName, { @@ -2037,7 +2033,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), }); @@ -2049,7 +2045,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), }); @@ -2204,9 +2200,7 @@ impl<'a, T> Iterator for Drain<'a, T> { // Remove the extra value let raw_links = RawLinks(self.entries); - let extra = unsafe { - remove_extra_value(raw_links, &mut *self.extra_values, next) - }; + let extra = unsafe { remove_extra_value(raw_links, &mut *self.extra_values, next) }; match extra.next { Link::Extra(idx) => self.next = Some(idx), @@ -2412,9 +2406,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 } @@ -2439,13 +2433,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, } } @@ -2851,7 +2845,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. @@ -2877,7 +2871,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. @@ -2904,7 +2898,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. @@ -2969,10 +2963,9 @@ impl<'a, T> OccupiedEntry<'a, T> { let raw_links = self.map.raw_links(); let extra_values = &mut self.map.extra_values; - let next = self.map.entries[self.index].links.map(|l| { - drain_all_extra_values(raw_links, extra_values, l.next) - .into_iter() - }); + let next = self.map.entries[self.index] + .links + .map(|l| drain_all_extra_values(raw_links, extra_values, l.next).into_iter()); let entry = self.map.remove_found(self.probe, self.index); @@ -3083,12 +3076,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)), } @@ -3099,7 +3092,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() {} } } @@ -3120,17 +3113,13 @@ impl ops::Index for RawLinks { type Output = Option; fn index(&self, idx: usize) -> &Self::Output { - unsafe { - &(*self.0)[idx].links - } + unsafe { &(*self.0)[idx].links } } } impl ops::IndexMut for RawLinks { fn index_mut(&mut self, idx: usize) -> &mut Self::Output { - unsafe { - &mut (*self.0)[idx].links - } + unsafe { &mut (*self.0)[idx].links } } } @@ -3142,7 +3131,7 @@ impl Pos { debug_assert!(index < MAX_SIZE); Pos { index: index as Size, - hash: hash, + hash, } } @@ -3176,10 +3165,7 @@ impl Pos { impl Danger { fn is_red(&self) -> bool { - match *self { - Danger::Red(_) => true, - _ => false, - } + matches!(self, Danger::Red(_)) } fn to_red(&mut self) { @@ -3188,18 +3174,12 @@ impl Danger { } 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; - } - _ => {} + if matches!(self, Danger::Green) { + *self = Danger::Yellow; } } @@ -3406,7 +3386,7 @@ mod as_header_name { } fn as_str(&self) -> &str { - ::as_str(*self) + ::as_str(self) } } @@ -3460,7 +3440,7 @@ mod as_header_name { } fn as_str(&self) -> &str { - *self + self } } diff --git a/src/header/mod.rs b/src/header/mod.rs index 1ca49450..0c55bffe 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -82,6 +82,7 @@ pub use self::name::{HeaderName, InvalidHeaderName}; pub use self::value::{HeaderValue, InvalidHeaderValue, ToStrError}; // Use header name constants +#[rustfmt::skip] pub use self::name::{ ACCEPT, ACCEPT_CHARSET, diff --git a/src/header/name.rs b/src/header/name.rs index 6080cf08..ebd52129 100644 --- a/src/header/name.rs +++ b/src/header/name.rs @@ -2,12 +2,12 @@ use crate::byte_str::ByteStr; use bytes::{Bytes, BytesMut}; use std::borrow::Borrow; +use std::convert::TryFrom; use std::error::Error; -use std::convert::{TryFrom}; +use std::fmt; use std::hash::{Hash, Hasher}; use std::mem::MaybeUninit; use std::str::FromStr; -use std::fmt; /// Represents an HTTP header field name /// @@ -1002,6 +1002,7 @@ standard_headers! { /// ``` // HEADER_CHARS maps every byte that is 128 or larger to 0 so everything that is // mapped by HEADER_CHARS, maps to a valid single-byte UTF-8 codepoint. +#[rustfmt::skip] const HEADER_CHARS: [u8; 256] = [ // 0 1 2 3 4 5 6 7 8 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x @@ -1035,6 +1036,7 @@ const HEADER_CHARS: [u8; 256] = [ /// Valid header name characters for HTTP/2.0 and HTTP/3.0 // HEADER_CHARS_H2 maps every byte that is 128 or larger to 0 so everything that is // mapped by HEADER_CHARS_H2, maps to a valid single-byte UTF-8 codepoint. +#[rustfmt::skip] const HEADER_CHARS_H2: [u8; 256] = [ // 0 1 2 3 4 5 6 7 8 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x @@ -1095,11 +1097,11 @@ fn parse_hdr<'a>( } } - - impl<'a> From for HdrName<'a> { fn from(hdr: StandardHeader) -> HdrName<'a> { - HdrName { inner: Repr::Standard(hdr) } + HdrName { + inner: Repr::Standard(hdr), + } } } @@ -1119,7 +1121,7 @@ impl HeaderName { Ok(Custom(val).into()) } Repr::Custom(MaybeLower { buf, lower: false }) => { - use bytes::{BufMut}; + use bytes::BufMut; let mut dst = BytesMut::with_capacity(buf.len()); for b in buf.iter() { @@ -1251,12 +1253,12 @@ impl HeaderName { pub const fn from_static(src: &'static str) -> HeaderName { let name_bytes = src.as_bytes(); if let Some(standard) = StandardHeader::from_bytes(name_bytes) { - return HeaderName{ + return HeaderName { inner: Repr::Standard(standard), }; } - 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() { @@ -1271,7 +1273,7 @@ impl HeaderName { } HeaderName { - inner: Repr::Custom(Custom(ByteStr::from_static(src))) + inner: Repr::Custom(Custom(ByteStr::from_static(src))), } } @@ -1282,7 +1284,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, } } @@ -1514,15 +1516,13 @@ 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 }), } } pub fn from_bytes(hdr: &[u8], f: F) -> Result - where F: FnOnce(HdrName<'_>) -> U, + where + F: FnOnce(HdrName<'_>) -> U, { let mut buf = uninit_u8_array(); // Precondition: HEADER_CHARS is a valid table for parse_hdr(). @@ -1551,7 +1551,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) }; @@ -1636,9 +1636,10 @@ fn eq_ignore_ascii_case(lower: &[u8], s: &[u8]) -> bool { return false; } - lower.iter().zip(s).all(|(a, b)| { - *a == HEADER_CHARS[*b as usize] - }) + lower + .iter() + .zip(s) + .all(|(a, b)| *a == HEADER_CHARS[*b as usize]) } // Utility functions for MaybeUninit<>. These are drawn from unstable API's on @@ -1649,13 +1650,13 @@ const SCRATCH_BUF_OVERFLOW: usize = SCRATCH_BUF_SIZE + 1; fn uninit_u8_array() -> [MaybeUninit; SCRATCH_BUF_SIZE] { let arr = MaybeUninit::<[MaybeUninit; SCRATCH_BUF_SIZE]>::uninit(); // Safety: assume_init() is claiming that an array of MaybeUninit<> - // has been initilized, but MaybeUninit<>'s do not require initilizaton. + // has been initialized, but MaybeUninit<>'s do not require initialization. unsafe { arr.assume_init() } } -// Assuming all the elements are initilized, get a slice of them. +// Assuming all the elements are initialized, get a slice of them. // -// Safety: All elements of `slice` must be initilized to prevent +// Safety: All elements of `slice` must be initialized to prevent // undefined behavior. unsafe fn slice_assume_init(slice: &[MaybeUninit]) -> &[T] { &*(slice as *const [MaybeUninit] as *const [T]) @@ -1663,8 +1664,8 @@ unsafe fn slice_assume_init(slice: &[MaybeUninit]) -> &[T] { #[cfg(test)] mod tests { - use super::*; use self::StandardHeader::Vary; + use super::*; #[test] fn test_bounds() { @@ -1676,11 +1677,15 @@ mod tests { fn test_parse_invalid_headers() { for i in 0..128 { let hdr = vec![1u8; i]; - assert!(HeaderName::from_bytes(&hdr).is_err(), "{} invalid header chars did not fail", i); + assert!( + HeaderName::from_bytes(&hdr).is_err(), + "{} invalid header chars did not fail", + i + ); } } - const ONE_TOO_LONG: &[u8] = &[b'a'; super::super::MAX_HEADER_NAME_LEN+1]; + const ONE_TOO_LONG: &[u8] = &[b'a'; super::super::MAX_HEADER_NAME_LEN + 1]; #[test] fn test_invalid_name_lengths() { @@ -1728,7 +1733,10 @@ mod tests { }), }); - assert_eq!(name.inner, Repr::Custom(Custom(ByteStr::from_static("hello-world")))); + assert_eq!( + name.inner, + Repr::Custom(Custom(ByteStr::from_static("hello-world"))) + ); let name = HeaderName::from(HdrName { inner: Repr::Custom(MaybeLower { @@ -1737,49 +1745,68 @@ mod tests { }), }); - assert_eq!(name.inner, Repr::Custom(Custom(ByteStr::from_static("hello-world")))); + assert_eq!( + name.inner, + Repr::Custom(Custom(ByteStr::from_static("hello-world"))) + ); } #[test] fn test_eq_hdr_name() { use self::StandardHeader::Vary; - let a = HeaderName { inner: Repr::Standard(Vary) }; - let b = HdrName { inner: Repr::Standard(Vary) }; + let a = HeaderName { + inner: Repr::Standard(Vary), + }; + let b = HdrName { + inner: Repr::Standard(Vary), + }; assert_eq!(a, b); - let a = HeaderName { inner: Repr::Custom(Custom(ByteStr::from_static("vaary"))) }; + let a = HeaderName { + inner: Repr::Custom(Custom(ByteStr::from_static("vaary"))), + }; assert_ne!(a, b); - let b = HdrName { inner: Repr::Custom(MaybeLower { - buf: b"vaary", - lower: true, - })}; + let b = HdrName { + inner: Repr::Custom(MaybeLower { + buf: b"vaary", + lower: true, + }), + }; assert_eq!(a, b); - let b = HdrName { inner: Repr::Custom(MaybeLower { - buf: b"vaary", - lower: false, - })}; + let b = HdrName { + inner: Repr::Custom(MaybeLower { + buf: b"vaary", + lower: false, + }), + }; assert_eq!(a, b); - let b = HdrName { inner: Repr::Custom(MaybeLower { - buf: b"VAARY", - lower: false, - })}; + let b = HdrName { + inner: Repr::Custom(MaybeLower { + buf: b"VAARY", + lower: false, + }), + }; assert_eq!(a, b); - let a = HeaderName { inner: Repr::Standard(Vary) }; + let a = HeaderName { + inner: Repr::Standard(Vary), + }; assert_ne!(a, b); } #[test] fn test_from_static_std() { - let a = HeaderName { inner: Repr::Standard(Vary) }; + let a = HeaderName { + inner: Repr::Standard(Vary), + }; let b = HeaderName::from_static("vary"); assert_eq!(a, b); @@ -1803,7 +1830,9 @@ mod tests { // MaybeLower { lower: true } #[test] fn test_from_static_custom_short() { - let a = HeaderName { inner: Repr::Custom(Custom(ByteStr::from_static("customheader"))) }; + let a = HeaderName { + inner: Repr::Custom(Custom(ByteStr::from_static("customheader"))), + }; let b = HeaderName::from_static("customheader"); assert_eq!(a, b); } @@ -1823,11 +1852,13 @@ mod tests { // MaybeLower { lower: false } #[test] fn test_from_static_custom_long() { - let a = HeaderName { inner: Repr::Custom(Custom(ByteStr::from_static( - "longer-than-63--thisheaderislongerthansixtythreecharactersandthushandleddifferent" - ))) }; + let a = HeaderName { + inner: Repr::Custom(Custom(ByteStr::from_static( + "longer-than-63--thisheaderislongerthansixtythreecharactersandthushandleddifferent", + ))), + }; let b = HeaderName::from_static( - "longer-than-63--thisheaderislongerthansixtythreecharactersandthushandleddifferent" + "longer-than-63--thisheaderislongerthansixtythreecharactersandthushandleddifferent", ); assert_eq!(a, b); } @@ -1836,7 +1867,7 @@ mod tests { #[should_panic] fn test_from_static_custom_long_uppercase() { HeaderName::from_static( - "Longer-Than-63--ThisHeaderIsLongerThanSixtyThreeCharactersAndThusHandledDifferent" + "Longer-Than-63--ThisHeaderIsLongerThanSixtyThreeCharactersAndThusHandledDifferent", ); } @@ -1850,7 +1881,9 @@ mod tests { #[test] fn test_from_static_custom_single_char() { - let a = HeaderName { inner: Repr::Custom(Custom(ByteStr::from_static("a"))) }; + let a = HeaderName { + inner: Repr::Custom(Custom(ByteStr::from_static("a"))), + }; let b = HeaderName::from_static("a"); assert_eq!(a, b); } diff --git a/src/header/value.rs b/src/header/value.rs index bf05f16f..4b80cb4e 100644 --- a/src/header/value.rs +++ b/src/header/value.rs @@ -14,7 +14,7 @@ use crate::header::name::HeaderName; /// HTTP spec allows for a header value to contain opaque bytes as well. In this /// case, the header field value is not able to be represented as a string. /// -/// To handle this, the `HeaderValue` is useable as a type and can be compared +/// To handle this, the `HeaderValue` is usable 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)] @@ -203,7 +203,6 @@ impl HeaderValue { } } } else { - if_downcast_into!(T, Bytes, src, { return HeaderValue { inner: src, @@ -223,7 +222,10 @@ impl HeaderValue { HeaderValue::try_from_generic(src, std::convert::identity) } - fn try_from_generic, F: FnOnce(T) -> Bytes>(src: T, into: F) -> Result { + fn try_from_generic, F: FnOnce(T) -> Bytes>( + src: T, + into: F, + ) -> Result { for &b in src.as_ref() { if !is_valid(b) { return Err(InvalidHeaderValue { _priv: () }); @@ -697,7 +699,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 b7b3b357..6b0b7964 100644 --- a/src/method.rs +++ b/src/method.rs @@ -15,13 +15,13 @@ //! assert_eq!(Method::POST.as_str(), "POST"); //! ``` +use self::extension::{AllocatedExtension, InlineExtension}; use self::Inner::*; -use self::extension::{InlineExtension, AllocatedExtension}; use std::convert::AsRef; +use std::convert::TryFrom; use std::error::Error; use std::str::FromStr; -use std::convert::TryFrom; use std::{fmt, str}; /// The Request Method (VERB) @@ -67,7 +67,6 @@ enum Inner { ExtensionAllocated(AllocatedExtension), } - impl Method { /// GET pub const GET: Method = Method(Get); @@ -148,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 @@ -339,7 +335,7 @@ mod extension { let InlineExtension(ref data, len) = self; // Safety: the invariant of InlineExtension ensures that the first // len bytes of data contain valid UTF-8. - unsafe {str::from_utf8_unchecked(&data[..*len as usize])} + unsafe { str::from_utf8_unchecked(&data[..*len as usize]) } } } @@ -357,7 +353,7 @@ mod extension { pub fn as_str(&self) -> &str { // Safety: the invariant of AllocatedExtension ensures that self.0 // contains valid UTF-8. - unsafe {str::from_utf8_unchecked(&self.0)} + unsafe { str::from_utf8_unchecked(&self.0) } } } @@ -376,6 +372,7 @@ mod extension { // Note that this definition means that any &[u8] that consists solely of valid // characters is also valid UTF-8 because the valid method characters are a // subset of the valid 1 byte UTF-8 encoding. + #[rustfmt::skip] const METHOD_CHARS: [u8; 256] = [ // 0 1 2 3 4 5 6 7 8 9 b'\0', b'\0', b'\0', b'\0', b'\0', b'\0', b'\0', b'\0', b'\0', b'\0', // x diff --git a/src/request.rs b/src/request.rs index 2f662e9e..5b5b7eb7 100644 --- a/src/request.rs +++ b/src/request.rs @@ -53,7 +53,7 @@ //! ``` use std::any::Any; -use std::convert::{TryFrom}; +use std::convert::TryFrom; use std::fmt; use crate::header::{HeaderMap, HeaderName, HeaderValue}; @@ -163,6 +163,7 @@ pub struct Request { /// /// The HTTP request head consists of a method, uri, version, and a set of /// header fields. +#[non_exhaustive] pub struct Parts { /// The request's method pub method: Method, @@ -178,8 +179,6 @@ pub struct Parts { /// The request's extensions pub extensions: Extensions, - - _priv: (), } /// An HTTP request builder @@ -231,7 +230,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::GET).uri(uri) } @@ -254,7 +252,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::PUT).uri(uri) } @@ -277,7 +274,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::POST).uri(uri) } @@ -300,7 +296,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::DELETE).uri(uri) } @@ -324,7 +319,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::OPTIONS).uri(uri) } @@ -347,7 +341,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::HEAD).uri(uri) } @@ -370,7 +363,6 @@ impl Request<()> { where Uri: TryFrom, >::Error: Into, - { Builder::new().method(Method::CONNECT).uri(uri) } @@ -439,7 +431,7 @@ impl Request { pub fn new(body: T) -> Request { Request { head: Parts::new(), - body: body, + body, } } @@ -457,10 +449,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. @@ -723,7 +712,6 @@ impl Parts { version: Version::default(), headers: HeaderMap::default(), extensions: Extensions::default(), - _priv: (), } } } @@ -736,7 +724,6 @@ impl fmt::Debug for Parts { .field("version", &self.version) .field("headers", &self.headers) // omits Extensions because not useful - // omits _priv because not useful .finish() } } @@ -1051,19 +1038,14 @@ impl Builder { /// .unwrap(); /// ``` pub fn body(self, body: T) -> Result> { - self.inner.map(move |head| { - Request { - head, - body, - } - }) + self.inner.map(move |head| Request { head, body }) } // private fn and_then(self, func: F) -> Self where - F: FnOnce(Parts) -> Result + F: FnOnce(Parts) -> Result, { Builder { inner: self.inner.and_then(func), diff --git a/src/response.rs b/src/response.rs index 7233cdb7..d1a58251 100644 --- a/src/response.rs +++ b/src/response.rs @@ -185,6 +185,7 @@ pub struct Response { /// /// The HTTP response head consists of a status, version, and a set of /// header fields. +#[non_exhaustive] pub struct Parts { /// The response's status pub status: StatusCode, @@ -197,8 +198,6 @@ pub struct Parts { /// The response's extensions pub extensions: Extensions, - - _priv: (), } /// An HTTP response builder @@ -251,7 +250,7 @@ impl Response { pub fn new(body: T) -> Response { Response { head: Parts::new(), - body: body, + body, } } @@ -272,10 +271,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`. @@ -508,7 +504,6 @@ impl Parts { version: Version::default(), headers: HeaderMap::default(), extensions: Extensions::default(), - _priv: (), } } } @@ -520,7 +515,6 @@ impl fmt::Debug for Parts { .field("version", &self.version) .field("headers", &self.headers) // omits Extensions because not useful - // omits _priv because not useful .finish() } } @@ -754,19 +748,14 @@ impl Builder { /// .unwrap(); /// ``` pub fn body(self, body: T) -> Result> { - self.inner.map(move |head| { - Response { - head, - body, - } - }) + self.inner.map(move |head| Response { head, body }) } // private fn and_then(self, func: F) -> Self where - F: FnOnce(Parts) -> Result + F: FnOnce(Parts) -> Result, { Builder { inner: self.inner.and_then(func), diff --git a/src/status.rs b/src/status.rs index d98d24c3..9b8b62e3 100644 --- a/src/status.rs +++ b/src/status.rs @@ -15,9 +15,9 @@ //! ``` use std::convert::TryFrom; -use std::num::NonZeroU16; use std::error::Error; use std::fmt; +use std::num::NonZeroU16; use std::str::FromStr; /// An HTTP status code (`status-code` in RFC 7230 et al.). @@ -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()); } @@ -140,10 +140,14 @@ impl StatusCode { // ASCII-only, of length 900 * 3 = 2700 bytes #[cfg(debug_assertions)] - { &CODE_DIGITS[offset..offset+3] } + { + &CODE_DIGITS[offset..offset + 3] + } #[cfg(not(debug_assertions))] - unsafe { CODE_DIGITS.get_unchecked(offset..offset+3) } + unsafe { + CODE_DIGITS.get_unchecked(offset..offset + 3) + } } /// Get the standardised `reason-phrase` for this status code. @@ -263,7 +267,7 @@ impl FromStr for StatusCode { impl<'a> From<&'a StatusCode> for StatusCode { #[inline] fn from(t: &'a StatusCode) -> Self { - t.clone() + *t } } @@ -516,9 +520,7 @@ status_codes! { impl InvalidStatusCode { fn new() -> InvalidStatusCode { - InvalidStatusCode { - _priv: (), - } + InvalidStatusCode { _priv: () } } } @@ -540,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 7a43bc10..6e6aab36 100644 --- a/src/uri/authority.rs +++ b/src/uri/authority.rs @@ -234,7 +234,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()) } @@ -249,7 +249,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 @@ -430,7 +430,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) } } @@ -482,7 +482,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"); @@ -658,8 +658,7 @@ mod tests { let err = Authority::try_from([0xc0u8].as_ref()).unwrap_err(); assert_eq!(err.0, ErrorKind::InvalidUriChar); - let err = Authority::from_shared(Bytes::from_static([0xc0u8].as_ref())) - .unwrap_err(); + let err = Authority::from_shared(Bytes::from_static([0xc0u8].as_ref())).unwrap_err(); assert_eq!(err.0, ErrorKind::InvalidUriChar); } diff --git a/src/uri/builder.rs b/src/uri/builder.rs index 825c0faf..b07dc96f 100644 --- a/src/uri/builder.rs +++ b/src/uri/builder.rs @@ -137,7 +137,6 @@ impl Builder { where F: FnOnce(Parts) -> Result, { - Builder { parts: self.parts.and_then(func), } diff --git a/src/uri/mod.rs b/src/uri/mod.rs index 30be83b5..20d4bf2c 100644 --- a/src/uri/mod.rs +++ b/src/uri/mod.rs @@ -103,6 +103,7 @@ pub struct Uri { /// /// This struct is used to provide to and retrieve from a URI. #[derive(Debug, Default)] +#[non_exhaustive] pub struct Parts { /// The scheme component of a URI pub scheme: Option, @@ -112,9 +113,6 @@ pub struct Parts { /// The origin-form component of a URI pub path_and_query: Option, - - /// Allow extending in the future - _priv: (), } /// An error resulting from a failed attempt to construct a URI. @@ -149,6 +147,7 @@ const MAX_LEN: usize = (u16::MAX - 1) as usize; // of this table is that all entries above 127 are invalid. This makes all of the // valid entries a valid single-byte UTF-8 code point. This means that a slice // of such valid entries is valid UTF-8. +#[rustfmt::skip] const URI_CHARS: [u8; 256] = [ // 0 1 2 3 4 5 6 7 8 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x @@ -244,10 +243,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 { @@ -268,9 +265,9 @@ impl Uri { }; Ok(Uri { - scheme: scheme, - authority: authority, - path_and_query: path_and_query, + scheme, + authority, + path_and_query, }) } @@ -321,7 +318,7 @@ impl Uri { return Ok(Uri { scheme: Scheme::empty(), - authority: authority, + authority, path_and_query: PathAndQuery::empty(), }); } @@ -650,7 +647,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 `?`. @@ -742,7 +739,7 @@ impl TryFrom for Uri { } } -impl<'a> TryFrom> for Uri { +impl TryFrom> for Uri { type Error = InvalidUri; #[inline] @@ -812,10 +809,9 @@ impl From for Parts { }; Parts { - scheme: scheme, - authority: authority, - path_and_query: path_and_query, - _priv: (), + scheme, + authority, + path_and_query, } } } @@ -858,7 +854,7 @@ fn parse_full(mut s: Bytes) -> Result { return Ok(Uri { scheme: scheme.into(), - authority: authority, + authority, path_and_query: PathAndQuery::empty(), }); } @@ -875,7 +871,7 @@ fn parse_full(mut s: Bytes) -> Result { Ok(Uri { scheme: scheme.into(), - authority: authority, + authority, path_and_query: PathAndQuery::from_shared(s)?, }) } @@ -956,7 +952,7 @@ impl PartialEq for Uri { if other.len() < path.len() || path.as_bytes() != &other[..path.len()] { if absolute && path == "/" { - // PathAndQuery can be ommitted, fall through + // PathAndQuery can be omitted, fall through } else { return false; } @@ -965,8 +961,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 be2cb65c..90db1dde 100644 --- a/src/uri/path.rs +++ b/src/uri/path.rs @@ -18,6 +18,7 @@ const NONE: u16 = ::std::u16::MAX; impl PathAndQuery { // Not public while `bytes` is unstable. + #[rustfmt::skip] pub(super) fn from_shared(mut src: Bytes) -> Result { let mut query = NONE; let mut fragment = None; @@ -98,7 +99,7 @@ impl PathAndQuery { Ok(PathAndQuery { data: unsafe { ByteStr::from_utf8_unchecked(src) }, - query: query, + query, }) } @@ -291,7 +292,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 { @@ -555,7 +556,10 @@ mod tests { #[test] fn json_is_fine() { - assert_eq!(r#"/{"bread":"baguette"}"#, pq(r#"/{"bread":"baguette"}"#).path()); + assert_eq!( + r#"/{"bread":"baguette"}"#, + pq(r#"/{"bread":"baguette"}"#).path() + ); } fn pq(s: &str) -> PathAndQuery { diff --git a/src/uri/scheme.rs b/src/uri/scheme.rs index 682b11ee..1e80749e 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) } } @@ -204,6 +201,7 @@ const MAX_SCHEME_LEN: usize = 64; // important characteristic of this table is that all entries above 127 are // invalid. This makes all of the valid entries a valid single-byte UTF-8 code // point. This means that a slice of such valid entries is valid UTF-8. +#[rustfmt::skip] const SCHEME_CHARS: [u8; 256] = [ // 0 1 2 3 4 5 6 7 8 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x diff --git a/tests/header_map.rs b/tests/header_map.rs index f2beba08..b6c3f75e 100644 --- a/tests/header_map.rs +++ b/tests/header_map.rs @@ -190,7 +190,7 @@ fn drain_entry() { assert_eq!(vals[1], "world2"); } - assert_eq!(5-2+1, headers.len()); + assert_eq!(5 - 2 + 1, headers.len()); } #[test] @@ -427,7 +427,6 @@ fn value_htab() { HeaderValue::from_str("hello\tworld").unwrap(); } - #[test] fn remove_multiple_a() { let mut headers = HeaderMap::new(); @@ -570,7 +569,8 @@ fn remove_entry_multi_3_others() { } fn remove_all_values(headers: &mut HeaderMap, key: K) -> Vec - where K: IntoHeaderName +where + K: IntoHeaderName, { match headers.entry(key) { Entry::Occupied(e) => e.remove_entry_mult().1.collect(), @@ -629,7 +629,8 @@ fn remove_entry_3_others_b() { } fn remove_values(headers: &mut HeaderMap, key: K) -> Option - where K: IntoHeaderName +where + K: IntoHeaderName, { match headers.entry(key) { Entry::Occupied(e) => Some(e.remove_entry().1), diff --git a/tests/status_code.rs b/tests/status_code.rs index 160df6ba..0a962398 100644 --- a/tests/status_code.rs +++ b/tests/status_code.rs @@ -3,7 +3,7 @@ use http::*; #[test] fn from_bytes() { for ok in &[ - "100", "101", "199", "200", "250", "299", "321", "399", "499", "599", "600", "999" + "100", "101", "199", "200", "250", "299", "321", "399", "499", "599", "600", "999", ] { assert!(StatusCode::from_bytes(ok.as_bytes()).is_ok()); }