Skip to content

Instantly share code, notes, and snippets.

@cthulahoops
Created November 20, 2018 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cthulahoops/ba0cca494b4f735140608a8bd3ca6290 to your computer and use it in GitHub Desktop.
Save cthulahoops/ba0cca494b4f735140608a8bd3ca6290 to your computer and use it in GitHub Desktop.
struct LineIterator<'a> {
iter: std::iter::Peekable<std::str::SplitWhitespace<'a>>,
width: usize,
}
impl<'a> LineIterator<'a> {
fn new(width: usize, text: &str) -> LineIterator {
LineIterator {
iter: text.split_whitespace().peekable(),
width: width,
}
}
}
impl<'a> std::iter::Iterator for LineIterator<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
let mut line = vec![];
let mut length = 0;
loop {
match self.iter.peek() {
Some(word) => {
if length == 0 || self.width > length + word.len() {
line.push(word.to_string());
length += word.len() + 1;
} else {
break;
}
}
None => {
if length == 0 {
return None;
} else {
break;
}
}
}
self.iter.next();
}
Some(line.join(" "))
}
}
fn chunk_text(width: usize, text: &str) -> Vec<String> {
LineIterator::new(width, text).collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment