Skip to content

Commit

Permalink
Add OsStr starts_with and ends_with.
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed Jun 22, 2015
1 parent 4a788a2 commit cbc965e
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/libstd/ffi/os_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,18 @@ impl OsStr {
self.to_bytes().and_then(|b| CString::new(b).ok())
}

/// Returns true if the `other` is a prefix of the `OsStr`.
#[unstable(feature = "os_str_compare", reason = "recently added")]
pub fn starts_with<S: AsRef<OsStr>>(&self, other: S) -> bool {
self.bytes().starts_with(other.as_ref().bytes())
}

/// Returns true if the `other` is a suffix of the `OsStr`.
#[unstable(feature = "os_str_compare", reason = "recently added")]
pub fn ends_with<S: AsRef<OsStr>>(&self, other: S) -> bool {
self.bytes().ends_with(other.as_ref().bytes())
}

/// Gets the underlying byte representation.
///
/// Note: it is *crucial* that this API is private, to avoid
Expand Down Expand Up @@ -414,3 +426,35 @@ impl AsInner<Slice> for OsStr {
&self.inner
}
}

#[cfg(test)]
mod test {
use super::OsStr;
#[test]
fn starts_with() {
assert!(OsStr::new("abcde").starts_with(OsStr::new("abcde")));
assert!(OsStr::new("abcde").starts_with(OsStr::new("abc")));
assert!(!OsStr::new("abcde").starts_with(OsStr::new("abde")));
assert!(!OsStr::new("abcde").starts_with(OsStr::new("abcdef")));
assert!(OsStr::new("").starts_with(OsStr::new("")));
assert!(OsStr::new("anything").starts_with(OsStr::new("")));
assert!(!OsStr::new("").starts_with(OsStr::new("anything")));

// test as_ref
assert!(OsStr::new("abcde").starts_with("abc"));
}

#[test]
fn ends_with() {
assert!(OsStr::new("abcde").ends_with(OsStr::new("abcde")));
assert!(OsStr::new("abcde").ends_with(OsStr::new("cde")));
assert!(!OsStr::new("abcde").ends_with(OsStr::new("abde")));
assert!(!OsStr::new("bcde").ends_with(OsStr::new("abcde")));
assert!(OsStr::new("").ends_with(OsStr::new("")));
assert!(OsStr::new("anything").ends_with(OsStr::new("")));
assert!(!OsStr::new("").ends_with(OsStr::new("anything")));

// test as_ref
assert!(OsStr::new("abcde").ends_with("cde"));
}
}

0 comments on commit cbc965e

Please sign in to comment.