Skip to content

Commit

Permalink
Make tally() nonconsuming and add into_tally()
Browse files Browse the repository at this point in the history
  • Loading branch information
havenwood committed Oct 10, 2024
1 parent 6478867 commit d924966
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
11 changes: 8 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
//! let words = WordTally::new(input, Options::default(), Filters::default());
//! let expected_tally: Box<[(Box<str>, usize)]> = [("cinquedea".into(), 1)].into();
//!
//! assert_eq!(words.tally(), expected_tally);
//! assert_eq!(words.into_tally(), expected_tally);
//! ```
use indexmap::IndexMap;
#[cfg(feature = "serde")]
Expand Down Expand Up @@ -58,7 +58,7 @@ pub struct WordTally {
/// A `tally` supports `iter` and can also be represented as a `Vec`.
impl From<WordTally> for Vec<(Box<str>, usize)> {
fn from(word_tally: WordTally) -> Self {
word_tally.tally.into_vec()
word_tally.into_tally().into_vec()
}
}

Expand Down Expand Up @@ -88,7 +88,12 @@ impl WordTally {
}

/// Gets the `tally` field.
pub fn tally(self) -> Box<[(Box<str>, usize)]> {
pub const fn tally(&self) -> &[(Box<str>, usize)] {
&self.tally
}

/// Consumes the `tally` field.
pub fn into_tally(self) -> Box<[(Box<str>, usize)]> {
self.tally
}

Expand Down
22 changes: 20 additions & 2 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ fn word_tally_test(case: Case, sort: Sort, filters: Filters, fields: &ExpectedFi
.map(|(word, count)| (Box::from(*word), *count))
.collect::<Vec<_>>()
.into_boxed_slice();
assert_eq!(word_tally.tally(), expected_tally);

assert_eq!(word_tally.tally(), expected_tally.as_ref());
}

#[test]
Expand Down Expand Up @@ -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<str>, 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();
Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit d924966

Please sign in to comment.