fix(rustup): update FromStr

Signed-off-by: Peter Atashian <retep998@gmail.com>
This commit is contained in:
Peter Atashian
2015-02-03 17:14:11 -05:00
committed by Sean McArthur
parent c983ebf3ce
commit 742081c8cf
18 changed files with 90 additions and 79 deletions

View File

@@ -1,4 +1,4 @@
#![feature(core, collections, io, test)] #![feature(collections, io, test)]
extern crate hyper; extern crate hyper;
extern crate test; extern crate test;

View File

@@ -32,9 +32,9 @@ impl<S: Scheme> Header for Authorization<S> {
match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) {
(Ok(header), Some(scheme)) (Ok(header), Some(scheme))
if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { if header.starts_with(scheme) && header.len() > scheme.len() + 1 => {
header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)).ok()
}, },
(Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)).ok(),
_ => None _ => None
} }
} else { } else {
@@ -108,32 +108,33 @@ impl Scheme for Basic {
} }
impl FromStr for Basic { impl FromStr for Basic {
fn from_str(s: &str) -> Option<Basic> { type Err = ();
fn from_str(s: &str) -> Result<Basic, ()> {
match s.from_base64() { match s.from_base64() {
Ok(decoded) => match String::from_utf8(decoded) { Ok(decoded) => match String::from_utf8(decoded) {
Ok(text) => { Ok(text) => {
let mut parts = &mut text[].split(':'); let mut parts = &mut text[].split(':');
let user = match parts.next() { let user = match parts.next() {
Some(part) => part.to_string(), Some(part) => part.to_string(),
None => return None None => return Err(())
}; };
let password = match parts.next() { let password = match parts.next() {
Some(part) => Some(part.to_string()), Some(part) => Some(part.to_string()),
None => None None => None
}; };
Some(Basic { Ok(Basic {
username: user, username: user,
password: password password: password
}) })
}, },
Err(e) => { Err(e) => {
debug!("Basic::from_utf8 error={:?}", e); debug!("Basic::from_utf8 error={:?}", e);
None Err(())
} }
}, },
Err(e) => { Err(e) => {
debug!("Basic::from_base64 error={:?}", e); debug!("Basic::from_base64 error={:?}", e);
None Err(())
} }
} }
} }

View File

@@ -96,28 +96,29 @@ impl fmt::Display for CacheDirective {
} }
impl FromStr for CacheDirective { impl FromStr for CacheDirective {
fn from_str(s: &str) -> Option<CacheDirective> { type Err = Option<<u32 as FromStr>::Err>;
fn from_str(s: &str) -> Result<CacheDirective, Option<<u32 as FromStr>::Err>> {
use self::CacheDirective::*; use self::CacheDirective::*;
match s { match s {
"no-cache" => Some(NoCache), "no-cache" => Ok(NoCache),
"no-store" => Some(NoStore), "no-store" => Ok(NoStore),
"no-transform" => Some(NoTransform), "no-transform" => Ok(NoTransform),
"only-if-cached" => Some(OnlyIfCached), "only-if-cached" => Ok(OnlyIfCached),
"must-revalidate" => Some(MustRevalidate), "must-revalidate" => Ok(MustRevalidate),
"public" => Some(Public), "public" => Ok(Public),
"private" => Some(Private), "private" => Ok(Private),
"proxy-revalidate" => Some(ProxyRevalidate), "proxy-revalidate" => Ok(ProxyRevalidate),
"" => None, "" => Err(None),
_ => match s.find('=') { _ => match s.find('=') {
Some(idx) if idx+1 < s.len() => match (&s[..idx], &s[idx+1..].trim_matches('"')) { Some(idx) if idx+1 < s.len() => match (&s[..idx], &s[idx+1..].trim_matches('"')) {
("max-age" , secs) => secs.parse().map(MaxAge), ("max-age" , secs) => secs.parse().map(MaxAge).map_err(|x| Some(x)),
("max-stale", secs) => secs.parse().map(MaxStale), ("max-stale", secs) => secs.parse().map(MaxStale).map_err(|x| Some(x)),
("min-fresh", secs) => secs.parse().map(MinFresh), ("min-fresh", secs) => secs.parse().map(MinFresh).map_err(|x| Some(x)),
("s-maxage", secs) => secs.parse().map(SMaxAge), ("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(|x| Some(x)),
(left, right) => Some(Extension(left.to_string(), Some(right.to_string()))) (left, right) => Ok(Extension(left.to_string(), Some(right.to_string())))
}, },
Some(_) => None, Some(_) => Err(None),
None => Some(Extension(s.to_string(), None)) None => Ok(Extension(s.to_string(), None))
} }
} }
} }

View File

@@ -31,11 +31,12 @@ pub enum ConnectionOption {
} }
impl FromStr for ConnectionOption { impl FromStr for ConnectionOption {
fn from_str(s: &str) -> Option<ConnectionOption> { type Err = ();
fn from_str(s: &str) -> Result<ConnectionOption, ()> {
match s { match s {
"keep-alive" => Some(KeepAlive), "keep-alive" => Ok(KeepAlive),
"close" => Some(Close), "close" => Ok(Close),
s => Some(ConnectionHeader(UniCase(s.to_string()))) s => Ok(ConnectionHeader(UniCase(s.to_string())))
} }
} }
} }

View File

@@ -30,8 +30,8 @@ impl Header for Cookie {
Ok(cookies_str) => { Ok(cookies_str) => {
for cookie_str in cookies_str.split(';') { for cookie_str in cookies_str.split(';') {
match cookie_str.trim().parse() { match cookie_str.trim().parse() {
Some(cookie) => cookies.push(cookie), Ok(cookie) => cookies.push(cookie),
None => return None Err(_) => return None
} }
} }
}, },

View File

@@ -35,8 +35,9 @@ impl HeaderFormat for Date {
} }
impl FromStr for Date { impl FromStr for Date {
fn from_str(s: &str) -> Option<Date> { type Err = ();
tm_from_str(s).map(Date) fn from_str(s: &str) -> Result<Date, ()> {
tm_from_str(s).map(Date).ok_or(())
} }
} }

View File

@@ -34,8 +34,9 @@ impl HeaderFormat for Expires {
} }
impl FromStr for Expires { impl FromStr for Expires {
fn from_str(s: &str) -> Option<Expires> { type Err = ();
tm_from_str(s).map(Expires) fn from_str(s: &str) -> Result<Expires, ()> {
tm_from_str(s).map(Expires).ok_or(())
} }
} }

View File

@@ -46,7 +46,7 @@ impl Header for Host {
}; };
let port = match idx { let port = match idx {
Some(idx) => s[idx + 1..].parse(), Some(idx) => s[idx + 1..].parse().ok(),
None => None None => None
}; };

View File

@@ -34,8 +34,9 @@ impl HeaderFormat for IfModifiedSince {
} }
impl FromStr for IfModifiedSince { impl FromStr for IfModifiedSince {
fn from_str(s: &str) -> Option<IfModifiedSince> { type Err = ();
tm_from_str(s).map(IfModifiedSince) fn from_str(s: &str) -> Result<IfModifiedSince, ()> {
tm_from_str(s).map(IfModifiedSince).ok_or(())
} }
} }

View File

@@ -34,8 +34,9 @@ impl HeaderFormat for LastModified {
} }
impl FromStr for LastModified { impl FromStr for LastModified {
fn from_str(s: &str) -> Option<LastModified> { type Err = ();
tm_from_str(s).map(LastModified) fn from_str(s: &str) -> Result<LastModified, ()> {
tm_from_str(s).map(LastModified).ok_or(())
} }
} }

View File

@@ -26,8 +26,8 @@ impl Header for SetCookie {
match from_utf8(&set_cookies_raw[]) { match from_utf8(&set_cookies_raw[]) {
Ok(s) if !s.is_empty() => { Ok(s) if !s.is_empty() => {
match s.parse() { match s.parse() {
Some(cookie) => set_cookies.push(cookie), Ok(cookie) => set_cookies.push(cookie),
None => () Err(_) => ()
} }
}, },
_ => () _ => ()

View File

@@ -22,12 +22,13 @@ pub enum Protocol {
} }
impl FromStr for Protocol { impl FromStr for Protocol {
fn from_str(s: &str) -> Option<Protocol> { type Err = ();
fn from_str(s: &str) -> Result<Protocol, ()> {
if UniCase(s) == UniCase("websocket") { if UniCase(s) == UniCase("websocket") {
Some(WebSocket) Ok(WebSocket)
} }
else { else {
Some(ProtocolExt(s.to_string())) Ok(ProtocolExt(s.to_string()))
} }
} }
} }

View File

@@ -349,7 +349,7 @@ impl<'a> fmt::Debug for HeaderView<'a> {
} }
impl<'a> Extend<HeaderView<'a>> for Headers { impl<'a> Extend<HeaderView<'a>> for Headers {
fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, mut iter: I) { fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, iter: I) {
for header in iter { for header in iter {
self.data.insert((*header.0).clone(), (*header.1).clone()); self.data.insert((*header.0).clone(), (*header.1).clone());
} }
@@ -571,7 +571,7 @@ mod tests {
} }
// we JUST checked that raw.len() == 1, so raw[0] WILL exist. // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
match from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { match from_utf8(unsafe { &raw[].get_unchecked(0)[] }) {
Ok(s) => FromStr::from_str(s), Ok(s) => FromStr::from_str(s).ok(),
Err(_) => None Err(_) => None
}.map(|u| CrazyLength(Some(false), u)) }.map(|u| CrazyLength(Some(false), u))
} }

View File

@@ -12,7 +12,7 @@ pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> {
} }
// we JUST checked that raw.len() == 1, so raw[0] WILL exist. // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
match str::from_utf8(&raw[0][]) { match str::from_utf8(&raw[0][]) {
Ok(s) => str::FromStr::from_str(s), Ok(s) => str::FromStr::from_str(s).ok(),
Err(_) => None Err(_) => None
} }
} }
@@ -34,7 +34,7 @@ pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
Some(s.as_slice() Some(s.as_slice()
.split(',') .split(',')
.map(|x| x.trim()) .map(|x| x.trim())
.filter_map(str::FromStr::from_str) .filter_map(|x| x.parse().ok())
.collect()) .collect())
} }
Err(_) => None Err(_) => None

View File

@@ -37,14 +37,15 @@ impl fmt::Display for Encoding {
} }
impl str::FromStr for Encoding { impl str::FromStr for Encoding {
fn from_str(s: &str) -> Option<Encoding> { type Err = ();
fn from_str(s: &str) -> Result<Encoding, ()> {
match s { match s {
"chunked" => Some(Chunked), "chunked" => Ok(Chunked),
"deflate" => Some(Deflate), "deflate" => Ok(Deflate),
"gzip" => Some(Gzip), "gzip" => Ok(Gzip),
"compress" => Some(Compress), "compress" => Ok(Compress),
"identity" => Some(Identity), "identity" => Ok(Identity),
_ => Some(EncodingExt(s.to_string())) _ => Ok(EncodingExt(s.to_string()))
} }
} }
} }

View File

@@ -38,7 +38,8 @@ impl<T: fmt::Display> fmt::Display for QualityItem<T> {
} }
impl<T: str::FromStr> str::FromStr for QualityItem<T> { impl<T: str::FromStr> str::FromStr for QualityItem<T> {
fn from_str(s: &str) -> Option<Self> { type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
// Set defaults used if parsing fails. // Set defaults used if parsing fails.
let mut raw_item = s; let mut raw_item = s;
let mut quality = 1f32; let mut quality = 1f32;
@@ -49,28 +50,28 @@ impl<T: str::FromStr> str::FromStr for QualityItem<T> {
if start == "q=" || start == "Q=" { if start == "q=" || start == "Q=" {
let q_part = &parts[0][2..parts[0].len()]; let q_part = &parts[0][2..parts[0].len()];
if q_part.len() > 5 { if q_part.len() > 5 {
return None; return Err(());
} }
let x: Option<f32> = q_part.parse(); let x: Result<f32, _> = q_part.parse();
match x { match x {
Some(q_value) => { Ok(q_value) => {
if 0f32 <= q_value && q_value <= 1f32 { if 0f32 <= q_value && q_value <= 1f32 {
quality = q_value; quality = q_value;
raw_item = parts[1]; raw_item = parts[1];
} else { } else {
return None; return Err(());
} }
}, },
None => return None, Err(_) => return Err(()),
} }
} }
} }
let x: Option<T> = raw_item.parse(); let x: Result<T, _> = raw_item.parse();
match x { match x {
Some(item) => { Ok(item) => {
Some(QualityItem{ item: item, quality: quality, }) Ok(QualityItem{ item: item, quality: quality, })
}, },
None => return None, Err(_) => return Err(()),
} }
} }
} }
@@ -103,26 +104,26 @@ fn test_quality_item_show3() {
#[test] #[test]
fn test_quality_item_from_str1() { fn test_quality_item_from_str1() {
let x: Option<QualityItem<Encoding>> = "chunked".parse(); let x: Result<QualityItem<Encoding>, ()> = "chunked".parse();
assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, }); assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
} }
#[test] #[test]
fn test_quality_item_from_str2() { fn test_quality_item_from_str2() {
let x: Option<QualityItem<Encoding>> = "chunked; q=1".parse(); let x: Result<QualityItem<Encoding>, ()> = "chunked; q=1".parse();
assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, }); assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
} }
#[test] #[test]
fn test_quality_item_from_str3() { fn test_quality_item_from_str3() {
let x: Option<QualityItem<Encoding>> = "gzip; q=0.5".parse(); let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.5".parse();
assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.5f32, }); assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.5f32, });
} }
#[test] #[test]
fn test_quality_item_from_str4() { fn test_quality_item_from_str4() {
let x: Option<QualityItem<Encoding>> = "gzip; q=0.273".parse(); let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.273".parse();
assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.273f32, }); assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.273f32, });
} }
#[test] #[test]
fn test_quality_item_from_str5() { fn test_quality_item_from_str5() {
let x: Option<QualityItem<Encoding>> = "gzip; q=0.2739999".parse(); let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.2739999".parse();
assert_eq!(x, None); assert_eq!(x, Err(()));
} }

View File

@@ -4,7 +4,7 @@ use std::borrow::IntoCow;
use std::cmp::min; use std::cmp::min;
use std::old_io::{self, Reader, IoResult, BufWriter}; use std::old_io::{self, Reader, IoResult, BufWriter};
use std::num::from_u16; use std::num::from_u16;
use std::str::{self, FromStr}; use std::str;
use std::string::CowString; use std::string::CowString;
use url::Url; use url::Url;
@@ -625,7 +625,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> {
try!(stream.read_byte()), try!(stream.read_byte()),
]; ];
let code = match str::from_utf8(code.as_slice()).ok().and_then(FromStr::from_str) { let code = match str::from_utf8(code.as_slice()).ok().and_then(|x| x.parse().ok()) {
Some(num) => num, Some(num) => num,
None => return Err(HttpStatusError) None => return Err(HttpStatusError)
}; };

View File

@@ -68,11 +68,12 @@ impl Method {
} }
impl FromStr for Method { impl FromStr for Method {
fn from_str(s: &str) -> Option<Method> { type Err = ();
fn from_str(s: &str) -> Result<Method, ()> {
if s == "" { if s == "" {
None Err(())
} else { } else {
Some(match s { Ok(match s {
"OPTIONS" => Options, "OPTIONS" => Options,
"GET" => Get, "GET" => Get,
"POST" => Post, "POST" => Post,
@@ -127,8 +128,8 @@ mod tests {
#[test] #[test]
fn test_from_str() { fn test_from_str() {
assert_eq!(Some(Get), FromStr::from_str("GET")); assert_eq!(Ok(Get), FromStr::from_str("GET"));
assert_eq!(Some(Extension("MOVE".to_string())), assert_eq!(Ok(Extension("MOVE".to_string())),
FromStr::from_str("MOVE")); FromStr::from_str("MOVE"));
} }