commit fc7ec7a5988530b59b03d018cd2761612d651c47
parent e59fbb54454d53b0c169759f9f649d15242c72e9
Author: Yuval Langer <yuval.langer@gmail.com>
Date: Wed, 6 Nov 2024 03:43:06 +0200
Add the end-of-file case for the single word from die rolls reading function.
Diffstat:
M | src/main.rs | | | 46 | +++++++++++++++++++++++++++++++++++++--------- |
1 file changed, 37 insertions(+), 9 deletions(-)
diff --git a/src/main.rs b/src/main.rs
@@ -78,6 +78,31 @@ fn print_words(
println!();
}
+struct ReadWords<'a, T: std::iter::Iterator> {
+ bytes_iter: &'a mut std::iter::Peekable<T>,
+ wordlist: &'a Vec<&'a str>
+}
+
+impl<'a, T: std::iter::Iterator> ReadWords<'a, T> {
+ fn new(
+ bytes_iter: &'a mut std::iter::Peekable<T>,
+ wordlist: &'a Vec<&'a str>
+ ) -> ReadWords<'a, T> {
+ ReadWords {
+ bytes_iter,
+ wordlist,
+ }
+ }
+}
+
+impl<'a, T: std::iter::Iterator<Item = Result<u8, std::io::Error>> + std::fmt::Display> Iterator for ReadWords<'a, T> {
+ type Item = String;
+
+ fn next(&mut self) -> Option<<Self as Iterator>::Item> {
+ return read_single_word::<T, T>(self.bytes_iter, self.wordlist);
+ }
+}
+
fn read_single_word<T: std::iter::Iterator<Item = Result<u8, std::io::Error>>, U: std::fmt::Display + ?Sized>(bytes_iter: &mut std::iter::Peekable<T>, wordlist: &Vec<&str>) -> Option<String> {
let die_cast_per_word = die_cast_per_word(wordlist.len());
let mut word_index = 0;
@@ -113,6 +138,12 @@ fn read_single_word<T: std::iter::Iterator<Item = Result<u8, std::io::Error>>, U
}
};
} else {
+ if die_significance == 0 {
+ match bytes_iter.peek() {
+ None => return None,
+ Some(_) => {},
+ }
+ }
let current_byte_result = match bytes_iter.next() {
Some(x) => {
x
@@ -153,7 +184,7 @@ fn read_single_word<T: std::iter::Iterator<Item = Result<u8, std::io::Error>>, U
fn read_words_from_rolls<U: std::fmt::Display + ?Sized>(wordlist: &Vec<&str>) -> Vec<String> {
let stdin = std::io::stdin();
- let mut words: Vec<String> = Vec::new();
+ let mut words = Vec::new();
let mut bytes_iter = stdin.bytes().peekable();
loop {
@@ -168,6 +199,11 @@ fn read_words_from_rolls<U: std::fmt::Display + ?Sized>(wordlist: &Vec<&str>) ->
}
};
+ // TODO: Maybe use an iterator?
+ // for word in ReadWords::new(&mut bytes_iter, wordlist) {
+ // words.push(word)
+ // };
+
words
}
@@ -291,14 +327,6 @@ fn main() {
mod tests {
use super::*;
- /*
- #[test]
- fn test_rolls_to_word_index_01() {
- assert_eq!(0, rolls_to_word_index(3, &[1, 1, 1]));
- assert_eq!(1, rolls_to_word_index(3, &[1, 1, 2]));
- }
- */
-
#[test]
fn test_read_single_word() {
let wordlist = Wordlist::default().get_list().to_vec();