From bc29f1dfc0e60f08f4bafb8ac105f2aa7ce3a8b2 Mon Sep 17 00:00:00 2001 From: Tom Alexander Date: Tue, 22 Aug 2023 21:38:50 -0400 Subject: [PATCH] Add slicing tests. --- src/main.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1ada841..4ed11e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -76,10 +76,16 @@ where std::ops::Bound::Unbounded => self.start, }; let new_end = match range.end_bound() { - std::ops::Bound::Included(idx) => self.start + idx, - std::ops::Bound::Excluded(idx) => self.start + idx - 1, - std::ops::Bound::Unbounded => self.start, + std::ops::Bound::Included(idx) => self.start + idx + 1, + std::ops::Bound::Excluded(idx) => self.start + idx, + std::ops::Bound::Unbounded => self.end, }; + if new_start < self.start { + panic!("Attempted to extend before the start of the WrappedInput.") + } + if new_end > self.end { + panic!("Attempted to extend past the end of the WrappedInput.") + } // TODO: calculate updated values for WrappedInput WrappedInput { @@ -96,3 +102,60 @@ impl<'s> std::fmt::Display for WrappedInput<'s> { Into::<&str>::into(self).fmt(f) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn range() { + let input = WrappedInput::new("foo bar baz"); + let output = input.slice(4..7); + assert_eq!(output.to_string(), "bar"); + } + + #[test] + fn range_to() { + let input = WrappedInput::new("foo bar baz"); + let output = input.slice(..7); + assert_eq!(output.to_string(), "foo bar"); + } + + #[test] + fn range_from() { + let input = WrappedInput::new("foo bar baz"); + let output = input.slice(4..); + assert_eq!(output.to_string(), "bar baz"); + } + + #[test] + fn full_range() { + let input = WrappedInput::new("foo bar baz"); + let output = input.slice(..); + assert_eq!(output.to_string(), "foo bar baz"); + } + + #[test] + fn nested_range() { + let input = WrappedInput::new("lorem foo bar baz ipsum"); + let first_cut = input.slice(6..17); + let output = first_cut.slice(4..7); + assert_eq!(first_cut.to_string(), "foo bar baz"); + assert_eq!(output.to_string(), "bar"); + } + + #[test] + #[should_panic] + fn out_of_bounds() { + let input = WrappedInput::new("lorem foo bar baz ipsum"); + input.slice(6..30); + } + + #[test] + #[should_panic] + fn out_of_nested_bounds() { + let input = WrappedInput::new("lorem foo bar baz ipsum"); + let first_cut = input.slice(6..17); + first_cut.slice(4..14); + } +}