use std::ops::Deref;
use crate::core::{display_width, Word};
pub trait WordSplitter: WordSplitterClone + std::fmt::Debug {
fn split_points(&self, word: &str) -> Vec<usize>;
}
#[doc(hidden)]
pub trait WordSplitterClone {
fn clone_box(&self) -> Box<dyn WordSplitter>;
}
impl<T: WordSplitter + Clone + 'static> WordSplitterClone for T {
fn clone_box(&self) -> Box<dyn WordSplitter> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn WordSplitter> {
fn clone(&self) -> Box<dyn WordSplitter> {
self.deref().clone_box()
}
}
impl WordSplitter for Box<dyn WordSplitter> {
fn split_points(&self, word: &str) -> Vec<usize> {
self.deref().split_points(word)
}
}
#[derive(Clone, Copy, Debug)]
pub struct NoHyphenation;
impl WordSplitter for NoHyphenation {
fn split_points(&self, _: &str) -> Vec<usize> {
Vec::new()
}
}
#[derive(Clone, Copy, Debug)]
pub struct HyphenSplitter;
impl WordSplitter for HyphenSplitter {
fn split_points(&self, word: &str) -> Vec<usize> {
let mut splits = Vec::new();
for (idx, _) in word.match_indices('-') {
let prev = word[..idx].chars().next_back();
let next = word[idx + 1..].chars().next();
if prev.filter(|ch| ch.is_alphanumeric()).is_some()
&& next.filter(|ch| ch.is_alphanumeric()).is_some()
{
splits.push(idx + 1); }
}
splits
}
}
#[cfg(feature = "hyphenation")]
impl WordSplitter for hyphenation::Standard {
fn split_points(&self, word: &str) -> Vec<usize> {
use hyphenation::Hyphenator;
self.hyphenate(word).breaks
}
}
pub fn split_words<'a, I, WordSplit>(
words: I,
word_splitter: &'a WordSplit,
) -> impl Iterator<Item = Word<'a>>
where
I: IntoIterator<Item = Word<'a>>,
WordSplit: WordSplitter,
{
words.into_iter().flat_map(move |word| {
let mut prev = 0;
let mut split_points = word_splitter.split_points(&word).into_iter();
std::iter::from_fn(move || {
if let Some(idx) = split_points.next() {
let need_hyphen = !word[..idx].ends_with('-');
let w = Word {
word: &word.word[prev..idx],
width: display_width(&word[prev..idx]),
whitespace: "",
penalty: if need_hyphen { "-" } else { "" },
};
prev = idx;
return Some(w);
}
if prev < word.word.len() || prev == 0 {
let w = Word {
word: &word.word[prev..],
width: display_width(&word[prev..]),
whitespace: word.whitespace,
penalty: word.penalty,
};
prev = word.word.len() + 1;
return Some(w);
}
None
})
})
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! assert_iter_eq {
($left:expr, $right:expr) => {
assert_eq!($left.collect::<Vec<_>>(), $right);
};
}
#[test]
fn split_words_no_words() {
assert_iter_eq!(split_words(vec![], &HyphenSplitter), vec![]);
}
#[test]
fn split_words_empty_word() {
assert_iter_eq!(
split_words(vec![Word::from(" ")], &HyphenSplitter),
vec![Word::from(" ")]
);
}
#[test]
fn split_words_single_word() {
assert_iter_eq!(
split_words(vec![Word::from("foobar")], &HyphenSplitter),
vec![Word::from("foobar")]
);
}
#[test]
fn split_words_hyphen_splitter() {
assert_iter_eq!(
split_words(vec![Word::from("foo-bar")], &HyphenSplitter),
vec![Word::from("foo-"), Word::from("bar")]
);
}
#[test]
fn split_words_adds_penalty() {
#[derive(Clone, Debug)]
struct FixedSplitPoint;
impl WordSplitter for FixedSplitPoint {
fn split_points(&self, _: &str) -> Vec<usize> {
vec![3]
}
}
assert_iter_eq!(
split_words(vec![Word::from("foobar")].into_iter(), &FixedSplitPoint),
vec![
Word {
word: "foo",
width: 3,
whitespace: "",
penalty: "-"
},
Word {
word: "bar",
width: 3,
whitespace: "",
penalty: ""
}
]
);
assert_iter_eq!(
split_words(vec![Word::from("fo-bar")].into_iter(), &FixedSplitPoint),
vec![
Word {
word: "fo-",
width: 3,
whitespace: "",
penalty: ""
},
Word {
word: "bar",
width: 3,
whitespace: "",
penalty: ""
}
]
);
}
}