diff options
| author | Kevin Ballard <kevin@sb.org> | 2013-10-16 22:01:20 -0700 |
|---|---|---|
| committer | Kevin Ballard <kevin@sb.org> | 2013-10-16 23:17:30 -0700 |
| commit | 2fcb53493dc80469acf86797c53dacc331629d50 (patch) | |
| tree | 4e1ae819fcc549cbe6e9369289ccde046adedac5 /src/libstd | |
| parent | d8f82c8e431472e9a1742a6923790b1f32e6e248 (diff) | |
| download | rust-2fcb53493dc80469acf86797c53dacc331629d50.tar.gz rust-2fcb53493dc80469acf86797c53dacc331629d50.zip | |
Implement new methods vec.starts_with()/vec.ends_with()
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/vec.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 694f3344cc2..17dcced9485 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -1173,6 +1173,12 @@ pub trait ImmutableEqVector<T:Eq> { /// Return true if a vector contains an element with the given value fn contains(&self, x: &T) -> bool; + + /// Returns true if `needle` is a prefix of the vector. + fn starts_with(&self, needle: &[T]) -> bool; + + /// Returns true if `needle` is a suffix of the vector. + fn ends_with(&self, needle: &[T]) -> bool; } impl<'self,T:Eq> ImmutableEqVector<T> for &'self [T] { @@ -1190,6 +1196,18 @@ impl<'self,T:Eq> ImmutableEqVector<T> for &'self [T] { fn contains(&self, x: &T) -> bool { self.iter().any(|elt| *x == *elt) } + + #[inline] + fn starts_with(&self, needle: &[T]) -> bool { + let n = needle.len(); + self.len() >= n && needle == self.slice_to(n) + } + + #[inline] + fn ends_with(&self, needle: &[T]) -> bool { + let (m, n) = (self.len(), needle.len()); + m >= n && needle == self.slice_from(m - n) + } } /// Extension methods for vectors containing `TotalOrd` elements. @@ -3828,6 +3846,34 @@ mod tests { assert_eq!(xs.capacity(), 100); assert_eq!(xs, range(0, 100).to_owned_vec()); } + + #[test] + fn test_starts_with() { + assert!(bytes!("foobar").starts_with(bytes!("foo"))); + assert!(!bytes!("foobar").starts_with(bytes!("oob"))); + assert!(!bytes!("foobar").starts_with(bytes!("bar"))); + assert!(!bytes!("foo").starts_with(bytes!("foobar"))); + assert!(!bytes!("bar").starts_with(bytes!("foobar"))); + assert!(bytes!("foobar").starts_with(bytes!("foobar"))); + let empty: &[u8] = []; + assert!(empty.starts_with(empty)); + assert!(!empty.starts_with(bytes!("foo"))); + assert!(bytes!("foobar").starts_with(empty)); + } + + #[test] + fn test_ends_with() { + assert!(bytes!("foobar").ends_with(bytes!("bar"))); + assert!(!bytes!("foobar").ends_with(bytes!("oba"))); + assert!(!bytes!("foobar").ends_with(bytes!("foo"))); + assert!(!bytes!("foo").ends_with(bytes!("foobar"))); + assert!(!bytes!("bar").ends_with(bytes!("foobar"))); + assert!(bytes!("foobar").ends_with(bytes!("foobar"))); + let empty: &[u8] = []; + assert!(empty.ends_with(empty)); + assert!(!empty.ends_with(bytes!("foo"))); + assert!(bytes!("foobar").ends_with(empty)); + } } #[cfg(test)] |
