Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no_std support #749

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ documentation = "https://docs.rs/http"
repository = "https://github.com/hyperium/http"
license = "MIT OR Apache-2.0"
authors = [
"Alex Crichton <[email protected]>",
"Carl Lerche <[email protected]>",
"Sean McArthur <[email protected]>",
"Alex Crichton <[email protected]>",
"Carl Lerche <[email protected]>",
"Sean McArthur <[email protected]>",
]
description = """
A set of types for representing HTTP requests and responses.
Expand All @@ -25,19 +25,21 @@ rust-version = "1.49.0"

[workspace]
members = [
".",
".",
]
exclude = [
"fuzz",
"benches"
"fuzz",
"benches"
]

[features]
default = ["std"]
std = []
std = ["alloc"]
alloc = ["dep:bytes", "dep:hashbrown"]

[dependencies]
bytes = "1"
bytes = { version = "1", optional = true }
hashbrown = { version = "0.15", optional = true }
fnv = "1.0.5"
itoa = "1"

Expand All @@ -47,3 +49,11 @@ rand = "0.8.0"
serde = "1.0"
serde_json = "1.0"
doc-comment = "0.3"

[[test]]
name = "header_map_fuzz"
required-features = ["alloc"]

[[test]]
name = "header_map"
required-features = ["alloc"]
6 changes: 3 additions & 3 deletions src/byte_str.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use bytes::Bytes;

use std::{ops, str};
use core::{ops, str};

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub(crate) struct ByteStr {
Expand Down Expand Up @@ -58,9 +58,9 @@ impl ops::Deref for ByteStr {
}
}

impl From<String> for ByteStr {
impl From<alloc::string::String> for ByteStr {
#[inline]
fn from(src: String) -> ByteStr {
fn from(src: alloc::string::String) -> ByteStr {
ByteStr {
// Invariant: src is a String so contains valid UTF-8.
bytes: Bytes::from(src),
Expand Down
5 changes: 3 additions & 2 deletions src/convert.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#[cfg(feature = "alloc")]
macro_rules! if_downcast_into {
($in_ty:ty, $out_ty:ty, $val:ident, $body:expr) => {{
if std::any::TypeId::of::<$in_ty>() == std::any::TypeId::of::<$out_ty>() {
if ::core::any::TypeId::of::<$in_ty>() == ::core::any::TypeId::of::<$out_ty>() {
// Store the value in an `Option` so we can `take`
// it after casting to `&mut dyn Any`.
let mut slot = Some($val);
// Re-write the `$val` ident with the downcasted value.
let $val = (&mut slot as &mut dyn std::any::Any)
let $val = (&mut slot as &mut dyn ::core::any::Any)
.downcast_mut::<Option<$out_ty>>()
.unwrap()
.take()
Expand Down
27 changes: 21 additions & 6 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::error;
use std::fmt;
use std::result;
use core::error;
use core::fmt;

use crate::header;
#[cfg(feature = "alloc")]
use crate::header::MaxSizeReached;
use crate::method;
use crate::status;
#[cfg(feature = "alloc")]
use crate::uri;

/// A generic "error" for HTTP connections
Expand All @@ -19,15 +20,19 @@ pub struct Error {
}

/// A `Result` typedef to use with the `http::Error` type
pub type Result<T> = result::Result<T, Error>;
pub type Result<T> = core::result::Result<T, Error>;

enum ErrorKind {
StatusCode(status::InvalidStatusCode),
Method(method::InvalidMethod),
#[cfg(feature = "alloc")]
Uri(uri::InvalidUri),
#[cfg(feature = "alloc")]
UriParts(uri::InvalidUriParts),
HeaderName(header::InvalidHeaderName),
#[cfg(feature = "alloc")]
HeaderValue(header::InvalidHeaderValue),
#[cfg(feature = "alloc")]
MaxSizeReached(MaxSizeReached),
}

Expand Down Expand Up @@ -59,10 +64,14 @@ impl Error {
match self.inner {
StatusCode(ref e) => e,
Method(ref e) => e,
#[cfg(feature = "alloc")]
Uri(ref e) => e,
#[cfg(feature = "alloc")]
UriParts(ref e) => e,
HeaderName(ref e) => e,
#[cfg(feature = "alloc")]
HeaderValue(ref e) => e,
#[cfg(feature = "alloc")]
MaxSizeReached(ref e) => e,
}
}
Expand All @@ -76,6 +85,7 @@ impl error::Error for Error {
}
}

#[cfg(feature = "alloc")]
impl From<MaxSizeReached> for Error {
fn from(err: MaxSizeReached) -> Error {
Error {
Expand All @@ -100,6 +110,7 @@ impl From<method::InvalidMethod> for Error {
}
}

#[cfg(feature = "alloc")]
impl From<uri::InvalidUri> for Error {
fn from(err: uri::InvalidUri) -> Error {
Error {
Expand All @@ -108,6 +119,7 @@ impl From<uri::InvalidUri> for Error {
}
}

#[cfg(feature = "alloc")]
impl From<uri::InvalidUriParts> for Error {
fn from(err: uri::InvalidUriParts) -> Error {
Error {
Expand All @@ -124,6 +136,7 @@ impl From<header::InvalidHeaderName> for Error {
}
}

#[cfg(feature = "alloc")]
impl From<header::InvalidHeaderValue> for Error {
fn from(err: header::InvalidHeaderValue) -> Error {
Error {
Expand All @@ -132,8 +145,8 @@ impl From<header::InvalidHeaderValue> for Error {
}
}

impl From<std::convert::Infallible> for Error {
fn from(err: std::convert::Infallible) -> Error {
impl From<core::convert::Infallible> for Error {
fn from(err: core::convert::Infallible) -> Error {
match err {}
}
}
Expand All @@ -147,10 +160,12 @@ mod tests {
if let Err(e) = status::StatusCode::from_u16(6666) {
let err: Error = e.into();
let ie = err.get_ref();
#[cfg(feature = "alloc")]
assert!(!ie.is::<header::InvalidHeaderValue>());
assert!(ie.is::<status::InvalidStatusCode>());
ie.downcast_ref::<status::InvalidStatusCode>().unwrap();

#[cfg(feature = "alloc")]
assert!(!err.is::<header::InvalidHeaderValue>());
assert!(err.is::<status::InvalidStatusCode>());
} else {
Expand Down
16 changes: 10 additions & 6 deletions src/extensions.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::hash::{BuildHasherDefault, Hasher};

type AnyMap = HashMap<TypeId, Box<dyn AnyClone + Send + Sync>, BuildHasherDefault<IdHasher>>;
use alloc::boxed::Box;
use core::any::{Any, TypeId};
use core::fmt;
use std::hash::Hasher;

type AnyMap = hashbrown::HashMap<
TypeId,
Box<dyn AnyClone + Send + Sync>,
core::hash::BuildHasherDefault<IdHasher>,
>;

// With TypeIds as keys, there's no need to hash them. They are already hashes
// themselves, coming from the compiler. The IdHasher just holds the u64 of
Expand Down
116 changes: 95 additions & 21 deletions src/header/map.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
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};
use std::marker::PhantomData;
use std::{fmt, mem, ops, ptr, vec};
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;

use core::convert::TryFrom;
use core::hash::{BuildHasher, Hash, Hasher};
use core::iter::{FromIterator, FusedIterator};
use core::marker::PhantomData;
use core::{fmt, mem, ops, ptr};

use hashbrown::HashMap;

use crate::Error;

Expand Down Expand Up @@ -116,7 +120,7 @@ pub struct IntoIter<T> {
/// associated value.
#[derive(Debug)]
pub struct Keys<'a, T> {
inner: ::std::slice::Iter<'a, Bucket<T>>,
inner: ::core::slice::Iter<'a, Bucket<T>>,
}

/// `HeaderMap` value iterator.
Expand Down Expand Up @@ -209,7 +213,7 @@ pub struct ValueIterMut<'a, T> {
#[derive(Debug)]
pub struct ValueDrain<'a, T> {
first: Option<T>,
next: Option<::std::vec::IntoIter<T>>,
next: Option<::alloc::vec::IntoIter<T>>,
lt: PhantomData<&'a mut HeaderMap<T>>,
}

Expand Down Expand Up @@ -316,7 +320,7 @@ enum Link {
enum Danger {
Green,
Yellow,
Red(RandomState),
Red(hashbrown::DefaultHashBuilder),
}

// Constants related to detecting DOS attacks.
Expand Down Expand Up @@ -2007,12 +2011,56 @@ impl<T> FromIterator<(HeaderName, T)> for HeaderMap<T> {
}
}

/// Try to convert a `HashMap` into a `HeaderMap`.
macro_rules! try_map {
($map_like:ident) => {
($map_like)
.into_iter()
.map(|(k, v)| {
let name = TryFrom::try_from(k).map_err(Into::into)?;
let value = TryFrom::try_from(v).map_err(Into::into)?;

Ok((name, value))
})
.collect()
};
}

/// Try to convert a `BTreeMap` into a `HeaderMap`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::collections::BTreeMap;
/// use std::convert::TryInto;
/// use http::HeaderMap;
///
/// let mut map = BTreeMap::new();
/// map.insert("X-Custom-Header".to_string(), "my value".to_string());
///
/// let headers: HeaderMap = (&map).try_into().expect("valid headers");
/// assert_eq!(headers["X-Custom-Header"], "my value");
/// ```
impl<'a, K, V, T> TryFrom<&'a alloc::collections::BTreeMap<K, V>> for HeaderMap<T>
where
K: Eq + Hash + Ord,
HeaderName: TryFrom<&'a K>,
<HeaderName as TryFrom<&'a K>>::Error: Into<crate::Error>,
T: TryFrom<&'a V>,
T::Error: Into<crate::Error>,
{
type Error = Error;

fn try_from(c: &'a alloc::collections::BTreeMap<K, V>) -> Result<Self, Self::Error> {
try_map!(c)
}
}

/// Try to convert a `hashbrown::HashMap` into a `HeaderMap`.
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use std::convert::TryInto;
/// use http::HeaderMap;
///
Expand All @@ -2033,13 +2081,38 @@ where
type Error = Error;

fn try_from(c: &'a HashMap<K, V, S>) -> Result<Self, Self::Error> {
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)?;
Ok((name, value))
})
.collect()
try_map!(c)
}
}

/// Try to convert a `HashMap` into a `HeaderMap`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::convert::TryInto;
/// use http::HeaderMap;
///
/// let mut map = HashMap::new();
/// map.insert("X-Custom-Header".to_string(), "my value".to_string());
///
/// let headers: HeaderMap = (&map).try_into().expect("valid headers");
/// assert_eq!(headers["X-Custom-Header"], "my value");
/// ```
#[cfg(feature = "std")]
impl<'a, K, V, S, T> TryFrom<&'a std::collections::HashMap<K, V, S>> for HeaderMap<T>
where
K: Eq + Hash,
HeaderName: TryFrom<&'a K>,
<HeaderName as TryFrom<&'a K>>::Error: Into<crate::Error>,
T: TryFrom<&'a V>,
T::Error: Into<crate::Error>,
{
type Error = Error;

fn try_from(c: &'a std::collections::HashMap<K, V, S>) -> Result<Self, Self::Error> {
try_map!(c)
}
}

Expand Down Expand Up @@ -3533,7 +3606,7 @@ impl Danger {

fn set_red(&mut self) {
debug_assert!(self.is_yellow());
*self = Danger::Red(RandomState::new());
*self = Danger::Red(hashbrown::DefaultHashBuilder::default());
}

fn is_yellow(&self) -> bool {
Expand Down Expand Up @@ -3574,7 +3647,7 @@ impl fmt::Display for MaxSizeReached {
}
}

impl std::error::Error for MaxSizeReached {}
impl core::error::Error for MaxSizeReached {}

// ===== impl Utils =====

Expand Down Expand Up @@ -3736,6 +3809,7 @@ mod into_header_name {

mod as_header_name {
use super::{Entry, HdrName, HeaderMap, HeaderName, InvalidHeaderName, MaxSizeReached};
use alloc::string::String;

/// A marker trait used to identify values that can be used as search keys
/// to a `HeaderMap`.
Expand Down
Loading