Skip to content

Commit

Permalink
Fix panic trim_first_and_last_line_of_whitespace on bad slice indic…
Browse files Browse the repository at this point in the history
…es (#865)

* Fix panic from slice end being before slice start

* Fix fallback value for end index

Co-authored-by: XAMPPRocky <4464295+XAMPPRocky@users.noreply.github.com>
  • Loading branch information
CosmicHorrorDev and XAMPPRocky authored Dec 20, 2021
1 parent 46d447f commit 0152709
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 2 deletions.
78 changes: 78 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ optional = true
version = "0.8.15"

[dev-dependencies]
proptest = "1.0.0"
strum = "0.23.0"
strum_macros = "0.23.0"
regex = "1.4.6"
Expand Down
22 changes: 20 additions & 2 deletions src/utils/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ impl SliceExt for [u8] {
.iter()
.rposition(|c| c.is_line_ending_whitespace() || !c.is_whitespace())
.map_or_else(
|| self.len(),
|| self.len().saturating_sub(1),
|i| {
if self[i.saturating_sub(1)] == b'\r' {
// Remove the entire `\r\n` in the case that it was the line ending whitespace
if self[i.saturating_sub(1)] == b'\r' && self[i] == b'\n' {
i - 1
} else {
i
Expand Down Expand Up @@ -114,6 +115,8 @@ impl SliceExt for [u8] {
mod tests {
use super::*;

use proptest::prelude::*;

#[test]
fn is_whitespace() {
assert!(b' '.is_whitespace());
Expand Down Expand Up @@ -142,4 +145,19 @@ mod tests {
assert!([1, 2, 3, 4, 5].contains_slice(&[2, 3, 4]));
assert!(![1, 2, 3, 4, 5].contains_slice(&[]));
}

#[test]
fn trim_first_and_last_line_of_whitespace_edge_cases() {
assert_eq!(b"", b"\ra ".trim_first_and_last_line_of_whitespace());
assert_eq!(b"a", b"\r\na ".trim_first_and_last_line_of_whitespace());

assert_eq!(b" ", b" ".trim_first_and_last_line_of_whitespace());
}

proptest! {
#[test]
fn trim_first_and_last_line_of_whitespace_doesnt_panic(input: Vec<u8>) {
let _ = &input.trim_first_and_last_line_of_whitespace();
}
}
}

0 comments on commit 0152709

Please sign in to comment.