Auto merge of #411 - cite-reader:hyphen-doesnt-panic, r=kbknapp

fix: Stop lonely hyphens from causing panic

The method `starts_with` as implemented for the `OsStrExt2` trait on
`OsStr` assumed that the needle given is shorter than the haystack. When
this is not the case, the method panics due to an attempted
out-of-bounds access on the byte representation of `self`. Problematic
if, say, an end-user gives us `"-"` and the library tries to see if that
starts with `"--"`.

Fortunately, slices already implement a `starts_with` method, and we can
delegate to it.

This *does* create a semantics change: if both `self` and the needle
have length 0, this implementation will return `true`, but the old
implementation would return `false`. Based on the test suite still
passing, acknowledging the vacuous truth doesn't seem to cause any
problems.

Fixes #410
This commit is contained in:
Homu 2016-02-04 16:15:31 +09:00
commit 355a5fdabd
2 changed files with 8 additions and 6 deletions

View file

@ -36,12 +36,7 @@ impl OsStrExt3 for OsStr {
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool {
let sab = self.as_bytes();
if sab.is_empty() { return false; }
for (i, b) in s.iter().enumerate() {
if *b != sab[i] { return false; }
}
true
self.as_bytes().starts_with(s)
}
fn is_empty(&self) -> bool {

View file

@ -132,3 +132,10 @@ fn create_positional() {
.help("testing testing"))
.get_matches();
}
#[test]
fn positional_hyphen_does_not_panic() {
let _ = App::new("test")
.arg(Arg::with_name("dummy"))
.get_matches_from(vec!["test", "-"]);
}