Navigation Menu

Skip to content

Commit

Permalink
Fix starts_with() and ends_with().
Browse files Browse the repository at this point in the history
d4a3238 broke these since slice_to() and slice_from() must get character
boundaries, and arbitrary needle lengths don't necessarily map to character
boundaries of the haystack.

This also adds new tests that would have caught this bug.
  • Loading branch information
metajack committed Oct 18, 2013
1 parent 3fd0e3a commit 090b245
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/libstd/str.rs
Expand Up @@ -2010,13 +2010,13 @@ impl<'self> StrSlice<'self> for &'self str {
#[inline]
fn starts_with<'a>(&self, needle: &'a str) -> bool {
let n = needle.len();
self.len() >= n && needle == self.slice_to(n)
self.len() >= n && needle.as_bytes() == self.as_bytes().slice_to(n)
}

#[inline]
fn ends_with(&self, needle: &str) -> bool {
let (m, n) = (self.len(), needle.len());
m >= n && needle == self.slice_from(m - n)
m >= n && needle.as_bytes() == self.as_bytes().slice_from(m - n)
}

fn escape_default(&self) -> ~str {
Expand Down Expand Up @@ -2886,6 +2886,8 @@ mod tests {
assert!(("abc".starts_with("a")));
assert!((!"a".starts_with("abc")));
assert!((!"".starts_with("abc")));
assert!((!"ödd".starts_with("-")));
assert!(("ödd".starts_with("öd")));
}

#[test]
Expand All @@ -2895,6 +2897,8 @@ mod tests {
assert!(("abc".ends_with("c")));
assert!((!"a".ends_with("abc")));
assert!((!"".ends_with("abc")));
assert!((!"ddö".ends_with("-")));
assert!(("ddö".ends_with("dö")));
}

#[test]
Expand Down

5 comments on commit 090b245

@bors
Copy link
Contributor

@bors bors commented on 090b245 Oct 18, 2013

Choose a reason for hiding this comment

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

saw approval from huonw
at metajack@090b245

@bors
Copy link
Contributor

@bors bors commented on 090b245 Oct 18, 2013

Choose a reason for hiding this comment

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

merging metajack/rust/fix-starts-with-ends-with = 090b245 into auto

@bors
Copy link
Contributor

@bors bors commented on 090b245 Oct 18, 2013

Choose a reason for hiding this comment

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

metajack/rust/fix-starts-with-ends-with = 090b245 merged ok, testing candidate = 71c3f8c

@bors
Copy link
Contributor

@bors bors commented on 090b245 Oct 18, 2013

@bors
Copy link
Contributor

@bors bors commented on 090b245 Oct 18, 2013

Choose a reason for hiding this comment

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

fast-forwarding master to auto = 71c3f8c

Please sign in to comment.