| 1 | //! This module provides two interfaces for accessing clusters from an underlying string. The |
| 2 | //! `GraphemeCluster` trait extends the `Peekable` iterators over `Chars` or `CharIndices` |
| 3 | //! to add a `next_cluster` method which returns `Option<String>` with the next |
| 4 | //! cluster if one exists. This is the best method for getting individual clusters from a stream which is normally |
| 5 | //! only getting `char`s but is not recommended if you wish to iterate over clusters. |
| 6 | //! ``` |
| 7 | //! # use crate::finl_unicode::grapheme_clusters::GraphemeCluster; |
| 8 | //! let mut char_iterator = "A\u{301}✋🏽🇦🇹!".chars().peekable(); |
| 9 | //! assert_eq!(char_iterator.next_cluster(), Some("A\u{301}".to_string())); |
| 10 | //! assert_eq!(char_iterator.next_cluster(), Some("✋🏽".to_string())); |
| 11 | //! assert_eq!(char_iterator.next_cluster(), Some("🇦🇹".to_string())); |
| 12 | //! assert_eq!(char_iterator.next_cluster(), Some("!".to_string())); |
| 13 | //! assert_eq!(char_iterator.next_cluster(), None); |
| 14 | //! ``` |
| 15 | //! |
| 16 | //! For the iterating over clusters case there is a struct `Graphemes` which implements `iterator` |
| 17 | //! and can be constructed from a `&str`. This returns references to substrings of the original |
| 18 | //! `&str` and is more performant for that case than the extended iterator provided through |
| 19 | //! `GraphemeCluster` which allocates a new `String` for each cluster found. |
| 20 | //! ``` |
| 21 | //! # use crate::finl_unicode::grapheme_clusters::Graphemes; |
| 22 | //! let graphemes = Graphemes::new("A\u{301}✋🏽🇦🇹!"); |
| 23 | //! assert_eq!(graphemes.collect::<Vec<&str>>(), ["A\u{301}", "✋🏽", "🇦🇹", "!"]) |
| 24 | //! ``` |
| 25 | |
| 26 | use std::iter::Peekable; |
| 27 | use std::str::CharIndices; |
| 28 | use crate::data::grapheme_property::{GP_PAGES,GP_TABLE}; |
| 29 | |
| 30 | |
| 31 | /// `Graphemes` provides an iterator over the grapheme clusters of a string. |
| 32 | pub struct Graphemes<'a> { |
| 33 | input: &'a str, |
| 34 | iter: Peekable<CharIndices<'a>>, |
| 35 | } |
| 36 | |
| 37 | impl<'a> Graphemes<'a> { |
| 38 | /// A new instance of graphemes can be constructed from a string using `Graphemes::new` |
| 39 | /// ``` |
| 40 | /// # use crate::finl_unicode::grapheme_clusters::Graphemes; |
| 41 | /// let graphemes = Graphemes::new("some string"); |
| 42 | /// ``` |
| 43 | pub fn new(input: &'a str) -> Graphemes<'a> { |
| 44 | let iter = input.char_indices().peekable(); |
| 45 | Graphemes { |
| 46 | input, |
| 47 | iter |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | impl<'a> Iterator for Graphemes<'a> { |
| 53 | type Item = &'a str; |
| 54 | #[inline] |
| 55 | /// Return a slice of the underlying |
| 56 | /// string corresponding to the next cluster if one exists, or `None` if the end of the string |
| 57 | /// has been reached. |
| 58 | fn next(&mut self) -> Option<Self::Item> { |
| 59 | if let Some(&(start, _)) = self.iter.peek() { |
| 60 | let mut cluster_machine = ClusterMachine::new(); |
| 61 | loop { |
| 62 | if let Some(&(curr_loc, ch)) = self.iter.peek() { |
| 63 | match cluster_machine.find_cluster(ch) { |
| 64 | Break::None => { self.iter.next(); } |
| 65 | Break::Before => { |
| 66 | return Some(&self.input[start..curr_loc]); |
| 67 | } |
| 68 | Break::After => { |
| 69 | self.iter.next(); |
| 70 | return Some( |
| 71 | if let Some(&(curr_loc, _)) = self.iter.peek() { |
| 72 | &self.input[start..curr_loc] |
| 73 | } else { |
| 74 | &self.input[start..] |
| 75 | }); |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | else { |
| 80 | return Some(&self.input[start..]); |
| 81 | } |
| 82 | } |
| 83 | } else { |
| 84 | None |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | /// Get the next grapheme cluster from a stream of characters or char indices |
| 90 | /// This trait is implemented for any `Peekable` iterator over either `char` or `(usize, char)` (so |
| 91 | /// it will work on `Peekable<Chars>` and `Peekable<CharIndices>` as well as any other peekable iterator |
| 92 | /// which meets this requirement. |
| 93 | pub trait GraphemeCluster<T> { |
| 94 | fn next_cluster(&mut self) -> Option<String>; |
| 95 | } |
| 96 | |
| 97 | impl<T> GraphemeCluster<T> for T where T: PeekChar { |
| 98 | /// Returns the next cluster if there is one in an `Option<String>`. Since this has a heap allocation |
| 99 | /// it is *not* recommended for iterating over all the clusters in a string. In that case, use |
| 100 | /// `Graphemes` instead. |
| 101 | #[inline] |
| 102 | fn next_cluster(&mut self) -> Option<String> { |
| 103 | if self.has_next() { |
| 104 | let mut cluster_machine = ClusterMachine::new(); |
| 105 | let mut rv = String::new(); |
| 106 | loop { |
| 107 | if let Some(ch) = self.peek_char() { |
| 108 | let state = cluster_machine.find_cluster(ch); |
| 109 | match state { |
| 110 | Break::None => { |
| 111 | rv.push(ch); |
| 112 | self.next(); |
| 113 | } |
| 114 | Break::Before => { return Some(rv); } |
| 115 | Break::After => { |
| 116 | rv.push(ch); |
| 117 | self.next(); |
| 118 | return Some(rv); |
| 119 | } |
| 120 | } |
| 121 | } else { |
| 122 | break; |
| 123 | } |
| 124 | } |
| 125 | Some(rv) |
| 126 | } else { |
| 127 | None |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | } |
| 132 | |
| 133 | /// This trait exists primarily to allow a single implementation to be used for both `Peekable<Chars>` |
| 134 | /// and `Peekable<CharIndices>`. You could implement this for some other iterator if you like as |
| 135 | /// long as you can implement the two methods below. |
| 136 | pub trait PeekChar: Iterator { |
| 137 | /// Returns the next character (if it exists) or `None` otherwise. |
| 138 | fn peek_char(&mut self) -> Option<char>; |
| 139 | /// Returns `true` if there is another character available on the iterator, `false` otherwise. |
| 140 | fn has_next(&mut self) -> bool; |
| 141 | } |
| 142 | |
| 143 | trait HasChar { |
| 144 | fn get_char(& self) -> char; |
| 145 | } |
| 146 | |
| 147 | impl HasChar for char { |
| 148 | fn get_char(& self) -> char { |
| 149 | *self |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | impl HasChar for (usize, char) { |
| 154 | fn get_char(&self) -> char { |
| 155 | self.1 |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | impl<CharIter, C: HasChar> PeekChar for Peekable<CharIter> |
| 160 | where CharIter: Iterator<Item = C> |
| 161 | { |
| 162 | #[inline] |
| 163 | fn peek_char(&mut self) -> Option<char> { |
| 164 | self.peek().map(|c| c.get_char()) |
| 165 | } |
| 166 | |
| 167 | #[inline] |
| 168 | fn has_next(&mut self) -> bool { |
| 169 | self.peek().is_some() |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | // ------------------------ |
| 174 | // Private implementation details follow |
| 175 | |
| 176 | #[derive(PartialEq)] |
| 177 | enum ClusterMachineState { |
| 178 | Start, |
| 179 | Precore, |
| 180 | CcsBase, |
| 181 | CrLf, |
| 182 | HangulSyllableL, |
| 183 | HangulSyllableV, |
| 184 | HangulSyllableT, |
| 185 | CcsExtend, |
| 186 | Flag, |
| 187 | Emoji, |
| 188 | EmojiZWJ, |
| 189 | IndicClusterStart, |
| 190 | IndicClusterExtend, |
| 191 | Other, |
| 192 | } |
| 193 | |
| 194 | #[derive(Debug, PartialEq)] |
| 195 | enum Break { |
| 196 | None, |
| 197 | Before, |
| 198 | After, |
| 199 | } |
| 200 | |
| 201 | struct ClusterMachine { |
| 202 | state: ClusterMachineState, |
| 203 | } |
| 204 | |
| 205 | impl ClusterMachine { |
| 206 | #[inline] |
| 207 | pub fn new() -> ClusterMachine { |
| 208 | ClusterMachine { |
| 209 | state: ClusterMachineState::Start, |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// If we have a cluster, we return the cluster in a `String` in an `Option` long with a `bool` |
| 214 | /// If the `bool` is true, it means that we are also consuming the character in the cluster. |
| 215 | #[inline] |
| 216 | pub fn find_cluster(&mut self, c: char) -> Break { |
| 217 | if self.state == ClusterMachineState::Start { |
| 218 | return self.first_character(c); |
| 219 | } |
| 220 | let property = get_property(c); |
| 221 | |
| 222 | if property == GraphemeProperty::CONTROL { |
| 223 | return if self.state == ClusterMachineState::CrLf && c == '\n' { |
| 224 | self.state = ClusterMachineState::Start; |
| 225 | Break::After |
| 226 | } else { |
| 227 | if c == '\r' { |
| 228 | self.state = ClusterMachineState::CrLf; |
| 229 | } else { |
| 230 | self.state = ClusterMachineState::Start; |
| 231 | } |
| 232 | Break::Before |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | match self.state { |
| 237 | ClusterMachineState::Start => self.first_character(c), |
| 238 | ClusterMachineState::Precore => { |
| 239 | self.first_character(c); |
| 240 | Break::None |
| 241 | } |
| 242 | ClusterMachineState::HangulSyllableL => { |
| 243 | match property { |
| 244 | GraphemeProperty::L => Break::None, |
| 245 | GraphemeProperty::V | GraphemeProperty::LV => { |
| 246 | self.state = ClusterMachineState::HangulSyllableV; |
| 247 | Break::None |
| 248 | } |
| 249 | GraphemeProperty::LVT => { |
| 250 | self.state = ClusterMachineState::HangulSyllableT; |
| 251 | Break::None |
| 252 | } |
| 253 | GraphemeProperty::EXTEND | GraphemeProperty::SPACING_MARK | GraphemeProperty::IN_LINKER | GraphemeProperty::ZWJ => { |
| 254 | self.state = ClusterMachineState::CcsBase; |
| 255 | Break::None |
| 256 | } |
| 257 | _ => { |
| 258 | self.first_character(c); |
| 259 | Break::Before |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | ClusterMachineState::HangulSyllableV => { |
| 264 | match property { |
| 265 | GraphemeProperty::V => Break::None, |
| 266 | GraphemeProperty::T => { |
| 267 | self.state = ClusterMachineState::HangulSyllableT; |
| 268 | Break::None |
| 269 | } |
| 270 | GraphemeProperty::EXTEND | GraphemeProperty::SPACING_MARK | GraphemeProperty::IN_LINKER | GraphemeProperty::ZWJ => { |
| 271 | self.state = ClusterMachineState::CcsBase; |
| 272 | Break::None |
| 273 | } |
| 274 | _ => { |
| 275 | self.first_character(c); |
| 276 | Break::Before |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | ClusterMachineState::HangulSyllableT => { |
| 281 | match property { |
| 282 | GraphemeProperty::T => Break::None, |
| 283 | GraphemeProperty::EXTEND | GraphemeProperty::SPACING_MARK | GraphemeProperty::IN_LINKER | GraphemeProperty::ZWJ => { |
| 284 | self.state = ClusterMachineState::CcsBase; |
| 285 | Break::None |
| 286 | } |
| 287 | _ => { |
| 288 | self.first_character(c); |
| 289 | Break::Before |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | ClusterMachineState::CcsExtend => { |
| 294 | match property { |
| 295 | GraphemeProperty::EXTEND |
| 296 | | GraphemeProperty::SPACING_MARK |
| 297 | | GraphemeProperty::IN_LINKER |
| 298 | | GraphemeProperty::ZWJ => Break::None, |
| 299 | _ => Break::Before |
| 300 | } |
| 301 | } |
| 302 | ClusterMachineState::Flag => { |
| 303 | self.state = ClusterMachineState::Start; |
| 304 | match property { |
| 305 | GraphemeProperty::REGIONAL_INDICATOR => { |
| 306 | self.state = ClusterMachineState::Other; |
| 307 | Break::None |
| 308 | } |
| 309 | GraphemeProperty::EXTEND |
| 310 | | GraphemeProperty::SPACING_MARK |
| 311 | | GraphemeProperty::IN_LINKER |
| 312 | | GraphemeProperty::ZWJ => { |
| 313 | self.state = ClusterMachineState::CcsExtend; |
| 314 | Break::None |
| 315 | } |
| 316 | _ => { |
| 317 | self.first_character(c); |
| 318 | Break::Before |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | ClusterMachineState::Emoji => { |
| 323 | match property { |
| 324 | GraphemeProperty::ZWJ => { |
| 325 | self.state = ClusterMachineState::EmojiZWJ; |
| 326 | Break::None |
| 327 | } |
| 328 | GraphemeProperty::EXTEND | GraphemeProperty::SPACING_MARK | GraphemeProperty::IN_LINKER => { |
| 329 | self.state = ClusterMachineState::Emoji; |
| 330 | Break::None |
| 331 | } |
| 332 | _ => { |
| 333 | self.first_character(c); |
| 334 | Break::Before |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | ClusterMachineState::EmojiZWJ => { |
| 339 | if property == GraphemeProperty::EXTENDED_GRAPHEME { |
| 340 | self.state = ClusterMachineState::Emoji; |
| 341 | Break::None |
| 342 | } else { |
| 343 | Break::Before |
| 344 | } |
| 345 | } |
| 346 | ClusterMachineState::CrLf => Break::Before, |
| 347 | ClusterMachineState::IndicClusterStart => { |
| 348 | match property { |
| 349 | GraphemeProperty::IN_LINKER => { |
| 350 | self.state = ClusterMachineState::IndicClusterExtend; |
| 351 | Break::None |
| 352 | } |
| 353 | GraphemeProperty::EXTEND | GraphemeProperty::ZWJ | GraphemeProperty::SPACING_MARK=> { |
| 354 | Break::None |
| 355 | } |
| 356 | _ => { |
| 357 | self.first_character(c); |
| 358 | Break::Before |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | ClusterMachineState::IndicClusterExtend => { |
| 363 | match property { |
| 364 | GraphemeProperty::IN_LINKER | GraphemeProperty::EXTEND | GraphemeProperty::ZWJ => { |
| 365 | Break::None |
| 366 | } |
| 367 | GraphemeProperty::IN_CONSONANT => { |
| 368 | self.state = ClusterMachineState::IndicClusterStart; |
| 369 | Break::None |
| 370 | } |
| 371 | _ => { |
| 372 | self.first_character(c); |
| 373 | Break::Before |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | _ => { |
| 378 | if is_continuation(property) { |
| 379 | Break::None |
| 380 | } else { |
| 381 | self.first_character(c); |
| 382 | Break::Before |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | #[inline] |
| 388 | fn first_character(&mut self, c: char) -> Break { |
| 389 | if c == '\r' { |
| 390 | self.state = ClusterMachineState::CrLf; |
| 391 | return Break::None; |
| 392 | } |
| 393 | let property = get_property(c); |
| 394 | if property == GraphemeProperty::CONTROL { |
| 395 | self.state = ClusterMachineState::Start; |
| 396 | return Break::After; |
| 397 | } |
| 398 | match property { |
| 399 | GraphemeProperty::PREPEND => { |
| 400 | self.state = ClusterMachineState::Precore; |
| 401 | } |
| 402 | GraphemeProperty::EXTEND | GraphemeProperty::IN_LINKER => { |
| 403 | self.state = ClusterMachineState::CcsExtend; |
| 404 | } |
| 405 | GraphemeProperty::SPACING_MARK => { |
| 406 | self.state = ClusterMachineState::CcsExtend; |
| 407 | } |
| 408 | GraphemeProperty::L => { |
| 409 | self.state = ClusterMachineState::HangulSyllableL; |
| 410 | } |
| 411 | GraphemeProperty::V => { |
| 412 | self.state = ClusterMachineState::HangulSyllableV; |
| 413 | } |
| 414 | GraphemeProperty::T => { |
| 415 | self.state = ClusterMachineState::HangulSyllableT; |
| 416 | } |
| 417 | GraphemeProperty::LV => { |
| 418 | self.state = ClusterMachineState::HangulSyllableV; |
| 419 | } |
| 420 | GraphemeProperty::LVT => { |
| 421 | self.state = ClusterMachineState::HangulSyllableT; |
| 422 | } |
| 423 | GraphemeProperty::EXTENDED_GRAPHEME => { |
| 424 | self.state = ClusterMachineState::Emoji; |
| 425 | } |
| 426 | GraphemeProperty::REGIONAL_INDICATOR => { |
| 427 | self.state = ClusterMachineState::Flag; |
| 428 | } |
| 429 | GraphemeProperty::IN_CONSONANT => { |
| 430 | self.state = ClusterMachineState::IndicClusterStart; |
| 431 | } |
| 432 | _ => { |
| 433 | self.state = ClusterMachineState::Other; |
| 434 | } |
| 435 | } |
| 436 | Break::None |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | #[inline] |
| 441 | fn is_continuation(property: u8) -> bool { |
| 442 | property != 0 && property & 0x2c == 0 |
| 443 | } |
| 444 | |
| 445 | |
| 446 | // Symbolic names for properties in data tables |
| 447 | struct GraphemeProperty {} |
| 448 | impl GraphemeProperty { |
| 449 | const EXTEND: u8 = 0x01; |
| 450 | const SPACING_MARK: u8 = 0x02; |
| 451 | const ZWJ: u8 = 0x03; |
| 452 | const CONTROL: u8 = 0x04; |
| 453 | const PREPEND: u8 = 0x05; |
| 454 | const EXTENDED_GRAPHEME: u8 = 0x06; |
| 455 | const REGIONAL_INDICATOR: u8 = 0x07; |
| 456 | const L: u8 = 0x0c; |
| 457 | const V: u8 = 0x08; |
| 458 | const T: u8 = 0x09; |
| 459 | const LV: u8 = 0x0d; |
| 460 | const LVT: u8 = 0x0e; |
| 461 | const IN_CONSONANT: u8 = 0x20; |
| 462 | const IN_LINKER: u8 = 0x11; |
| 463 | } |
| 464 | |
| 465 | |
| 466 | #[inline] |
| 467 | fn get_property(c: char) -> u8 { |
| 468 | GP_PAGES[usize::from(GP_TABLE[(c as usize) >> 8])][(c as usize) & 0xff] |
| 469 | } |
| 470 | |
| 471 | |
| 472 | |
| 473 | #[cfg(test)] |
| 474 | pub (crate) mod tests { |
| 475 | use crate::grapheme_clusters::*; |
| 476 | |
| 477 | #[test] |
| 478 | fn low_level_interface_test() { |
| 479 | let mut machine = ClusterMachine::new(); |
| 480 | assert_eq!(machine.find_cluster('\r'), Break::None); |
| 481 | assert_eq!(machine.find_cluster('a'), Break::Before); |
| 482 | assert_eq!(machine.find_cluster('\r'), Break::Before); |
| 483 | assert_eq!(machine.find_cluster('\n'), Break::After); |
| 484 | } |
| 485 | |
| 486 | #[test] |
| 487 | fn can_get_clusters() { |
| 488 | let mut peekable_index = "\r\ne\u{301}f".char_indices().peekable(); |
| 489 | assert_eq!(Some("\r\n".to_string()), peekable_index.next_cluster()); |
| 490 | assert_eq!(Some("e\u{301}".to_string()), peekable_index.next_cluster()); |
| 491 | assert_eq!(Some("f".to_string()), peekable_index.next_cluster()); |
| 492 | } |
| 493 | |
| 494 | pub (crate) fn grapheme_test(input: &str, expected_output: &[&str], message: &str) { |
| 495 | let mut iter = input.char_indices().peekable(); |
| 496 | let mut clusters = vec!(); |
| 497 | while let Some(cluster) = iter.next_cluster() { |
| 498 | clusters.push(cluster); |
| 499 | } |
| 500 | let codes :Vec<u8> = input.chars().map(get_property).collect(); |
| 501 | assert_eq!(clusters.len(), expected_output.len(), "Lengths did not match on Grapheme Cluster\n\t{message}\n\tOutput: {clusters:?}\n\tExpected: {expected_output:?}\n\tCodes: {codes:x?}"); |
| 502 | clusters.iter().zip(expected_output.into_iter()) |
| 503 | .for_each(|(actual, &expected)| assert_eq!(actual.as_str(), expected, "GraphemeCluster mismatch: {message}")); |
| 504 | |
| 505 | let iter = Graphemes::new(input); |
| 506 | let clusters = iter.collect::<Vec<&str>>(); |
| 507 | assert_eq!(clusters.len(), expected_output.len(), "Lengths did not match on Grapheme Cluster Indices\n\t{message}\n\tOutput: {clusters:?}\n\tExpected: {expected_output:?}"); |
| 508 | clusters.iter().zip(expected_output.into_iter()) |
| 509 | .for_each(|(actual, &expected)| assert_eq!(*actual, expected, "Grapheme cluster indices mismatch: {message}\n{} ≠ {}", actual.escape_unicode(), expected.escape_unicode())); |
| 510 | } |
| 511 | |
| 512 | } |