Skip to content

[0.2.x] introduce TryFrom impls for path, scheme, uri and authority #333

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

Merged
merged 1 commit into from
Jul 24, 2019
Merged
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
48 changes: 37 additions & 11 deletions src/uri/authority.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Deprecated in 1.26, needed until our minimum version is >=1.23.
#[allow(unused, deprecated)]
use std::ascii::AsciiExt;
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::{cmp, fmt, str};
Expand All @@ -26,8 +27,7 @@ impl Authority {

/// Attempt to convert an `Authority` from `Bytes`.
///
/// This function will be replaced by a `TryFrom` implementation once the
/// trait lands in stable.
/// This function has been replaced by `TryFrom` implementation.
///
/// # Examples
///
Expand All @@ -46,15 +46,7 @@ impl Authority {
/// # }
/// ```
pub fn from_shared(s: Bytes) -> Result<Self, InvalidUriBytes> {
let authority_end = Authority::parse_non_empty(&s[..]).map_err(InvalidUriBytes)?;

if authority_end != s.len() {
return Err(ErrorKind::InvalidUriChar.into());
}

Ok(Authority {
data: unsafe { ByteStr::from_utf8_unchecked(s) },
})
TryFrom::try_from(s)
}

/// Attempt to convert an `Authority` from a static string.
Expand Down Expand Up @@ -269,6 +261,40 @@ impl Authority {
}
}

impl TryFrom<Bytes> for Authority {
type Error = InvalidUriBytes;
/// Attempt to convert an `Authority` from `Bytes`.
///
/// # Examples
///
/// ```
/// # extern crate http;
/// # use http::uri::*;
/// extern crate bytes;
///
/// use std::convert::TryFrom;
/// use bytes::Bytes;
///
/// # pub fn main() {
/// let bytes = Bytes::from("example.com");
/// let authority = Authority::try_from(bytes).unwrap();
///
/// assert_eq!(authority.host(), "example.com");
/// # }
/// ```
fn try_from(s: Bytes) -> Result<Self, Self::Error> {
let authority_end = Authority::parse_non_empty(&s[..]).map_err(InvalidUriBytes)?;

if authority_end != s.len() {
return Err(ErrorKind::InvalidUriChar.into());
}

Ok(Authority {
data: unsafe { ByteStr::from_utf8_unchecked(s) },
})
}
}

impl AsRef<str> for Authority {
fn as_ref(&self) -> &str {
self.as_str()
Expand Down
126 changes: 77 additions & 49 deletions src/uri/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

use crate::byte_str::ByteStr;
use crate::HttpTryFrom;
use std::convert::TryFrom;

use bytes::Bytes;

Expand Down Expand Up @@ -241,8 +242,7 @@ impl Uri {

/// Attempt to convert a `Uri` from `Bytes`
///
/// This function will be replaced by a `TryFrom` implementation once the
/// trait lands in stable.
/// This function has been replaced by `TryFrom` implementation.
///
/// # Examples
///
Expand All @@ -262,53 +262,7 @@ impl Uri {
/// # }
/// ```
pub fn from_shared(s: Bytes) -> Result<Uri, InvalidUriBytes> {
use self::ErrorKind::*;

if s.len() > MAX_LEN {
return Err(TooLong.into());
}

match s.len() {
0 => {
return Err(Empty.into());
}
1 => match s[0] {
b'/' => {
return Ok(Uri {
scheme: Scheme::empty(),
authority: Authority::empty(),
path_and_query: PathAndQuery::slash(),
});
}
b'*' => {
return Ok(Uri {
scheme: Scheme::empty(),
authority: Authority::empty(),
path_and_query: PathAndQuery::star(),
});
}
_ => {
let authority = Authority::from_shared(s)?;

return Ok(Uri {
scheme: Scheme::empty(),
authority: authority,
path_and_query: PathAndQuery::empty(),
});
}
},
_ => {}
}

if s[0] == b'/' {
return Ok(Uri {
scheme: Scheme::empty(),
authority: Authority::empty(),
path_and_query: PathAndQuery::from_shared(s)?,
});
}

parse_full(s)
TryFrom::try_from(s)
}

/// Convert a `Uri` from a static string.
Expand Down Expand Up @@ -679,6 +633,80 @@ impl Uri {
}
}

impl TryFrom<Bytes> for Uri {
type Error = InvalidUriBytes;

/// Attempt to convert a `Uri` from `Bytes`
///
/// # Examples
///
/// ```
/// # extern crate http;
/// # use http::uri::*;
/// extern crate bytes;
///
/// use std::convert::TryFrom;
/// use bytes::Bytes;
///
/// # pub fn main() {
/// let bytes = Bytes::from("http://example.com/foo");
/// let uri = Uri::try_from(bytes).unwrap();
///
/// assert_eq!(uri.host().unwrap(), "example.com");
/// assert_eq!(uri.path(), "/foo");
/// # }
/// ```
fn try_from(s: Bytes) -> Result<Uri, Self::Error> {
use self::ErrorKind::*;

if s.len() > MAX_LEN {
return Err(TooLong.into());
}

match s.len() {
0 => {
return Err(Empty.into());
}
1 => match s[0] {
b'/' => {
return Ok(Uri {
scheme: Scheme::empty(),
authority: Authority::empty(),
path_and_query: PathAndQuery::slash(),
});
}
b'*' => {
return Ok(Uri {
scheme: Scheme::empty(),
authority: Authority::empty(),
path_and_query: PathAndQuery::star(),
});
}
_ => {
let authority = Authority::from_shared(s)?;

return Ok(Uri {
scheme: Scheme::empty(),
authority: authority,
path_and_query: PathAndQuery::empty(),
});
}
},
_ => {}
}

if s[0] == b'/' {
return Ok(Uri {
scheme: Scheme::empty(),
authority: Authority::empty(),
path_and_query: PathAndQuery::from_shared(s)?,
});
}

parse_full(s)
}
}

impl<'a> HttpTryFrom<&'a str> for Uri {
type Error = InvalidUri;

Expand Down
51 changes: 39 additions & 12 deletions src/uri/scheme.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Deprecated in 1.26, needed until our minimum version is >=1.23.
#[allow(unused, deprecated)]
use std::ascii::AsciiExt;
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
Expand Down Expand Up @@ -43,8 +44,7 @@ impl Scheme {

/// Attempt to convert a `Scheme` from `Bytes`
///
/// This function will be replaced by a `TryFrom` implementation once the
/// trait lands in stable.
/// This function has been replaced by `TryFrom` implementation
///
/// # Examples
///
Expand All @@ -63,16 +63,7 @@ impl Scheme {
/// # }
/// ```
pub fn from_shared(s: Bytes) -> Result<Self, InvalidUriBytes> {
use self::Scheme2::*;

match Scheme2::parse_exact(&s[..]).map_err(InvalidUriBytes)? {
None => Err(ErrorKind::InvalidScheme.into()),
Standard(p) => Ok(Standard(p).into()),
Other(_) => {
let b = unsafe { ByteStr::from_utf8_unchecked(s) };
Ok(Other(Box::new(b)).into())
}
}
TryFrom::try_from(s)
}

pub(super) fn empty() -> Self {
Expand Down Expand Up @@ -118,6 +109,42 @@ impl HttpTryFrom<Bytes> for Scheme {
}
}

impl TryFrom<Bytes> for Scheme {
type Error = InvalidUriBytes;

/// Attempt to convert a `Scheme` from `Bytes`
///
/// # Examples
///
/// ```
/// # extern crate http;
/// # use http::uri::*;
/// extern crate bytes;
///
/// use std::convert::TryFrom;
/// use bytes::Bytes;
///
/// # pub fn main() {
/// let bytes = Bytes::from("http");
/// let scheme = Scheme::try_from(bytes).unwrap();
///
/// assert_eq!(scheme.as_str(), "http");
/// # }
/// ```
fn try_from(s: Bytes) -> Result<Self, Self::Error> {
use self::Scheme2::*;

match Scheme2::parse_exact(&s[..]).map_err(InvalidUriBytes)? {
None => Err(ErrorKind::InvalidScheme.into()),
Standard(p) => Ok(Standard(p).into()),
Other(_) => {
let b = unsafe { ByteStr::from_utf8_unchecked(s) };
Ok(Other(Box::new(b)).into())
}
}
}
}

impl<'a> HttpTryFrom<&'a [u8]> for Scheme {
type Error = InvalidUri;
#[inline]
Expand Down