From d92496691878ab6018c1222344635771afbeaf26 Mon Sep 17 00:00:00 2001 From: Shannon Skipper Date: Thu, 10 Oct 2024 21:53:14 +0000 Subject: [PATCH] Make `tally()` nonconsuming and add `into_tally()` --- src/lib.rs | 11 ++++++++--- tests/lib.rs | 22 ++++++++++++++++++++-- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index bbdc109..e32437c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,7 +27,7 @@ //! let words = WordTally::new(input, Options::default(), Filters::default()); //! let expected_tally: Box<[(Box, usize)]> = [("cinquedea".into(), 1)].into(); //! -//! assert_eq!(words.tally(), expected_tally); +//! assert_eq!(words.into_tally(), expected_tally); //! ``` use indexmap::IndexMap; #[cfg(feature = "serde")] @@ -58,7 +58,7 @@ pub struct WordTally { /// A `tally` supports `iter` and can also be represented as a `Vec`. impl From for Vec<(Box, usize)> { fn from(word_tally: WordTally) -> Self { - word_tally.tally.into_vec() + word_tally.into_tally().into_vec() } } @@ -88,7 +88,12 @@ impl WordTally { } /// Gets the `tally` field. - pub fn tally(self) -> Box<[(Box, usize)]> { + pub const fn tally(&self) -> &[(Box, usize)] { + &self.tally + } + + /// Consumes the `tally` field. + pub fn into_tally(self) -> Box<[(Box, usize)]> { self.tally } diff --git a/tests/lib.rs b/tests/lib.rs index b418e72..c2dbe97 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -30,7 +30,8 @@ fn word_tally_test(case: Case, sort: Sort, filters: Filters, fields: &ExpectedFi .map(|(word, count)| (Box::from(*word), *count)) .collect::>() .into_boxed_slice(); - assert_eq!(word_tally.tally(), expected_tally); + + assert_eq!(word_tally.tally(), expected_tally.as_ref()); } #[test] @@ -277,6 +278,23 @@ fn vec_from() { ); } +#[test] +fn test_into_tally() { + let input = b"bye bye birdy"; + let options = Options::default(); + let filters = Filters::default(); + + let word_tally = WordTally::new(&input[..], options, filters); + + // Use `tally()` to get a reference to the slice. + let tally = word_tally.tally(); + + let expected_tally: Box<[(Box, usize)]> = + vec![("bye".into(), 2), ("birdy".into(), 1)].into_boxed_slice(); + + assert_eq!(tally, expected_tally.as_ref()); +} + #[test] fn test_excluding_words() { let input = "The tree that would grow to heaven must send its roots to hell.".as_bytes(); @@ -315,7 +333,7 @@ fn test_only_words() { let expected = vec![(Box::from("chaos"), 2), (Box::from("star"), 1)].into_boxed_slice(); - assert_eq!(result, expected); + assert_eq!(result, expected.as_ref()); } #[test]