Skip to content

Commit

Permalink
std: add Zero impls for &[] and &str.
Browse files Browse the repository at this point in the history
  • Loading branch information
huonw committed Jun 17, 2013
1 parent d1a2360 commit f1d971a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/libstd/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2202,6 +2202,12 @@ impl<'self> Iterator<u8> for StrBytesRevIterator<'self> {
}
}

// This works because every lifetime is a sub-lifetime of 'static
impl<'self> Zero for &'self str {
fn zero() -> &'self str { "" }
fn is_zero(&self) -> bool { self.is_empty() }
}

impl Zero for ~str {
fn zero() -> ~str { ~"" }
fn is_zero(&self) -> bool { self.len() == 0 }
Expand Down Expand Up @@ -3317,4 +3323,18 @@ mod tests {
t("zzz", "zz", ~["","z"]);
t("zzzzz", "zz", ~["","","z"]);
}

#[test]
fn test_str_zero() {
use num::Zero;
fn t<S: Zero + Str>() {
let s: S = Zero::zero();
assert_eq!(s.as_slice(), "");
assert!(s.is_zero());
}

t::<&str>();
t::<@str>();
t::<~str>();
}
}
22 changes: 22 additions & 0 deletions src/libstd/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2629,6 +2629,12 @@ impl<A:Clone> Clone for ~[A] {
}
}

// This works because every lifetime is a sub-lifetime of 'static
impl<'self, A> Zero for &'self [A] {
fn zero() -> &'self [A] { &'self [] }
fn is_zero(&self) -> bool { self.is_empty() }
}

impl<A> Zero for ~[A] {
fn zero() -> ~[A] { ~[] }
fn is_zero(&self) -> bool { self.len() == 0 }
Expand Down Expand Up @@ -4293,4 +4299,20 @@ mod tests {
}
assert_eq!(v, ~[~[1,2,3],~[1,3,2],~[2,1,3],~[2,3,1],~[3,1,2],~[3,2,1]]);
}

#[test]
fn test_vec_zero() {
use num::Zero;
macro_rules! t (
($ty:ty) => {
let v: $ty = Zero::zero();
assert!(v.is_empty());
assert!(v.is_zero());
}
);

t!(&[int]);
t!(@[int]);
t!(~[int]);
}
}

1 comment on commit f1d971a

@Aatch
Copy link

@Aatch Aatch commented on f1d971a Jun 17, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

r+

Please sign in to comment.