1
Fork 0

some more clippy-based improvements

This commit is contained in:
Andre Bogus 2015-09-08 00:36:29 +02:00
parent 7bf626a680
commit 9cca96545f
34 changed files with 253 additions and 273 deletions

View file

@ -220,7 +220,7 @@ impl<'longer_than_self> Arena<'longer_than_self> {
*self.copy_head.borrow_mut() = *self.copy_head.borrow_mut() =
chunk((new_min_chunk_size + 1).next_power_of_two(), true); chunk((new_min_chunk_size + 1).next_power_of_two(), true);
return self.alloc_copy_inner(n_bytes, align); self.alloc_copy_inner(n_bytes, align)
} }
#[inline] #[inline]
@ -247,7 +247,7 @@ impl<'longer_than_self> Arena<'longer_than_self> {
mem::align_of::<T>()); mem::align_of::<T>());
let ptr = ptr as *mut T; let ptr = ptr as *mut T;
ptr::write(&mut (*ptr), op()); ptr::write(&mut (*ptr), op());
return &mut *ptr; &mut *ptr
} }
} }
@ -261,7 +261,7 @@ impl<'longer_than_self> Arena<'longer_than_self> {
*self.head.borrow_mut() = *self.head.borrow_mut() =
chunk((new_min_chunk_size + 1).next_power_of_two(), false); chunk((new_min_chunk_size + 1).next_power_of_two(), false);
return self.alloc_noncopy_inner(n_bytes, align); self.alloc_noncopy_inner(n_bytes, align)
} }
#[inline] #[inline]
@ -290,7 +290,7 @@ impl<'longer_than_self> Arena<'longer_than_self> {
unsafe { unsafe {
let buf = head.as_ptr(); let buf = head.as_ptr();
return (buf.offset(tydesc_start as isize), buf.offset(start as isize)); (buf.offset(tydesc_start as isize), buf.offset(start as isize))
} }
} }
@ -312,7 +312,7 @@ impl<'longer_than_self> Arena<'longer_than_self> {
// the object is there. // the object is there.
*ty_ptr = bitpack_tydesc_ptr(tydesc, true); *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
return &mut *ptr; &mut *ptr
} }
} }
@ -486,14 +486,12 @@ impl<T> TypedArena<T> {
self.grow() self.grow()
} }
let ptr: &mut T = unsafe { unsafe {
let ptr: &mut T = &mut *(self.ptr.get() as *mut T); let ptr: &mut T = &mut *(self.ptr.get() as *mut T);
ptr::write(ptr, object); ptr::write(ptr, object);
self.ptr.set(self.ptr.get().offset(1)); self.ptr.set(self.ptr.get().offset(1));
ptr ptr
}; }
ptr
} }
/// Grows the arena. /// Grows the arena.

View file

@ -1558,10 +1558,10 @@ impl StrExt for str {
if w > 2 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 2]); } if w > 2 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 2]); }
if w > 3 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 3]); } if w > 3 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 3]); }
return CharRange {ch: unsafe { char::from_u32_unchecked(val) }, next: i}; CharRange {ch: unsafe { char::from_u32_unchecked(val) }, next: i}
} }
return multibyte_char_range_at_reverse(self, prev); multibyte_char_range_at_reverse(self, prev)
} }
#[inline] #[inline]
@ -1683,7 +1683,7 @@ fn char_range_at_raw(bytes: &[u8], i: usize) -> (u32, usize) {
if w > 2 { val = utf8_acc_cont_byte(val, bytes[i + 2]); } if w > 2 { val = utf8_acc_cont_byte(val, bytes[i + 2]); }
if w > 3 { val = utf8_acc_cont_byte(val, bytes[i + 3]); } if w > 3 { val = utf8_acc_cont_byte(val, bytes[i + 3]); }
return (val, i + w as usize); (val, i + w as usize)
} }
multibyte_char_range_at(bytes, i) multibyte_char_range_at(bytes, i)

View file

@ -229,14 +229,14 @@ impl Name {
if nm.len() == 1 { if nm.len() == 1 {
Short(nm.char_at(0)) Short(nm.char_at(0))
} else { } else {
Long(nm.to_string()) Long(nm.to_owned())
} }
} }
fn to_string(&self) -> String { fn to_string(&self) -> String {
match *self { match *self {
Short(ch) => ch.to_string(), Short(ch) => ch.to_string(),
Long(ref s) => s.to_string() Long(ref s) => s.to_owned()
} }
} }
} }
@ -375,7 +375,7 @@ impl Matches {
} else { } else {
match vals[0] { match vals[0] {
Val(ref s) => Some((*s).clone()), Val(ref s) => Some((*s).clone()),
_ => Some(def.to_string()) _ => Some(def.to_owned())
} }
} }
} }
@ -414,10 +414,10 @@ pub fn reqopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptG
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: hint.to_string(), hint: hint.to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: Yes, hasarg: Yes,
occur: Req occur: Req
} }
@ -434,10 +434,10 @@ pub fn optopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptG
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: hint.to_string(), hint: hint.to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: Yes, hasarg: Yes,
occur: Optional occur: Optional
} }
@ -452,10 +452,10 @@ pub fn optflag(short_name: &str, long_name: &str, desc: &str) -> OptGroup {
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: "".to_string(), hint: "".to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: No, hasarg: No,
occur: Optional occur: Optional
} }
@ -471,10 +471,10 @@ pub fn optflagmulti(short_name: &str, long_name: &str, desc: &str) -> OptGroup {
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: "".to_string(), hint: "".to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: No, hasarg: No,
occur: Multi occur: Multi
} }
@ -491,10 +491,10 @@ pub fn optflagopt(short_name: &str, long_name: &str, desc: &str, hint: &str) ->
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: hint.to_string(), hint: hint.to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: Maybe, hasarg: Maybe,
occur: Optional occur: Optional
} }
@ -512,10 +512,10 @@ pub fn optmulti(short_name: &str, long_name: &str, desc: &str, hint: &str) -> Op
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: hint.to_string(), hint: hint.to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: Yes, hasarg: Yes,
occur: Multi occur: Multi
} }
@ -531,10 +531,10 @@ pub fn opt(short_name: &str,
let len = short_name.len(); let len = short_name.len();
assert!(len == 1 || len == 0); assert!(len == 1 || len == 0);
OptGroup { OptGroup {
short_name: short_name.to_string(), short_name: short_name.to_owned(),
long_name: long_name.to_string(), long_name: long_name.to_owned(),
hint: hint.to_string(), hint: hint.to_owned(),
desc: desc.to_string(), desc: desc.to_owned(),
hasarg: hasarg, hasarg: hasarg,
occur: occur occur: occur
} }
@ -574,7 +574,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect(); let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect();
let n_opts = opts.len(); let n_opts = opts.len();
fn f(_x: usize) -> Vec<Optval> { return Vec::new(); } fn f(_x: usize) -> Vec<Optval> { Vec::new() }
let mut vals: Vec<_> = (0..n_opts).map(f).collect(); let mut vals: Vec<_> = (0..n_opts).map(f).collect();
let mut free: Vec<String> = Vec::new(); let mut free: Vec<String> = Vec::new();
@ -596,11 +596,11 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
let tail = &cur[2..curlen]; let tail = &cur[2..curlen];
let tail_eq: Vec<&str> = tail.split('=').collect(); let tail_eq: Vec<&str> = tail.split('=').collect();
if tail_eq.len() <= 1 { if tail_eq.len() <= 1 {
names = vec!(Long(tail.to_string())); names = vec!(Long(tail.to_owned()));
} else { } else {
names = names =
vec!(Long(tail_eq[0].to_string())); vec!(Long(tail_eq[0].to_owned()));
i_arg = Some(tail_eq[1].to_string()); i_arg = Some(tail_eq[1].to_owned());
} }
} else { } else {
let mut j = 1; let mut j = 1;
@ -630,7 +630,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
let next = j + ch.len_utf8(); let next = j + ch.len_utf8();
if arg_follows && next < curlen { if arg_follows && next < curlen {
i_arg = Some((&cur[next..curlen]).to_string()); i_arg = Some((&cur[next..curlen]).to_owned());
break; break;
} }
@ -769,7 +769,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String {
// FIXME: #5516 should be graphemes not codepoints // FIXME: #5516 should be graphemes not codepoints
let mut desc_rows = Vec::new(); let mut desc_rows = Vec::new();
each_split_within(&desc_normalized_whitespace[..], 54, |substr| { each_split_within(&desc_normalized_whitespace[..], 54, |substr| {
desc_rows.push(substr.to_string()); desc_rows.push(substr.to_owned());
true true
}); });
@ -936,7 +936,7 @@ fn each_split_within<F>(ss: &str, lim: usize, mut it: F) -> bool where
machine(&mut cont, (fake_i, ' ')); machine(&mut cont, (fake_i, ' '));
fake_i += 1; fake_i += 1;
} }
return cont; cont
} }
#[test] #[test]

View file

@ -74,12 +74,12 @@ pub fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<String>) {
} }
}; };
dirs.push(LogDirective { dirs.push(LogDirective {
name: name.map(|s| s.to_string()), name: name.map(str::to_owned),
level: log_level, level: log_level,
}); });
}}); }});
(dirs, filter.map(|s| s.to_string())) (dirs, filter.map(str::to_owned))
} }
#[cfg(test)] #[cfg(test)]
@ -90,13 +90,13 @@ mod tests {
fn parse_logging_spec_valid() { fn parse_logging_spec_valid() {
let (dirs, filter) = parse_logging_spec("crate1::mod1=1,crate1::mod2,crate2=4"); let (dirs, filter) = parse_logging_spec("crate1::mod1=1,crate1::mod2,crate2=4");
assert_eq!(dirs.len(), 3); assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); assert_eq!(dirs[0].name, Some("crate1::mod1".to_owned()));
assert_eq!(dirs[0].level, 1); assert_eq!(dirs[0].level, 1);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); assert_eq!(dirs[1].name, Some("crate1::mod2".to_owned()));
assert_eq!(dirs[1].level, ::MAX_LOG_LEVEL); assert_eq!(dirs[1].level, ::MAX_LOG_LEVEL);
assert_eq!(dirs[2].name, Some("crate2".to_string())); assert_eq!(dirs[2].name, Some("crate2".to_owned()));
assert_eq!(dirs[2].level, 4); assert_eq!(dirs[2].level, 4);
assert!(filter.is_none()); assert!(filter.is_none());
} }
@ -106,7 +106,7 @@ mod tests {
// test parse_logging_spec with multiple = in specification // test parse_logging_spec with multiple = in specification
let (dirs, filter) = parse_logging_spec("crate1::mod1=1=2,crate2=4"); let (dirs, filter) = parse_logging_spec("crate1::mod1=1=2,crate2=4");
assert_eq!(dirs.len(), 1); assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string())); assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, 4); assert_eq!(dirs[0].level, 4);
assert!(filter.is_none()); assert!(filter.is_none());
} }
@ -116,7 +116,7 @@ mod tests {
// test parse_logging_spec with 'noNumber' as log level // test parse_logging_spec with 'noNumber' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=noNumber,crate2=4"); let (dirs, filter) = parse_logging_spec("crate1::mod1=noNumber,crate2=4");
assert_eq!(dirs.len(), 1); assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string())); assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, 4); assert_eq!(dirs[0].level, 4);
assert!(filter.is_none()); assert!(filter.is_none());
} }
@ -126,7 +126,7 @@ mod tests {
// test parse_logging_spec with 'warn' as log level // test parse_logging_spec with 'warn' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=warn"); let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=warn");
assert_eq!(dirs.len(), 1); assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string())); assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, ::WARN); assert_eq!(dirs[0].level, ::WARN);
assert!(filter.is_none()); assert!(filter.is_none());
} }
@ -136,7 +136,7 @@ mod tests {
// test parse_logging_spec with '' as log level // test parse_logging_spec with '' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2="); let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=");
assert_eq!(dirs.len(), 1); assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string())); assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, ::MAX_LOG_LEVEL); assert_eq!(dirs[0].level, ::MAX_LOG_LEVEL);
assert!(filter.is_none()); assert!(filter.is_none());
} }
@ -148,7 +148,7 @@ mod tests {
assert_eq!(dirs.len(), 2); assert_eq!(dirs.len(), 2);
assert_eq!(dirs[0].name, None); assert_eq!(dirs[0].name, None);
assert_eq!(dirs[0].level, 2); assert_eq!(dirs[0].level, 2);
assert_eq!(dirs[1].name, Some("crate2".to_string())); assert_eq!(dirs[1].name, Some("crate2".to_owned()));
assert_eq!(dirs[1].level, 4); assert_eq!(dirs[1].level, 4);
assert!(filter.is_none()); assert!(filter.is_none());
} }
@ -157,32 +157,32 @@ mod tests {
fn parse_logging_spec_valid_filter() { fn parse_logging_spec_valid_filter() {
let (dirs, filter) = parse_logging_spec("crate1::mod1=1,crate1::mod2,crate2=4/abc"); let (dirs, filter) = parse_logging_spec("crate1::mod1=1,crate1::mod2,crate2=4/abc");
assert_eq!(dirs.len(), 3); assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); assert_eq!(dirs[0].name, Some("crate1::mod1".to_owned()));
assert_eq!(dirs[0].level, 1); assert_eq!(dirs[0].level, 1);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); assert_eq!(dirs[1].name, Some("crate1::mod2".to_owned()));
assert_eq!(dirs[1].level, ::MAX_LOG_LEVEL); assert_eq!(dirs[1].level, ::MAX_LOG_LEVEL);
assert_eq!(dirs[2].name, Some("crate2".to_string())); assert_eq!(dirs[2].name, Some("crate2".to_owned()));
assert_eq!(dirs[2].level, 4); assert_eq!(dirs[2].level, 4);
assert!(filter.is_some() && filter.unwrap().to_string() == "abc"); assert!(filter.is_some() && filter.unwrap().to_owned() == "abc");
} }
#[test] #[test]
fn parse_logging_spec_invalid_crate_filter() { fn parse_logging_spec_invalid_crate_filter() {
let (dirs, filter) = parse_logging_spec("crate1::mod1=1=2,crate2=4/a.c"); let (dirs, filter) = parse_logging_spec("crate1::mod1=1=2,crate2=4/a.c");
assert_eq!(dirs.len(), 1); assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string())); assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, 4); assert_eq!(dirs[0].level, 4);
assert!(filter.is_some() && filter.unwrap().to_string() == "a.c"); assert!(filter.is_some() && filter.unwrap().to_owned() == "a.c");
} }
#[test] #[test]
fn parse_logging_spec_empty_with_filter() { fn parse_logging_spec_empty_with_filter() {
let (dirs, filter) = parse_logging_spec("crate1/a*c"); let (dirs, filter) = parse_logging_spec("crate1/a*c");
assert_eq!(dirs.len(), 1); assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate1".to_string())); assert_eq!(dirs[0].name, Some("crate1".to_owned()));
assert_eq!(dirs[0].level, ::MAX_LOG_LEVEL); assert_eq!(dirs[0].level, ::MAX_LOG_LEVEL);
assert!(filter.is_some() && filter.unwrap().to_string() == "a*c"); assert!(filter.is_some() && filter.unwrap().to_owned() == "a*c");
} }
} }

View file

@ -1039,8 +1039,8 @@ impl Json {
/// If the Json value is an Object, returns the value associated with the provided key. /// If the Json value is an Object, returns the value associated with the provided key.
/// Otherwise, returns None. /// Otherwise, returns None.
pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{ pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
match self { match *self {
&Json::Object(ref map) => map.get(key), Json::Object(ref map) => map.get(key),
_ => None _ => None
} }
} }
@ -1083,41 +1083,41 @@ impl Json {
} }
/// Returns true if the Json value is an Object. Returns false otherwise. /// Returns true if the Json value is an Object. Returns false otherwise.
pub fn is_object<'a>(&'a self) -> bool { pub fn is_object(&self) -> bool {
self.as_object().is_some() self.as_object().is_some()
} }
/// If the Json value is an Object, returns the associated BTreeMap. /// If the Json value is an Object, returns the associated BTreeMap.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_object<'a>(&'a self) -> Option<&'a Object> { pub fn as_object(&self) -> Option<&Object> {
match self { match *self {
&Json::Object(ref map) => Some(map), Json::Object(ref map) => Some(map),
_ => None _ => None
} }
} }
/// Returns true if the Json value is an Array. Returns false otherwise. /// Returns true if the Json value is an Array. Returns false otherwise.
pub fn is_array<'a>(&'a self) -> bool { pub fn is_array(&self) -> bool {
self.as_array().is_some() self.as_array().is_some()
} }
/// If the Json value is an Array, returns the associated vector. /// If the Json value is an Array, returns the associated vector.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_array<'a>(&'a self) -> Option<&'a Array> { pub fn as_array(&self) -> Option<&Array> {
match self { match *self {
&Json::Array(ref array) => Some(&*array), Json::Array(ref array) => Some(&*array),
_ => None _ => None
} }
} }
/// Returns true if the Json value is a String. Returns false otherwise. /// Returns true if the Json value is a String. Returns false otherwise.
pub fn is_string<'a>(&'a self) -> bool { pub fn is_string(&self) -> bool {
self.as_string().is_some() self.as_string().is_some()
} }
/// If the Json value is a String, returns the associated str. /// If the Json value is a String, returns the associated str.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_string<'a>(&'a self) -> Option<&'a str> { pub fn as_string(&self) -> Option<&str> {
match *self { match *self {
Json::String(ref s) => Some(&s[..]), Json::String(ref s) => Some(&s[..]),
_ => None _ => None
@ -1195,8 +1195,8 @@ impl Json {
/// If the Json value is a Boolean, returns the associated bool. /// If the Json value is a Boolean, returns the associated bool.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_boolean(&self) -> Option<bool> { pub fn as_boolean(&self) -> Option<bool> {
match self { match *self {
&Json::Boolean(b) => Some(b), Json::Boolean(b) => Some(b),
_ => None _ => None
} }
} }
@ -1209,8 +1209,8 @@ impl Json {
/// If the Json value is a Null, returns (). /// If the Json value is a Null, returns ().
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_null(&self) -> Option<()> { pub fn as_null(&self) -> Option<()> {
match self { match *self {
&Json::Null => Some(()), Json::Null => Some(()),
_ => None _ => None
} }
} }
@ -1228,8 +1228,8 @@ impl Index<usize> for Json {
type Output = Json; type Output = Json;
fn index<'a>(&'a self, idx: usize) -> &'a Json { fn index<'a>(&'a self, idx: usize) -> &'a Json {
match self { match *self {
&Json::Array(ref v) => &v[idx], Json::Array(ref v) => &v[idx],
_ => panic!("can only index Json with usize if it is an array") _ => panic!("can only index Json with usize if it is an array")
} }
} }
@ -1323,20 +1323,20 @@ impl Stack {
/// Compares this stack with an array of StackElements. /// Compares this stack with an array of StackElements.
pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool { pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
if self.stack.len() != rhs.len() { return false; } if self.stack.len() != rhs.len() { return false; }
for i in 0..rhs.len() { for (i, r) in rhs.iter().enumerate() {
if self.get(i) != rhs[i] { return false; } if &self.get(i) != r { return false; }
} }
return true; true
} }
/// Returns true if the bottom-most elements of this stack are the same as /// Returns true if the bottom-most elements of this stack are the same as
/// the ones passed as parameter. /// the ones passed as parameter.
pub fn starts_with(&self, rhs: &[StackElement]) -> bool { pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
if self.stack.len() < rhs.len() { return false; } if self.stack.len() < rhs.len() { return false; }
for i in 0..rhs.len() { for (i, r) in rhs.iter().enumerate() {
if self.get(i) != rhs[i] { return false; } if &self.get(i) != r { return false; }
} }
return true; true
} }
/// Returns true if the top-most elements of this stack are the same as /// Returns true if the top-most elements of this stack are the same as
@ -1344,15 +1344,15 @@ impl Stack {
pub fn ends_with(&self, rhs: &[StackElement]) -> bool { pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
if self.stack.len() < rhs.len() { return false; } if self.stack.len() < rhs.len() { return false; }
let offset = self.stack.len() - rhs.len(); let offset = self.stack.len() - rhs.len();
for i in 0..rhs.len() { for (i, r) in rhs.iter().enumerate() {
if self.get(i + offset) != rhs[i] { return false; } if &self.get(i + offset) != r { return false; }
} }
return true; true
} }
/// Returns the top-most element (if any). /// Returns the top-most element (if any).
pub fn top<'l>(&'l self) -> Option<StackElement<'l>> { pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
return match self.stack.last() { match self.stack.last() {
None => None, None => None,
Some(&InternalIndex(i)) => Some(StackElement::Index(i)), Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
Some(&InternalKey(start, size)) => { Some(&InternalKey(start, size)) => {
@ -1442,7 +1442,7 @@ impl<T: Iterator<Item=char>> Iterator for Parser<T> {
} }
} }
return Some(self.parse()); Some(self.parse())
} }
} }
@ -1458,13 +1458,13 @@ impl<T: Iterator<Item=char>> Parser<T> {
state: ParseStart, state: ParseStart,
}; };
p.bump(); p.bump();
return p; p
} }
/// Provides access to the current position in the logical structure of the /// Provides access to the current position in the logical structure of the
/// JSON stream. /// JSON stream.
pub fn stack<'l>(&'l self) -> &'l Stack { pub fn stack<'l>(&'l self) -> &'l Stack {
return &self.stack; &self.stack
} }
fn eof(&self) -> bool { self.ch.is_none() } fn eof(&self) -> bool { self.ch.is_none() }
@ -1559,9 +1559,8 @@ impl<T: Iterator<Item=char>> Parser<T> {
self.bump(); self.bump();
// A leading '0' must be the only digit before the decimal point. // A leading '0' must be the only digit before the decimal point.
match self.ch_or_null() { if let '0' ... '9' = self.ch_or_null() {
'0' ... '9' => return self.error(InvalidNumber), return self.error(InvalidNumber)
_ => ()
} }
}, },
'1' ... '9' => { '1' ... '9' => {
@ -1798,7 +1797,7 @@ impl<T: Iterator<Item=char>> Parser<T> {
ObjectStart => ParseObject(true), ObjectStart => ParseObject(true),
_ => ParseBeforeFinish, _ => ParseBeforeFinish,
}; };
return val; val
} }
fn parse_array(&mut self, first: bool) -> JsonEvent { fn parse_array(&mut self, first: bool) -> JsonEvent {
@ -1905,7 +1904,7 @@ impl<T: Iterator<Item=char>> Parser<T> {
ObjectStart => ParseObject(true), ObjectStart => ParseObject(true),
_ => ParseObjectComma, _ => ParseObjectComma,
}; };
return val; val
} }
fn parse_object_end(&mut self) -> JsonEvent { fn parse_object_end(&mut self) -> JsonEvent {
@ -1994,7 +1993,7 @@ impl<T: Iterator<Item=char>> Builder<T> {
} }
fn build_value(&mut self) -> Result<Json, BuilderError> { fn build_value(&mut self) -> Result<Json, BuilderError> {
return match self.token { match self.token {
Some(NullValue) => Ok(Json::Null), Some(NullValue) => Ok(Json::Null),
Some(I64Value(n)) => Ok(Json::I64(n)), Some(I64Value(n)) => Ok(Json::I64(n)),
Some(U64Value(n)) => Ok(Json::U64(n)), Some(U64Value(n)) => Ok(Json::U64(n)),
@ -2043,7 +2042,7 @@ impl<T: Iterator<Item=char>> Builder<T> {
_ => {} _ => {}
} }
let key = match self.parser.stack().top() { let key = match self.parser.stack().top() {
Some(StackElement::Key(k)) => { k.to_string() } Some(StackElement::Key(k)) => { k.to_owned() }
_ => { panic!("invalid state"); } _ => { panic!("invalid state"); }
}; };
match self.build_value() { match self.build_value() {
@ -2052,7 +2051,7 @@ impl<T: Iterator<Item=char>> Builder<T> {
} }
self.bump(); self.bump();
} }
return self.parser.error(EOFWhileParsingObject); self.parser.error(EOFWhileParsingObject)
} }
} }
@ -2099,7 +2098,7 @@ macro_rules! expect {
($e:expr, Null) => ({ ($e:expr, Null) => ({
match $e { match $e {
Json::Null => Ok(()), Json::Null => Ok(()),
other => Err(ExpectedError("Null".to_string(), other => Err(ExpectedError("Null".to_owned(),
format!("{}", other))) format!("{}", other)))
} }
}); });
@ -2107,7 +2106,7 @@ macro_rules! expect {
match $e { match $e {
Json::$t(v) => Ok(v), Json::$t(v) => Ok(v),
other => { other => {
Err(ExpectedError(stringify!($t).to_string(), Err(ExpectedError(stringify!($t).to_owned(),
format!("{}", other))) format!("{}", other)))
} }
} }
@ -2120,14 +2119,14 @@ macro_rules! read_primitive {
match self.pop() { match self.pop() {
Json::I64(f) => Ok(f as $ty), Json::I64(f) => Ok(f as $ty),
Json::U64(f) => Ok(f as $ty), Json::U64(f) => Ok(f as $ty),
Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))), Json::F64(f) => Err(ExpectedError("Integer".to_owned(), format!("{}", f))),
// re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc) // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
// is going to have a string here, as per JSON spec. // is going to have a string here, as per JSON spec.
Json::String(s) => match s.parse().ok() { Json::String(s) => match s.parse().ok() {
Some(f) => Ok(f), Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_string(), s)), None => Err(ExpectedError("Number".to_owned(), s)),
}, },
value => Err(ExpectedError("Number".to_string(), format!("{}", value))), value => Err(ExpectedError("Number".to_owned(), format!("{}", value))),
} }
} }
} }
@ -2163,11 +2162,11 @@ impl ::Decoder for Decoder {
// is going to have a string here, as per JSON spec. // is going to have a string here, as per JSON spec.
match s.parse().ok() { match s.parse().ok() {
Some(f) => Ok(f), Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_string(), s)), None => Err(ExpectedError("Number".to_owned(), s)),
} }
}, },
Json::Null => Ok(f64::NAN), Json::Null => Ok(f64::NAN),
value => Err(ExpectedError("Number".to_string(), format!("{}", value))) value => Err(ExpectedError("Number".to_owned(), format!("{}", value)))
} }
} }
@ -2185,7 +2184,7 @@ impl ::Decoder for Decoder {
_ => () _ => ()
} }
} }
Err(ExpectedError("single character string".to_string(), format!("{}", s))) Err(ExpectedError("single character string".to_owned(), format!("{}", s)))
} }
fn read_str(&mut self) -> DecodeResult<string::String> { fn read_str(&mut self) -> DecodeResult<string::String> {
@ -2205,13 +2204,13 @@ impl ::Decoder for Decoder {
let name = match self.pop() { let name = match self.pop() {
Json::String(s) => s, Json::String(s) => s,
Json::Object(mut o) => { Json::Object(mut o) => {
let n = match o.remove(&"variant".to_string()) { let n = match o.remove(&"variant".to_owned()) {
Some(Json::String(s)) => s, Some(Json::String(s)) => s,
Some(val) => { Some(val) => {
return Err(ExpectedError("String".to_string(), format!("{}", val))) return Err(ExpectedError("String".to_owned(), format!("{}", val)))
} }
None => { None => {
return Err(MissingFieldError("variant".to_string())) return Err(MissingFieldError("variant".to_owned()))
} }
}; };
match o.remove(&"fields".to_string()) { match o.remove(&"fields".to_string()) {
@ -2221,16 +2220,16 @@ impl ::Decoder for Decoder {
} }
}, },
Some(val) => { Some(val) => {
return Err(ExpectedError("Array".to_string(), format!("{}", val))) return Err(ExpectedError("Array".to_owned(), format!("{}", val)))
} }
None => { None => {
return Err(MissingFieldError("fields".to_string())) return Err(MissingFieldError("fields".to_owned()))
} }
} }
n n
} }
json => { json => {
return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) return Err(ExpectedError("String or Object".to_owned(), format!("{}", json)))
} }
}; };
let idx = match names.iter().position(|n| *n == &name[..]) { let idx = match names.iter().position(|n| *n == &name[..]) {

View file

@ -515,7 +515,7 @@ macro_rules! tuple {
|d| -> Result<$name,D::Error> { |d| -> Result<$name,D::Error> {
Decodable::decode(d) Decodable::decode(d)
})),)*); })),)*);
return Ok(ret); Ok(ret)
}) })
} }
} }

View file

@ -231,7 +231,7 @@ mod dl {
Ok(result) Ok(result)
} else { } else {
let s = CStr::from_ptr(last_error).to_bytes(); let s = CStr::from_ptr(last_error).to_bytes();
Err(str::from_utf8(s).unwrap().to_string()) Err(str::from_utf8(s).unwrap().to_owned())
}; };
ret ret

View file

@ -277,11 +277,11 @@ impl Error {
impl fmt::Debug for Repr { impl fmt::Debug for Repr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self { match *self {
&Repr::Os(ref code) => Repr::Os(ref code) =>
fmt.debug_struct("Os").field("code", code) fmt.debug_struct("Os").field("code", code)
.field("message", &sys::os::error_string(*code)).finish(), .field("message", &sys::os::error_string(*code)).finish(),
&Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(), Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
} }
} }
} }

View file

@ -62,6 +62,6 @@ impl<T: Send + Sync + 'static> Lazy<T> {
if registered.is_ok() { if registered.is_ok() {
self.ptr.set(Box::into_raw(Box::new(ret.clone()))); self.ptr.set(Box::into_raw(Box::new(ret.clone())));
} }
return ret ret
} }
} }

View file

@ -262,8 +262,8 @@ impl<'a> Parser<'a> {
} }
fn read_ip_addr(&mut self) -> Option<IpAddr> { fn read_ip_addr(&mut self) -> Option<IpAddr> {
let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr().map(|v4| IpAddr::V4(v4)); let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr().map(IpAddr::V4);
let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr().map(|v6| IpAddr::V6(v6)); let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr().map(IpAddr::V6);
self.read_or(&mut [Box::new(ipv4_addr), Box::new(ipv6_addr)]) self.read_or(&mut [Box::new(ipv4_addr), Box::new(ipv6_addr)])
} }

View file

@ -42,7 +42,7 @@ unsafe fn init() -> bool {
return false return false
} }
return true true
} }
pub fn cleanup() { pub fn cleanup() {
@ -78,5 +78,5 @@ pub fn push(f: Box<FnBox()>) -> bool {
} }
LOCK.unlock(); LOCK.unlock();
} }
return ret ret
} }

View file

@ -104,7 +104,7 @@ pub unsafe fn find_landing_pad(lsda: *const u8, context: &EHContext)
// IP range not found: gcc's C++ personality calls terminate() here, // IP range not found: gcc's C++ personality calls terminate() here,
// however the rest of the languages treat this the same as cs_lpad == 0. // however the rest of the languages treat this the same as cs_lpad == 0.
// We follow this suit. // We follow this suit.
return None; None
} }
#[inline] #[inline]

View file

@ -73,7 +73,7 @@ fn lang_start(main: *const u8, argc: isize, argv: *const *const u8) -> isize {
// created. Note that this isn't necessary in general for new threads, // created. Note that this isn't necessary in general for new threads,
// but we just do this to name the main thread and to give it correct // but we just do this to name the main thread and to give it correct
// info about the stack bounds. // info about the stack bounds.
let thread: Thread = NewThread::new(Some("<main>".to_string())); let thread: Thread = NewThread::new(Some("<main>".to_owned()));
thread_info::set(main_guard, thread); thread_info::set(main_guard, thread);
// By default, some platforms will send a *signal* when a EPIPE error // By default, some platforms will send a *signal* when a EPIPE error

View file

@ -27,7 +27,7 @@ pub fn min_stack() -> usize {
// 0 is our sentinel value, so ensure that we'll never see 0 after // 0 is our sentinel value, so ensure that we'll never see 0 after
// initialization has run // initialization has run
MIN.store(amt + 1, Ordering::SeqCst); MIN.store(amt + 1, Ordering::SeqCst);
return amt; amt
} }
// Indicates whether we should perform expensive sanity checks, including rtassert! // Indicates whether we should perform expensive sanity checks, including rtassert!

View file

@ -397,7 +397,7 @@ enum Flavor<T> {
#[doc(hidden)] #[doc(hidden)]
trait UnsafeFlavor<T> { trait UnsafeFlavor<T> {
fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>>; fn inner_unsafe(&self) -> &UnsafeCell<Flavor<T>>;
unsafe fn inner_mut<'a>(&'a self) -> &'a mut Flavor<T> { unsafe fn inner_mut<'a>(&'a self) -> &'a mut Flavor<T> {
&mut *self.inner_unsafe().get() &mut *self.inner_unsafe().get()
} }
@ -406,12 +406,12 @@ trait UnsafeFlavor<T> {
} }
} }
impl<T> UnsafeFlavor<T> for Sender<T> { impl<T> UnsafeFlavor<T> for Sender<T> {
fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> { fn inner_unsafe(&self) -> &UnsafeCell<Flavor<T>> {
&self.inner &self.inner
} }
} }
impl<T> UnsafeFlavor<T> for Receiver<T> { impl<T> UnsafeFlavor<T> for Receiver<T> {
fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> { fn inner_unsafe(&self) -> &UnsafeCell<Flavor<T>> {
&self.inner &self.inner
} }
} }
@ -677,7 +677,7 @@ impl<T> SyncSender<T> {
impl<T> Clone for SyncSender<T> { impl<T> Clone for SyncSender<T> {
fn clone(&self) -> SyncSender<T> { fn clone(&self) -> SyncSender<T> {
unsafe { (*self.inner.get()).clone_chan(); } unsafe { (*self.inner.get()).clone_chan(); }
return SyncSender::new(self.inner.clone()); SyncSender::new(self.inner.clone())
} }
} }

View file

@ -196,7 +196,7 @@ impl<T> Queue<T> {
let _: Box<Node<T>> = Box::from_raw(tail); let _: Box<Node<T>> = Box::from_raw(tail);
} }
} }
return ret; ret
} }
} }
@ -207,14 +207,13 @@ impl<T> Queue<T> {
/// The reference returned is invalid if it is not used before the consumer /// The reference returned is invalid if it is not used before the consumer
/// pops the value off the queue. If the producer then pushes another value /// pops the value off the queue. If the producer then pushes another value
/// onto the queue, it will overwrite the value pointed to by the reference. /// onto the queue, it will overwrite the value pointed to by the reference.
pub fn peek<'a>(&'a self) -> Option<&'a mut T> { pub fn peek(&self) -> Option<&mut T> {
// This is essentially the same as above with all the popping bits // This is essentially the same as above with all the popping bits
// stripped out. // stripped out.
unsafe { unsafe {
let tail = *self.tail.get(); let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire); let next = (*tail).next.load(Ordering::Acquire);
if next.is_null() { return None } if next.is_null() { None } else { (*next).value.as_mut() }
return (*next).value.as_mut();
} }
} }
} }

View file

@ -307,12 +307,7 @@ impl<T> Packet<T> {
steals, DISCONNECTED, Ordering::SeqCst); steals, DISCONNECTED, Ordering::SeqCst);
cnt != DISCONNECTED && cnt != steals cnt != DISCONNECTED && cnt != steals
} { } {
loop { while let Some(_) = self.queue.pop() { steals += 1; }
match self.queue.pop() {
Some(..) => { steals += 1; }
None => break
}
}
} }
// At this point in time, we have gated all future senders from sending, // At this point in time, we have gated all future senders from sending,
@ -378,7 +373,7 @@ impl<T> Packet<T> {
// previous value is positive because we're not going to sleep // previous value is positive because we're not going to sleep
let prev = self.bump(1); let prev = self.bump(1);
assert!(prev == DISCONNECTED || prev >= 0); assert!(prev == DISCONNECTED || prev >= 0);
return ret; ret
} }
} }
} }

View file

@ -254,7 +254,7 @@ impl<T> Packet<T> {
assert!(guard.buf.size() > 0); assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue(); let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard); self.wakeup_senders(waited, guard);
return Ok(ret); Ok(ret)
} }
pub fn try_recv(&self) -> Result<T, Failure> { pub fn try_recv(&self) -> Result<T, Failure> {
@ -267,8 +267,7 @@ impl<T> Packet<T> {
// Be sure to wake up neighbors // Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue()); let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard); self.wakeup_senders(false, guard);
ret
return ret;
} }
// Wake up pending senders after some data has been received // Wake up pending senders after some data has been received
@ -356,12 +355,7 @@ impl<T> Packet<T> {
}; };
mem::drop(guard); mem::drop(guard);
loop { while let Some(token) = queue.dequeue() { token.signal(); }
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal()); waiter.map(|t| t.signal());
} }

View file

@ -334,13 +334,14 @@ impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> { impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> {
type Target = T; type Target = T;
fn deref<'a>(&'a self) -> &'a T { fn deref(&self) -> &T {
unsafe { &*self.__data.get() } unsafe { &*self.__data.get() }
} }
} }
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> { impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T { fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.__data.get() } unsafe { &mut *self.__data.get() }
} }
} }

View file

@ -151,7 +151,7 @@ pub fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void,
}; };
STATE = backtrace_create_state(filename, 0, error_cb, STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut()); ptr::null_mut());
return STATE STATE
} }
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////

View file

@ -161,7 +161,7 @@ pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
}; };
match from_utf8(data.to_bytes()) { match from_utf8(data.to_bytes()) {
Ok(name) => Ok(name.to_string()), Ok(name) => Ok(name.to_owned()),
Err(_) => Err(io::Error::new(io::ErrorKind::Other, Err(_) => Err(io::Error::new(io::ErrorKind::Other,
"failed to lookup address information")) "failed to lookup address information"))
} }

View file

@ -67,7 +67,7 @@ impl<T> ReentrantMutex<T> {
data: t, data: t,
}; };
mutex.inner.init(); mutex.inner.init();
return mutex mutex
} }
} }
@ -145,7 +145,7 @@ impl<'mutex, T> ReentrantMutexGuard<'mutex, T> {
impl<'mutex, T> Deref for ReentrantMutexGuard<'mutex, T> { impl<'mutex, T> Deref for ReentrantMutexGuard<'mutex, T> {
type Target = T; type Target = T;
fn deref<'a>(&'a self) -> &'a T { fn deref(&self) -> &T {
&self.__lock.data &self.__lock.data
} }
} }

View file

@ -282,19 +282,13 @@ impl Wtf8Buf {
/// like concatenating ill-formed UTF-16 strings effectively would. /// like concatenating ill-formed UTF-16 strings effectively would.
#[inline] #[inline]
pub fn push(&mut self, code_point: CodePoint) { pub fn push(&mut self, code_point: CodePoint) {
match code_point.to_u32() { if let trail @ 0xDC00...0xDFFF = code_point.to_u32() {
trail @ 0xDC00...0xDFFF => { if let Some(lead) = (&*self).final_lead_surrogate() {
match (&*self).final_lead_surrogate() { let len_without_lead_surrogate = self.len() - 3;
Some(lead) => { self.bytes.truncate(len_without_lead_surrogate);
let len_without_lead_surrogate = self.len() - 3; self.push_char(decode_surrogate_pair(lead, trail as u16));
self.bytes.truncate(len_without_lead_surrogate); return
self.push_char(decode_surrogate_pair(lead, trail as u16));
return
}
_ => {}
}
} }
_ => {}
} }
// No newly paired surrogates at the boundary. // No newly paired surrogates at the boundary.

View file

@ -99,7 +99,7 @@ pub fn write(w: &mut Write) -> io::Result<()> {
} }
// keep going // keep going
return uw::_URC_NO_REASON uw::_URC_NO_REASON
} }
} }

View file

@ -35,7 +35,7 @@ pub fn cvt_gai(err: c_int) -> io::Result<()> {
let detail = unsafe { let detail = unsafe {
str::from_utf8(CStr::from_ptr(c::gai_strerror(err)).to_bytes()).unwrap() str::from_utf8(CStr::from_ptr(c::gai_strerror(err)).to_bytes()).unwrap()
.to_string() .to_owned()
}; };
Err(io::Error::new(io::ErrorKind::Other, Err(io::Error::new(io::ErrorKind::Other,
&format!("failed to lookup address information: {}", &format!("failed to lookup address information: {}",

View file

@ -88,7 +88,7 @@ pub fn error_string(errno: i32) -> String {
} }
let p = p as *const _; let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string() str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
} }
} }
@ -134,7 +134,7 @@ pub struct SplitPaths<'a> {
fn(&'a [u8]) -> PathBuf>, fn(&'a [u8]) -> PathBuf>,
} }
pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> { pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
fn bytes_to_path(b: &[u8]) -> PathBuf { fn bytes_to_path(b: &[u8]) -> PathBuf {
PathBuf::from(<OsStr as OsStrExt>::from_bytes(b)) PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
} }
@ -142,7 +142,7 @@ pub fn split_paths<'a>(unparsed: &'a OsStr) -> SplitPaths<'a> {
let unparsed = unparsed.as_bytes(); let unparsed = unparsed.as_bytes();
SplitPaths { SplitPaths {
iter: unparsed.split(is_colon as fn(&u8) -> bool) iter: unparsed.split(is_colon as fn(&u8) -> bool)
.map(bytes_to_path as fn(&'a [u8]) -> PathBuf) .map(bytes_to_path as fn(&[u8]) -> PathBuf)
} }
} }

View file

@ -23,7 +23,7 @@ impl Stdin {
let fd = FileDesc::new(libc::STDIN_FILENO); let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data); let ret = fd.read(data);
fd.into_raw(); fd.into_raw();
return ret; ret
} }
} }
@ -34,7 +34,7 @@ impl Stdout {
let fd = FileDesc::new(libc::STDOUT_FILENO); let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data); let ret = fd.write(data);
fd.into_raw(); fd.into_raw();
return ret; ret
} }
} }
@ -45,7 +45,7 @@ impl Stderr {
let fd = FileDesc::new(libc::STDERR_FILENO); let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data); let ret = fd.write(data);
fd.into_raw(); fd.into_raw();
return ret; ret
} }
} }

View file

@ -310,7 +310,7 @@ pub mod guard {
ret = Some(stackaddr as usize + guardsize as usize); ret = Some(stackaddr as usize + guardsize as usize);
} }
assert_eq!(pthread_attr_destroy(&mut attr), 0); assert_eq!(pthread_attr_destroy(&mut attr), 0);
return ret ret
} }
#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg(any(target_os = "linux", target_os = "android"))]

View file

@ -18,7 +18,7 @@ pub type Key = pthread_key_t;
pub unsafe fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key { pub unsafe fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
let mut key = 0; let mut key = 0;
assert_eq!(pthread_key_create(&mut key, dtor), 0); assert_eq!(pthread_key_create(&mut key, dtor), 0);
return key; key
} }
#[inline] #[inline]

View file

@ -151,7 +151,7 @@ impl<T: Write+Send+'static> Terminal<T> for TerminfoTerminal<T> {
cap = self.ti.strings.get("op"); cap = self.ti.strings.get("op");
} }
} }
let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_string()), |op| { let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_owned()), |op| {
expand(op, &[], &mut Variables::new()) expand(op, &[], &mut Variables::new())
}); });
if s.is_ok() { if s.is_ok() {
@ -211,9 +211,9 @@ impl<T: Write+Send+'static> TerminfoTerminal<T> {
inf.numbers.get("colors").map_or(0, |&n| n) inf.numbers.get("colors").map_or(0, |&n| n)
} else { 0 }; } else { 0 };
return Some(box TerminfoTerminal {out: out, Some(box TerminfoTerminal {out: out,
ti: inf, ti: inf,
num_colors: nc}); num_colors: nc})
} }
fn dim_if_necessary(&self, color: color::Color) -> color::Color { fn dim_if_necessary(&self, color: color::Color) -> color::Color {

View file

@ -133,9 +133,9 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
c as u8 c as u8
}) })
} }
_ => return Err("a non-char was used with %c".to_string()) _ => return Err("a non-char was used with %c".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'p' => state = PushParam, 'p' => state = PushParam,
'P' => state = SetVar, 'P' => state = SetVar,
'g' => state = GetVar, 'g' => state = GetVar,
@ -144,112 +144,112 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
'l' => if !stack.is_empty() { 'l' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Words(s) => stack.push(Number(s.len() as isize)), Words(s) => stack.push(Number(s.len() as isize)),
_ => return Err("a non-str was used with %l".to_string()) _ => return Err("a non-str was used with %l".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'+' => if stack.len() > 1 { '+' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x + y)), (Number(y), Number(x)) => stack.push(Number(x + y)),
_ => return Err("non-numbers on stack with +".to_string()) _ => return Err("non-numbers on stack with +".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'-' => if stack.len() > 1 { '-' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x - y)), (Number(y), Number(x)) => stack.push(Number(x - y)),
_ => return Err("non-numbers on stack with -".to_string()) _ => return Err("non-numbers on stack with -".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'*' => if stack.len() > 1 { '*' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x * y)), (Number(y), Number(x)) => stack.push(Number(x * y)),
_ => return Err("non-numbers on stack with *".to_string()) _ => return Err("non-numbers on stack with *".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'/' => if stack.len() > 1 { '/' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x / y)), (Number(y), Number(x)) => stack.push(Number(x / y)),
_ => return Err("non-numbers on stack with /".to_string()) _ => return Err("non-numbers on stack with /".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'm' => if stack.len() > 1 { 'm' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x % y)), (Number(y), Number(x)) => stack.push(Number(x % y)),
_ => return Err("non-numbers on stack with %".to_string()) _ => return Err("non-numbers on stack with %".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'&' => if stack.len() > 1 { '&' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x & y)), (Number(y), Number(x)) => stack.push(Number(x & y)),
_ => return Err("non-numbers on stack with &".to_string()) _ => return Err("non-numbers on stack with &".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'|' => if stack.len() > 1 { '|' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x | y)), (Number(y), Number(x)) => stack.push(Number(x | y)),
_ => return Err("non-numbers on stack with |".to_string()) _ => return Err("non-numbers on stack with |".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'^' => if stack.len() > 1 { '^' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x ^ y)), (Number(y), Number(x)) => stack.push(Number(x ^ y)),
_ => return Err("non-numbers on stack with ^".to_string()) _ => return Err("non-numbers on stack with ^".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'=' => if stack.len() > 1 { '=' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(if x == y { 1 } (Number(y), Number(x)) => stack.push(Number(if x == y { 1 }
else { 0 })), else { 0 })),
_ => return Err("non-numbers on stack with =".to_string()) _ => return Err("non-numbers on stack with =".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'>' => if stack.len() > 1 { '>' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(if x > y { 1 } (Number(y), Number(x)) => stack.push(Number(if x > y { 1 }
else { 0 })), else { 0 })),
_ => return Err("non-numbers on stack with >".to_string()) _ => return Err("non-numbers on stack with >".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'<' => if stack.len() > 1 { '<' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(if x < y { 1 } (Number(y), Number(x)) => stack.push(Number(if x < y { 1 }
else { 0 })), else { 0 })),
_ => return Err("non-numbers on stack with <".to_string()) _ => return Err("non-numbers on stack with <".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'A' => if stack.len() > 1 { 'A' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(0), Number(_)) => stack.push(Number(0)), (Number(0), Number(_)) => stack.push(Number(0)),
(Number(_), Number(0)) => stack.push(Number(0)), (Number(_), Number(0)) => stack.push(Number(0)),
(Number(_), Number(_)) => stack.push(Number(1)), (Number(_), Number(_)) => stack.push(Number(1)),
_ => return Err("non-numbers on stack with logical and".to_string()) _ => return Err("non-numbers on stack with logical and".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'O' => if stack.len() > 1 { 'O' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) { match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(0), Number(0)) => stack.push(Number(0)), (Number(0), Number(0)) => stack.push(Number(0)),
(Number(_), Number(_)) => stack.push(Number(1)), (Number(_), Number(_)) => stack.push(Number(1)),
_ => return Err("non-numbers on stack with logical or".to_string()) _ => return Err("non-numbers on stack with logical or".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'!' => if !stack.is_empty() { '!' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Number(0) => stack.push(Number(1)), Number(0) => stack.push(Number(1)),
Number(_) => stack.push(Number(0)), Number(_) => stack.push(Number(0)),
_ => return Err("non-number on stack with logical not".to_string()) _ => return Err("non-number on stack with logical not".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'~' => if !stack.is_empty() { '~' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Number(x) => stack.push(Number(!x)), Number(x) => stack.push(Number(!x)),
_ => return Err("non-number on stack with %~".to_string()) _ => return Err("non-number on stack with %~".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'i' => match (mparams[0].clone(), mparams[1].clone()) { 'i' => match (mparams[0].clone(), mparams[1].clone()) {
(Number(x), Number(y)) => { (Number(x), Number(y)) => {
mparams[0] = Number(x+1); mparams[0] = Number(x+1);
mparams[1] = Number(y+1); mparams[1] = Number(y+1);
}, },
(_, _) => return Err("first two params not numbers with %i".to_string()) (_, _) => return Err("first two params not numbers with %i".to_owned())
}, },
// printf-style support for %doxXs // printf-style support for %doxXs
@ -258,7 +258,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags); let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags);
if res.is_err() { return res } if res.is_err() { return res }
output.push_all(&res.unwrap()) output.push_all(&res.unwrap())
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
':'|'#'|' '|'.'|'0'...'9' => { ':'|'#'|' '|'.'|'0'...'9' => {
let mut flags = Flags::new(); let mut flags = Flags::new();
let mut fstate = FormatStateFlags; let mut fstate = FormatStateFlags;
@ -283,9 +283,9 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
Number(0) => state = SeekIfElse(0), Number(0) => state = SeekIfElse(0),
Number(_) => (), Number(_) => (),
_ => return Err("non-number on stack \ _ => return Err("non-number on stack \
with conditional".to_string()) with conditional".to_owned())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
'e' => state = SeekIfEnd(0), 'e' => state = SeekIfEnd(0),
';' => (), ';' => (),
@ -298,7 +298,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
// params are 1-indexed // params are 1-indexed
stack.push(mparams[match cur.to_digit(10) { stack.push(mparams[match cur.to_digit(10) {
Some(d) => d as usize - 1, Some(d) => d as usize - 1,
None => return Err("bad param number".to_string()) None => return Err("bad param number".to_owned())
}].clone()); }].clone());
}, },
SetVar => { SetVar => {
@ -306,14 +306,14 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
if !stack.is_empty() { if !stack.is_empty() {
let idx = (cur as u8) - b'A'; let idx = (cur as u8) - b'A';
vars.sta[idx as usize] = stack.pop().unwrap(); vars.sta[idx as usize] = stack.pop().unwrap();
} else { return Err("stack is empty".to_string()) } } else { return Err("stack is empty".to_owned()) }
} else if cur >= 'a' && cur <= 'z' { } else if cur >= 'a' && cur <= 'z' {
if !stack.is_empty() { if !stack.is_empty() {
let idx = (cur as u8) - b'a'; let idx = (cur as u8) - b'a';
vars.dyn[idx as usize] = stack.pop().unwrap(); vars.dyn[idx as usize] = stack.pop().unwrap();
} else { return Err("stack is empty".to_string()) } } else { return Err("stack is empty".to_owned()) }
} else { } else {
return Err("bad variable name in %P".to_string()); return Err("bad variable name in %P".to_owned());
} }
}, },
GetVar => { GetVar => {
@ -324,7 +324,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
let idx = (cur as u8) - b'a'; let idx = (cur as u8) - b'a';
stack.push(vars.dyn[idx as usize].clone()); stack.push(vars.dyn[idx as usize].clone());
} else { } else {
return Err("bad variable name in %g".to_string()); return Err("bad variable name in %g".to_owned());
} }
}, },
CharConstant => { CharConstant => {
@ -333,7 +333,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
}, },
CharClose => { CharClose => {
if cur != '\'' { if cur != '\'' {
return Err("malformed character constant".to_string()); return Err("malformed character constant".to_owned());
} }
}, },
IntConstant(i) => { IntConstant(i) => {
@ -346,7 +346,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
state = IntConstant(i*10 + (cur as isize - '0' as isize)); state = IntConstant(i*10 + (cur as isize - '0' as isize));
old_state = Nothing; old_state = Nothing;
} }
_ => return Err("bad isize constant".to_string()) _ => return Err("bad isize constant".to_owned())
} }
} }
FormatPattern(ref mut flags, ref mut fstate) => { FormatPattern(ref mut flags, ref mut fstate) => {
@ -358,7 +358,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
output.push_all(&res.unwrap()); output.push_all(&res.unwrap());
// will cause state to go to Nothing // will cause state to go to Nothing
old_state = FormatPattern(*flags, *fstate); old_state = FormatPattern(*flags, *fstate);
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_owned()) },
(FormatStateFlags,'#') => { (FormatStateFlags,'#') => {
flags.alternate = true; flags.alternate = true;
} }
@ -381,7 +381,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
(FormatStateWidth,'0'...'9') => { (FormatStateWidth,'0'...'9') => {
let old = flags.width; let old = flags.width;
flags.width = flags.width * 10 + (cur as usize - '0' as usize); flags.width = flags.width * 10 + (cur as usize - '0' as usize);
if flags.width < old { return Err("format width overflow".to_string()) } if flags.width < old { return Err("format width overflow".to_owned()) }
} }
(FormatStateWidth,'.') => { (FormatStateWidth,'.') => {
*fstate = FormatStatePrecision; *fstate = FormatStatePrecision;
@ -390,10 +390,10 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
let old = flags.precision; let old = flags.precision;
flags.precision = flags.precision * 10 + (cur as usize - '0' as usize); flags.precision = flags.precision * 10 + (cur as usize - '0' as usize);
if flags.precision < old { if flags.precision < old {
return Err("format precision overflow".to_string()) return Err("format precision overflow".to_owned())
} }
} }
_ => return Err("invalid format specifier".to_string()) _ => return Err("invalid format specifier".to_owned())
} }
} }
SeekIfElse(level) => { SeekIfElse(level) => {
@ -502,7 +502,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
(FormatHex, _) => format!("{:x}", d).into_bytes(), (FormatHex, _) => format!("{:x}", d).into_bytes(),
(FormatHEX, _) => format!("{:X}", d).into_bytes(), (FormatHEX, _) => format!("{:X}", d).into_bytes(),
(FormatString, _) => { (FormatString, _) => {
return Err("non-number on stack with %s".to_string()) return Err("non-number on stack with %s".to_owned())
} }
}; };
let mut s: Vec<u8> = s.into_iter().collect(); let mut s: Vec<u8> = s.into_iter().collect();
@ -692,7 +692,7 @@ mod tests {
Words("f".to_string()), Words("f".to_string()),
Words("foo".to_string())], vars), Words("foo".to_string())], vars),
Ok("foofoo ffo".bytes().collect::<Vec<_>>())); Ok("foofoo ffo".bytes().collect::<Vec<_>>()));
assert_eq!(expand(b"%p1%:-4.2s", &[Words("foo".to_string())], vars), assert_eq!(expand(b"%p1%:-4.2s", &[Words("foo".to_owned())], vars),
Ok("fo ".bytes().collect::<Vec<_>>())); Ok("fo ".bytes().collect::<Vec<_>>()));
assert_eq!(expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", &[Number(1)], vars), assert_eq!(expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", &[Number(1)], vars),

View file

@ -205,28 +205,28 @@ pub fn parse(file: &mut Read, longnames: bool)
if (bools_bytes as usize) > boolnames.len() { if (bools_bytes as usize) > boolnames.len() {
return Err("incompatible file: more booleans than \ return Err("incompatible file: more booleans than \
expected".to_string()); expected".to_owned());
} }
if (numbers_count as usize) > numnames.len() { if (numbers_count as usize) > numnames.len() {
return Err("incompatible file: more numbers than \ return Err("incompatible file: more numbers than \
expected".to_string()); expected".to_owned());
} }
if (string_offsets_count as usize) > stringnames.len() { if (string_offsets_count as usize) > stringnames.len() {
return Err("incompatible file: more string offsets than \ return Err("incompatible file: more string offsets than \
expected".to_string()); expected".to_owned());
} }
// don't read NUL // don't read NUL
let bytes = try!(read_exact(file, names_bytes as usize - 1)); let bytes = try!(read_exact(file, names_bytes as usize - 1));
let names_str = match String::from_utf8(bytes) { let names_str = match String::from_utf8(bytes) {
Ok(s) => s, Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()), Err(_) => return Err("input not utf-8".to_owned()),
}; };
let term_names: Vec<String> = names_str.split('|') let term_names: Vec<String> = names_str.split('|')
.map(|s| s.to_string()) .map(str::to_owned)
.collect(); .collect();
try!(read_byte(file)); // consume NUL try!(read_byte(file)); // consume NUL
@ -236,7 +236,7 @@ pub fn parse(file: &mut Read, longnames: bool)
for i in 0..bools_bytes { for i in 0..bools_bytes {
let b = try!(read_byte(file)); let b = try!(read_byte(file));
if b == 1 { if b == 1 {
bools_map.insert(bnames[i as usize].to_string(), true); bools_map.insert(bnames[i as usize].to_owned(), true);
} }
} }
} }
@ -250,7 +250,7 @@ pub fn parse(file: &mut Read, longnames: bool)
for i in 0..numbers_count { for i in 0..numbers_count {
let n = try!(read_le_u16(file)); let n = try!(read_le_u16(file));
if n != 0xFFFF { if n != 0xFFFF {
numbers_map.insert(nnames[i as usize].to_string(), n); numbers_map.insert(nnames[i as usize].to_owned(), n);
} }
} }
} }
@ -267,7 +267,7 @@ pub fn parse(file: &mut Read, longnames: bool)
if string_table.len() != string_table_bytes as usize { if string_table.len() != string_table_bytes as usize {
return Err("error: hit EOF before end of string \ return Err("error: hit EOF before end of string \
table".to_string()); table".to_owned());
} }
for (i, v) in string_offsets.iter().enumerate() { for (i, v) in string_offsets.iter().enumerate() {
@ -285,7 +285,7 @@ pub fn parse(file: &mut Read, longnames: bool)
if offset == 0xFFFE { if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present // undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct // unsure if the handling for this is correct
string_map.insert(name.to_string(), Vec::new()); string_map.insert(name.to_owned(), Vec::new());
continue; continue;
} }
@ -301,7 +301,7 @@ pub fn parse(file: &mut Read, longnames: bool)
}, },
None => { None => {
return Err("invalid file: missing NUL in \ return Err("invalid file: missing NUL in \
string_table".to_string()); string_table".to_owned());
} }
}; };
} }
@ -338,12 +338,12 @@ fn read_exact<R: Read + ?Sized>(r: &mut R, sz: usize) -> io::Result<Vec<u8>> {
/// Create a dummy TermInfo struct for msys terminals /// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> { pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new(); let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec()); strings.insert("sgr0".to_owned(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec()); strings.insert("bold".to_owned(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec()); strings.insert("setaf".to_owned(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec()); strings.insert("setab".to_owned(), b"\x1B[4%p1%dm".to_vec());
box TermInfo { box TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version
bools: HashMap::new(), bools: HashMap::new(),
numbers: HashMap::new(), numbers: HashMap::new(),
strings: strings strings: strings

View file

@ -103,7 +103,7 @@ pub enum TestName {
DynTestName(String) DynTestName(String)
} }
impl TestName { impl TestName {
fn as_slice<'a>(&'a self) -> &'a str { fn as_slice(&self) -> &str {
match *self { match *self {
StaticTestName(s) => s, StaticTestName(s) => s,
DynTestName(ref s) => s DynTestName(ref s) => s
@ -157,13 +157,13 @@ pub enum TestFn {
impl TestFn { impl TestFn {
fn padding(&self) -> NamePadding { fn padding(&self) -> NamePadding {
match self { match *self {
&StaticTestFn(..) => PadNone, StaticTestFn(..) => PadNone,
&StaticBenchFn(..) => PadOnRight, StaticBenchFn(..) => PadOnRight,
&StaticMetricFn(..) => PadOnRight, StaticMetricFn(..) => PadOnRight,
&DynTestFn(..) => PadNone, DynTestFn(..) => PadNone,
&DynMetricFn(..) => PadOnRight, DynMetricFn(..) => PadOnRight,
&DynBenchFn(..) => PadOnRight, DynBenchFn(..) => PadOnRight,
} }
} }
} }
@ -564,9 +564,9 @@ impl<T: Write> ConsoleTestState<T> {
None => Ok(()), None => Ok(()),
Some(ref mut o) => { Some(ref mut o) => {
let s = format!("{} {}\n", match *result { let s = format!("{} {}\n", match *result {
TrOk => "ok".to_string(), TrOk => "ok".to_owned(),
TrFailed => "failed".to_string(), TrFailed => "failed".to_owned(),
TrIgnored => "ignored".to_string(), TrIgnored => "ignored".to_owned(),
TrMetrics(ref mm) => mm.fmt_metrics(), TrMetrics(ref mm) => mm.fmt_metrics(),
TrBench(ref bs) => fmt_bench_samples(bs) TrBench(ref bs) => fmt_bench_samples(bs)
}, test.name); }, test.name);
@ -925,7 +925,7 @@ pub fn filter_tests(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> Vec<TestDescA
None None
} }
}; };
filtered.into_iter().filter_map(|x| filter(x)).collect() filtered.into_iter().filter_map(filter).collect()
}; };
// Sort the tests alphabetically // Sort the tests alphabetically
@ -978,8 +978,8 @@ pub fn run_test(opts: &TestOpts,
let data = Arc::new(Mutex::new(Vec::new())); let data = Arc::new(Mutex::new(Vec::new()));
let data2 = data.clone(); let data2 = data.clone();
let cfg = thread::Builder::new().name(match desc.name { let cfg = thread::Builder::new().name(match desc.name {
DynTestName(ref name) => name.clone().to_string(), DynTestName(ref name) => name.clone(),
StaticTestName(name) => name.to_string(), StaticTestName(name) => name.to_owned(),
}); });
let result_guard = cfg.spawn(move || { let result_guard = cfg.spawn(move || {
@ -1020,7 +1020,7 @@ pub fn run_test(opts: &TestOpts,
} }
DynTestFn(f) => run_test_inner(desc, monitor_ch, opts.nocapture, f), DynTestFn(f) => run_test_inner(desc, monitor_ch, opts.nocapture, f),
StaticTestFn(f) => run_test_inner(desc, monitor_ch, opts.nocapture, StaticTestFn(f) => run_test_inner(desc, monitor_ch, opts.nocapture,
Box::new(move|| f())) Box::new(f))
} }
} }
@ -1063,7 +1063,7 @@ impl MetricMap {
noise: noise noise: noise
}; };
let MetricMap(ref mut map) = *self; let MetricMap(ref mut map) = *self;
map.insert(name.to_string(), m); map.insert(name.to_owned(), m);
} }
pub fn fmt_metrics(&self) -> String { pub fn fmt_metrics(&self) -> String {

View file

@ -168,7 +168,7 @@ impl Stats for [f64] {
let mut j = 0; let mut j = 0;
// This inner loop applies `hi`/`lo` summation to each // This inner loop applies `hi`/`lo` summation to each
// partial so that the list of partial sums remains exact. // partial so that the list of partial sums remains exact.
for i in 0..partials.len() { for mut y in &mut partials {
let mut y: f64 = partials[i]; let mut y: f64 = partials[i];
if x.abs() < y.abs() { if x.abs() < y.abs() {
mem::swap(&mut x, &mut y); mem::swap(&mut x, &mut y);