Skip to content

Commit

Permalink
fix: Stop lonely hyphens from causing panic
Browse files Browse the repository at this point in the history
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
  • Loading branch information
cite-reader committed Feb 3, 2016
1 parent e47f825 commit 85b1146
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
7 changes: 1 addition & 6 deletions src/osstringext.rs
Expand Up @@ -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 {
Expand Down
7 changes: 7 additions & 0 deletions tests/positionals.rs
Expand Up @@ -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", "-"]);
}

0 comments on commit 85b1146

Please sign in to comment.