1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//! # extract-words
//!
//! Extracts words from text without allocation
//!
//! ## Examples
//!
//! Iteration through words, discarding punctuation
//! ```
//! # use extract_words::extract_words;
//! let mut words = extract_words("¿Cómo estás?");
//! assert_eq!(words.next().unwrap(), "Cómo");
//! assert_eq!(words.next().unwrap(), "estás");
//! assert!(words.next().is_none());
//! ```
//!
//! Iteration through all entries
//! ```
//! # use extract_words::{Entries, Entry};
//! let mut entries = Entries::new("Bien :)");
//! assert_eq!(entries.next().unwrap(), Entry::Word("Bien"));
//! assert_eq!(entries.next().unwrap(), Entry::Other(" :)"));
//! assert!(entries.next().is_none());
//! ```

#![warn(clippy::all, missing_docs, nonstandard_style, future_incompatible)]

/// Extracts words from the text discarding punctuation
pub fn extract_words(text: &str) -> impl Iterator<Item = &str> {
    Entries::new(text).filter_map(|e| match e {
        Entry::Word(s) => Some(s),
        Entry::Other(_) => None,
    })
}

/// An iterator over text entries
pub struct Entries<'a> {
    text: &'a str,
    char_indices: std::str::CharIndices<'a>,
    cur_entry: CurEntry,
}

/// Text entry
#[derive(Debug, PartialEq)]
pub enum Entry<'a> {
    /// Punctuation, spaces, etc
    Other(&'a str),
    /// Word
    Word(&'a str),
}

enum CurEntry {
    None,
    Other(usize),
    Word(usize),
}

impl<'a> Entries<'a> {
    /// Creates an iterator over the text entries
    pub fn new(text: &'a str) -> Self {
        Entries {
            text,
            char_indices: text.char_indices(),
            cur_entry: CurEntry::None,
        }
    }
}

impl<'a> Iterator for Entries<'a> {
    type Item = Entry<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        for (i, c) in self.char_indices.by_ref() {
            if c.is_alphanumeric() {
                match self.cur_entry {
                    CurEntry::None => self.cur_entry = CurEntry::Word(i),
                    CurEntry::Other(start) => {
                        self.cur_entry = CurEntry::Word(i);
                        return Some(Entry::Other(&self.text[start..i]));
                    }
                    CurEntry::Word(_) => (),
                }
            } else {
                match self.cur_entry {
                    CurEntry::None => self.cur_entry = CurEntry::Other(i),
                    CurEntry::Other(_) => (),
                    CurEntry::Word(start) => {
                        self.cur_entry = CurEntry::Other(i);
                        return Some(Entry::Word(&self.text[start..i]));
                    }
                }
            }
        }

        match self.cur_entry {
            CurEntry::None => None,
            CurEntry::Other(start) => {
                self.cur_entry = CurEntry::None;
                if start < self.text.len() {
                    Some(Entry::Other(&self.text[start..]))
                } else {
                    None
                }
            }
            CurEntry::Word(start) => {
                self.cur_entry = CurEntry::None;
                if start < self.text.len() {
                    Some(Entry::Word(&self.text[start..]))
                } else {
                    None
                }
            }
        }
    }
}

impl<'a> AsRef<str> for Entry<'a> {
    fn as_ref(&self) -> &str {
        match self {
            Entry::Other(s) => s,
            Entry::Word(s) => s,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::extract_words;

    fn extract_vec(text: &str) -> Vec<&str> {
        extract_words(text).collect()
    }

    #[test]
    fn test_empty_string() {
        assert!(extract_vec("").is_empty());
    }

    #[test]
    fn test_punctuation_only() {
        assert!(extract_vec(".,!?-").is_empty());
    }

    #[test]
    fn test_mixed_input() {
        assert_eq!(
            extract_vec("Hola,mundo! ¿Cómo estás?"),
            ["Hola", "mundo", "Cómo", "estás"]
        );
    }

    #[test]
    fn test_multiple_delimiters() {
        assert_eq!(extract_vec("Hola, mundo!¿ .. !¿á"), ["Hola", "mundo", "á"]);
    }
}