From 85b11468b0189d5cc15f1cfac5db40d17a0077dc Mon Sep 17 00:00:00 2001 From: Alex Hill Date: Tue, 2 Feb 2016 21:05:45 -0800 Subject: [PATCH] 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 --- src/osstringext.rs | 7 +------ tests/positionals.rs | 7 +++++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/osstringext.rs b/src/osstringext.rs index 65a10064b78..5e179ba6050 100644 --- a/src/osstringext.rs +++ b/src/osstringext.rs @@ -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 { diff --git a/tests/positionals.rs b/tests/positionals.rs index 9994838e04a..5c81934f3f6 100644 --- a/tests/positionals.rs +++ b/tests/positionals.rs @@ -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", "-"]); +}