| 1 |
// This file is part of ICU4X. For terms of use, please see the file |
| 2 |
// called LICENSE at the top level of the ICU4X source tree |
| 3 |
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
| 4 |
|
| 5 |
use crate::complex::*; |
| 6 |
use crate::indices::*; |
| 7 |
use crate::provider::*; |
| 8 |
use crate::scaffold::*; |
| 9 |
use alloc::string::String; |
| 10 |
use alloc::vec; |
| 11 |
use alloc::vec::Vec; |
| 12 |
use icu_locale_core::LanguageIdentifier; |
| 13 |
use icu_provider::prelude::*; |
| 14 |
|
| 15 |
/// Options to tailor word breaking behavior. |
| 16 |
#[non_exhaustive] |
| 17 |
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] |
| 18 |
pub struct WordBreakOptions<'a> { |
| 19 |
/// Content locale for word segmenter |
| 20 |
/// |
| 21 |
/// If you know the language of the text being segmented, provide it here in order to produce |
| 22 |
/// higher quality breakpoints. |
| 23 |
pub content_locale: Option<&'a LanguageIdentifier>, |
| 24 |
/// Options independent of the locale |
| 25 |
pub invariant_options: WordBreakInvariantOptions, |
| 26 |
} |
| 27 |
|
| 28 |
impl WordBreakOptions<'_> { |
| 29 |
/// `const` version of [`Default::default`] |
| 30 |
pub const fn default() -> Self { |
| 31 |
Self { |
| 32 |
content_locale: None, |
| 33 |
invariant_options: WordBreakInvariantOptions::default(), |
| 34 |
} |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
/// Locale-independent options to tailor word breaking behavior |
| 39 |
/// |
| 40 |
/// Currently empty but may grow in the future |
| 41 |
#[non_exhaustive] |
| 42 |
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] |
| 43 |
pub struct WordBreakInvariantOptions {} |
| 44 |
|
| 45 |
impl WordBreakInvariantOptions { |
| 46 |
/// `const` version of [`Default::default`] |
| 47 |
pub const fn default() -> Self { |
| 48 |
Self {} |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
/// Implements the [`Iterator`] trait over the word boundaries of the given string. |
| 53 |
/// |
| 54 |
/// Lifetimes: |
| 55 |
/// |
| 56 |
/// - `'l` = lifetime of the segmenter object from which this iterator was created |
| 57 |
/// - `'s` = lifetime of the string being segmented |
| 58 |
/// |
| 59 |
/// The [`Iterator::Item`] is an [`usize`] representing index of a code unit |
| 60 |
/// _after_ the boundary (for a boundary at the end of text, this index is the length |
| 61 |
/// of the [`str`] or array of code units). |
| 62 |
/// |
| 63 |
/// For examples of use, see [`WordSegmenter`]. |
| 64 |
#[derive(Debug)] |
| 65 |
pub struct WordBreakIterator<'data, 's, Y: RuleBreakType>(WordBreakIteratorInner<'data, 's, Y>); |
| 66 |
|
| 67 |
#[derive(Debug)] |
| 68 |
enum WordBreakIteratorInner<'data, 's, Y: RuleBreakType> { |
| 69 |
V1(crate::rule_segmenter_v1::RuleBreakIterator<'data, 's, Y>), |
| 70 |
#[cfg(feature = "unstable")] |
| 71 |
V2(crate::rule_segmenter_v2::RuleBreakIterator<'data, 's, Y, ComplexWord<Y>>), |
| 72 |
} |
| 73 |
|
| 74 |
impl<Y: RuleBreakType> Iterator for WordBreakIterator<'_, '_, Y> { |
| 75 |
type Item = usize; |
| 76 |
fn next(&mut self) -> Option<Self::Item> { |
| 77 |
match self.0 { |
| 78 |
WordBreakIteratorInner::V1(ref mut iter) => iter.next(), |
| 79 |
#[cfg(feature = "unstable")] |
| 80 |
WordBreakIteratorInner::V2(ref mut iter) => iter.next(), |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
/// The word type tag that is returned by [`WordBreakIterator::word_type()`]. |
| 86 |
/// |
| 87 |
/// [`WordBreakIterator::word_type()`]: WordBreakIterator::word_type |
| 88 |
#[non_exhaustive] |
| 89 |
#[derive(Copy, Clone, PartialEq, Debug)] |
| 90 |
#[repr(u8)] |
| 91 |
pub enum WordType { |
| 92 |
/// No category tag. |
| 93 |
None = 0, |
| 94 |
/// Number category tag. |
| 95 |
Number = 1, |
| 96 |
/// Letter category tag, including CJK. |
| 97 |
Letter = 2, |
| 98 |
} |
| 99 |
|
| 100 |
impl WordType { |
| 101 |
/// Whether the segment is word-like; word-like segments include numbers, as |
| 102 |
/// well as segments made up of letters (including CJKV ideographs). |
| 103 |
pub fn is_word_like(&self) -> bool { |
| 104 |
self != &WordType::None |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
impl<'data, 's, Y: RuleBreakType> WordBreakIterator<'data, 's, Y> { |
| 109 |
/// Returns the word type of the segment preceding the current boundary. |
| 110 |
#[inline] |
| 111 |
pub fn word_type(&self) -> WordType { |
| 112 |
let last_accepting_status = match self.0 { |
| 113 |
WordBreakIteratorInner::V1(ref iter) => iter.rule_status(), |
| 114 |
#[cfg(feature = "unstable")] |
| 115 |
WordBreakIteratorInner::V2(ref iter) => iter.last_accepting_status(), |
| 116 |
}; |
| 117 |
match last_accepting_status { |
| 118 |
0 => WordType::None, |
| 119 |
1 => WordType::Number, |
| 120 |
_ => WordType::Letter, |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
/// Returns an iterator over pairs of boundary position and word type. |
| 125 |
pub fn iter_with_word_type(self) -> WordBreakIteratorWithWordType<'data, 's, Y> { |
| 126 |
WordBreakIteratorWithWordType(self) |
| 127 |
} |
| 128 |
|
| 129 |
/// Returns `true` when the segment preceding the current boundary is word-like, |
| 130 |
/// such as letters, numbers, or CJKV ideographs. |
| 131 |
#[inline] |
| 132 |
pub fn is_word_like(&self) -> bool { |
| 133 |
self.word_type().is_word_like() |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
/// Word break iterator that also returns the word type |
| 138 |
// We can use impl Trait here once `use<..>` syntax is available, see https://github.com/rust-lang/rust/issues/61756 |
| 139 |
#[derive(Debug)] |
| 140 |
pub struct WordBreakIteratorWithWordType<'data, 's, Y: RuleBreakType>( |
| 141 |
WordBreakIterator<'data, 's, Y>, |
| 142 |
); |
| 143 |
|
| 144 |
impl<Y: RuleBreakType> Iterator for WordBreakIteratorWithWordType<'_, '_, Y> { |
| 145 |
type Item = (usize, WordType); |
| 146 |
fn next(&mut self) -> Option<Self::Item> { |
| 147 |
let ret = self.0.next()?; |
| 148 |
Some((ret, self.0.word_type())) |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
/// Supports loading word break data, and creating word break iterators for different string |
| 153 |
/// encodings. |
| 154 |
/// |
| 155 |
/// Most segmentation methods live on [`WordSegmenterBorrowed`], which can be obtained via |
| 156 |
/// [`WordSegmenter::new_auto()`] (etc) or [`WordSegmenter::as_borrowed()`]. |
| 157 |
/// |
| 158 |
/// Word segmenter is currently compatible with [Unicode Standard Annex #29][UAX29] (Version 17.0.0). |
| 159 |
/// |
| 160 |
/// [UAX29]: https://www.unicode.org/reports/tr29/tr29-47.html |
| 161 |
/// |
| 162 |
/// # Content Locale |
| 163 |
/// |
| 164 |
/// You can optionally provide a _content locale_ to the [`WordSegmenter`] constructor. If you |
| 165 |
/// have information on the language of the text being segmented, providing this hint can |
| 166 |
/// produce higher-quality results. |
| 167 |
/// |
| 168 |
/// If you have a content locale, use [`WordBreakOptions`] and a constructor beginning with `try_new`. |
| 169 |
/// If you do not have a content locale use [`WordBreakInvariantOptions`] and a constructor |
| 170 |
/// beginning with `new`. |
| 171 |
/// |
| 172 |
/// # Examples |
| 173 |
/// |
| 174 |
/// Segment a string: |
| 175 |
/// |
| 176 |
/// ```rust |
| 177 |
/// use icu::segmenter::WordSegmenter; |
| 178 |
/// |
| 179 |
/// let segmenter = WordSegmenter::new_auto(Default::default()); |
| 180 |
/// |
| 181 |
/// let breakpoints: Vec<usize> = |
| 182 |
/// segmenter.segment_str("Hello World").collect(); |
| 183 |
/// assert_eq!(&breakpoints, &[0, 5, 6, 11]); |
| 184 |
/// ``` |
| 185 |
/// |
| 186 |
/// Segment a Latin1 byte string with a content locale: |
| 187 |
/// |
| 188 |
/// ```rust |
| 189 |
/// use icu::locale::langid; |
| 190 |
/// use icu::segmenter::WordSegmenter; |
| 191 |
/// use icu::segmenter::options::WordBreakOptions; |
| 192 |
/// |
| 193 |
/// let mut options = WordBreakOptions::default(); |
| 194 |
/// let langid = &langid!("en"); |
| 195 |
/// options.content_locale = Some(langid); |
| 196 |
/// let segmenter = WordSegmenter::try_new_auto(options).unwrap(); |
| 197 |
/// |
| 198 |
/// let breakpoints: Vec<usize> = segmenter |
| 199 |
/// .as_borrowed() |
| 200 |
/// .segment_latin1(b"Hello World") |
| 201 |
/// .collect(); |
| 202 |
/// assert_eq!(&breakpoints, &[0, 5, 6, 11]); |
| 203 |
/// ``` |
| 204 |
/// |
| 205 |
/// Successive boundaries can be used to retrieve the segments. |
| 206 |
/// In particular, the first boundary is always 0, and the last one is the |
| 207 |
/// length of the segmented text in code units. |
| 208 |
/// |
| 209 |
/// ```rust |
| 210 |
/// # use icu::segmenter::{WordSegmenter, options::WordBreakInvariantOptions}; |
| 211 |
/// # let segmenter = WordSegmenter::new_auto(WordBreakInvariantOptions::default()); |
| 212 |
/// use itertools::Itertools; |
| 213 |
/// let text = "Mark’d ye his words?"; |
| 214 |
/// let segments: Vec<&str> = segmenter |
| 215 |
/// .segment_str(text) |
| 216 |
/// .tuple_windows() |
| 217 |
/// .map(|(i, j)| &text[i..j]) |
| 218 |
/// .collect(); |
| 219 |
/// assert_eq!( |
| 220 |
/// &segments, |
| 221 |
/// &["Mark’d", " ", "ye", " ", "his", " ", "words", "?"] |
| 222 |
/// ); |
| 223 |
/// ``` |
| 224 |
/// |
| 225 |
/// Not all segments delimited by word boundaries are words; some are interword |
| 226 |
/// segments such as spaces and punctuation. |
| 227 |
/// The [`WordBreakIterator::word_type()`] of a boundary can be used to |
| 228 |
/// classify the preceding segment; [`WordBreakIterator::iter_with_word_type()`] |
| 229 |
/// associates each boundary with its status. |
| 230 |
/// ```rust |
| 231 |
/// # use itertools::Itertools; |
| 232 |
/// # use icu::segmenter::WordSegmenter; |
| 233 |
/// # use icu::segmenter::options::{WordType, WordBreakInvariantOptions}; |
| 234 |
/// # let segmenter = WordSegmenter::new_auto(WordBreakInvariantOptions::default()); |
| 235 |
/// # let text = "Mark’d ye his words?"; |
| 236 |
/// let words: Vec<&str> = segmenter |
| 237 |
/// .segment_str(text) |
| 238 |
/// .iter_with_word_type() |
| 239 |
/// .tuple_windows() |
| 240 |
/// .filter(|(_, (_, segment_type))| segment_type.is_word_like()) |
| 241 |
/// .map(|((i, _), (j, _))| &text[i..j]) |
| 242 |
/// .collect(); |
| 243 |
/// assert_eq!(&words, &["Mark’d", "ye", "his", "words"]); |
| 244 |
/// ``` |
| 245 |
#[derive(Debug)] |
| 246 |
pub struct WordSegmenter(WordSegmenterInner); |
| 247 |
|
| 248 |
#[derive(Debug)] |
| 249 |
enum WordSegmenterInner { |
| 250 |
V1 { |
| 251 |
payload: DataPayload<SegmenterBreakWordV1>, |
| 252 |
complex: ComplexPayloads, |
| 253 |
payload_locale_override: Option<DataPayload<SegmenterBreakWordOverrideV1>>, |
| 254 |
}, |
| 255 |
#[cfg(feature = "unstable")] |
| 256 |
V2 { |
| 257 |
payload: DataPayload<SegmenterBreakWordV2>, |
| 258 |
complex: ComplexPayloads, |
| 259 |
}, |
| 260 |
} |
| 261 |
|
| 262 |
/// Segments a string into words (borrowed version). |
| 263 |
/// |
| 264 |
/// See [`WordSegmenter`] for examples. |
| 265 |
#[derive(Clone, Debug, Copy)] |
| 266 |
pub struct WordSegmenterBorrowed<'data>(WordSegmenterBorrowedInner<'data>); |
| 267 |
|
| 268 |
#[derive(Clone, Debug, Copy)] |
| 269 |
enum WordSegmenterBorrowedInner<'data> { |
| 270 |
V1 { |
| 271 |
data: &'data RuleBreakData<'data>, |
| 272 |
complex: ComplexPayloadsBorrowed<'data>, |
| 273 |
locale_override: Option<&'data RuleBreakDataOverride<'data>>, |
| 274 |
}, |
| 275 |
#[cfg(feature = "unstable")] |
| 276 |
V2 { |
| 277 |
data: &'data SegmenterStateMachine<'data>, |
| 278 |
complex: ComplexPayloadsBorrowed<'data>, |
| 279 |
}, |
| 280 |
} |
| 281 |
|
| 282 |
impl WordSegmenter { |
| 283 |
/// Constructs a [`WordSegmenter`] with an invariant locale and the best available compiled data for |
| 284 |
/// complex scripts (Chinese, Japanese, Khmer, Lao, Myanmar, and Thai). |
| 285 |
/// |
| 286 |
/// The current behavior, which is subject to change, is to use the LSTM model when available |
| 287 |
/// and the dictionary model for Chinese and Japanese. |
| 288 |
/// |
| 289 |
/// ✨ *Enabled with the `compiled_data` and `auto` Cargo features.* |
| 290 |
/// |
| 291 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 292 |
/// |
| 293 |
/// # Examples |
| 294 |
/// |
| 295 |
/// Behavior with complex scripts: |
| 296 |
/// |
| 297 |
/// ``` |
| 298 |
/// use icu::segmenter::{WordSegmenter, options::WordBreakInvariantOptions}; |
| 299 |
/// |
| 300 |
/// let th_str = "ทุกสองสัปดาห์"; |
| 301 |
/// let ja_str = "こんにちは世界"; |
| 302 |
/// |
| 303 |
/// let segmenter = |
| 304 |
/// WordSegmenter::new_auto(WordBreakInvariantOptions::default()); |
| 305 |
/// |
| 306 |
/// let th_bps = segmenter.segment_str(th_str).collect::<Vec<_>>(); |
| 307 |
/// let ja_bps = segmenter.segment_str(ja_str).collect::<Vec<_>>(); |
| 308 |
/// |
| 309 |
/// assert_eq!(th_bps, [0, 9, 18, 39]); |
| 310 |
/// assert_eq!(ja_bps, [0, 15, 21]); |
| 311 |
/// ``` |
| 312 |
#[cfg(feature = "compiled_data")] |
| 313 |
#[cfg(feature = "auto")] |
| 314 |
pub fn new_auto(_options: WordBreakInvariantOptions) -> WordSegmenterBorrowed<'static> { |
| 315 |
let mut s = Self::new_for_non_complex_scripts(_options); |
| 316 |
s.load_auto(); |
| 317 |
s |
| 318 |
} |
| 319 |
|
| 320 |
#[cfg(feature = "auto")] |
| 321 |
icu_provider::gen_buffer_data_constructors!( |
| 322 |
(options: WordBreakOptions) -> error: DataError, |
| 323 |
functions: [ |
| 324 |
try_new_auto, |
| 325 |
try_new_auto_with_buffer_provider, |
| 326 |
try_new_auto_unstable, |
| 327 |
Self |
| 328 |
] |
| 329 |
); |
| 330 |
|
| 331 |
#[cfg(feature = "auto")] |
| 332 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_auto)] |
| 333 |
pub fn try_new_auto_unstable<D>( |
| 334 |
provider: &D, |
| 335 |
options: WordBreakOptions, |
| 336 |
) -> Result<Self, DataError> |
| 337 |
where |
| 338 |
D: DataProvider<SegmenterBreakWordV1> |
| 339 |
+ DataProvider<SegmenterBreakWordOverrideV1> |
| 340 |
+ DataProvider<SegmenterDictionaryAutoV1> |
| 341 |
+ DataProvider<SegmenterLstmAutoV1> |
| 342 |
+ DataProvider<SegmenterBreakGraphemeClusterV1> |
| 343 |
+ ?Sized, |
| 344 |
{ |
| 345 |
let mut s = Self::try_new_for_non_complex_scripts_unstable(provider, options)?; |
| 346 |
s.load_auto_unstable(provider)?; |
| 347 |
Ok(s) |
| 348 |
} |
| 349 |
|
| 350 |
/// Constructs a [`WordSegmenter`] with an invariant locale and compiled LSTM data for |
| 351 |
/// complex scripts (Burmese, Khmer, Lao, and Thai). |
| 352 |
/// |
| 353 |
/// The LSTM, or Long Term Short Memory, is a machine learning model. It is smaller than |
| 354 |
/// the full dictionary but more expensive during segmentation (inference). |
| 355 |
/// |
| 356 |
/// Warning: there is not currently an LSTM model for Chinese or Japanese, so the [`WordSegmenter`] |
| 357 |
/// created by this function will have unexpected behavior in spans of those scripts. |
| 358 |
/// |
| 359 |
/// ✨ *Enabled with the `compiled_data` and `lstm` Cargo features.* |
| 360 |
/// |
| 361 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 362 |
/// |
| 363 |
/// # Examples |
| 364 |
/// |
| 365 |
/// Behavior with complex scripts: |
| 366 |
/// |
| 367 |
/// ``` |
| 368 |
/// use icu::segmenter::{WordSegmenter, options::WordBreakInvariantOptions}; |
| 369 |
/// |
| 370 |
/// let th_str = "ทุกสองสัปดาห์"; |
| 371 |
/// let ja_str = "こんにちは世界"; |
| 372 |
/// |
| 373 |
/// let segmenter = |
| 374 |
/// WordSegmenter::new_lstm(WordBreakInvariantOptions::default()); |
| 375 |
/// |
| 376 |
/// let th_bps = segmenter.segment_str(th_str).collect::<Vec<_>>(); |
| 377 |
/// let ja_bps = segmenter.segment_str(ja_str).collect::<Vec<_>>(); |
| 378 |
/// |
| 379 |
/// assert_eq!(th_bps, [0, 9, 18, 39]); |
| 380 |
/// |
| 381 |
/// // Note: We aren't able to find a suitable breakpoint in Chinese/Japanese. |
| 382 |
/// assert_eq!(ja_bps, [0, 21]); |
| 383 |
/// ``` |
| 384 |
#[cfg(feature = "compiled_data")] |
| 385 |
#[cfg(feature = "lstm")] |
| 386 |
pub fn new_lstm(options: WordBreakInvariantOptions) -> WordSegmenterBorrowed<'static> { |
| 387 |
let mut s = Self::new_for_non_complex_scripts(options); |
| 388 |
s.load_lstm(); |
| 389 |
s |
| 390 |
} |
| 391 |
|
| 392 |
#[cfg(feature = "lstm")] |
| 393 |
icu_provider::gen_buffer_data_constructors!( |
| 394 |
(options: WordBreakOptions) -> error: DataError, |
| 395 |
functions: [ |
| 396 |
try_new_lstm, |
| 397 |
try_new_lstm_with_buffer_provider, |
| 398 |
try_new_lstm_unstable, |
| 399 |
Self |
| 400 |
] |
| 401 |
); |
| 402 |
|
| 403 |
#[cfg(feature = "lstm")] |
| 404 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_lstm)] |
| 405 |
pub fn try_new_lstm_unstable<D>( |
| 406 |
provider: &D, |
| 407 |
options: WordBreakOptions, |
| 408 |
) -> Result<Self, DataError> |
| 409 |
where |
| 410 |
D: DataProvider<SegmenterBreakWordV1> |
| 411 |
+ DataProvider<SegmenterBreakWordOverrideV1> |
| 412 |
+ DataProvider<SegmenterLstmAutoV1> |
| 413 |
+ DataProvider<SegmenterBreakGraphemeClusterV1> |
| 414 |
+ ?Sized, |
| 415 |
{ |
| 416 |
let mut s = Self::try_new_for_non_complex_scripts_unstable(provider, options)?; |
| 417 |
s.load_lstm_unstable(provider)?; |
| 418 |
Ok(s) |
| 419 |
} |
| 420 |
|
| 421 |
/// Construct a [`WordSegmenter`] with an invariant locale and compiled dictionary data for |
| 422 |
/// complex scripts (Chinese, Japanese, Khmer, Lao, Myanmar, and Thai). |
| 423 |
/// |
| 424 |
/// The dictionary model uses a list of words to determine appropriate breakpoints. It is |
| 425 |
/// faster than the LSTM model but requires more data. |
| 426 |
/// |
| 427 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 428 |
/// |
| 429 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 430 |
/// |
| 431 |
/// # Examples |
| 432 |
/// |
| 433 |
/// Behavior with complex scripts: |
| 434 |
/// |
| 435 |
/// ``` |
| 436 |
/// use icu::segmenter::{WordSegmenter, options::WordBreakInvariantOptions}; |
| 437 |
/// |
| 438 |
/// let th_str = "ทุกสองสัปดาห์"; |
| 439 |
/// let ja_str = "こんにちは世界"; |
| 440 |
/// |
| 441 |
/// let segmenter = |
| 442 |
/// WordSegmenter::new_dictionary(WordBreakInvariantOptions::default()); |
| 443 |
/// |
| 444 |
/// let th_bps = segmenter.segment_str(th_str).collect::<Vec<_>>(); |
| 445 |
/// let ja_bps = segmenter.segment_str(ja_str).collect::<Vec<_>>(); |
| 446 |
/// |
| 447 |
/// assert_eq!(th_bps, [0, 9, 18, 39]); |
| 448 |
/// assert_eq!(ja_bps, [0, 15, 21]); |
| 449 |
/// ``` |
| 450 |
#[cfg(feature = "compiled_data")] |
| 451 |
pub fn new_dictionary(options: WordBreakInvariantOptions) -> WordSegmenterBorrowed<'static> { |
| 452 |
let mut s = Self::new_for_non_complex_scripts(options); |
| 453 |
s.load_dictionary(); |
| 454 |
s |
| 455 |
} |
| 456 |
|
| 457 |
icu_provider::gen_buffer_data_constructors!( |
| 458 |
(options: WordBreakOptions) -> error: DataError, |
| 459 |
functions: [ |
| 460 |
try_new_dictionary, |
| 461 |
try_new_dictionary_with_buffer_provider, |
| 462 |
try_new_dictionary_unstable, |
| 463 |
Self |
| 464 |
] |
| 465 |
); |
| 466 |
|
| 467 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_dictionary)] |
| 468 |
pub fn try_new_dictionary_unstable<D>( |
| 469 |
provider: &D, |
| 470 |
options: WordBreakOptions, |
| 471 |
) -> Result<Self, DataError> |
| 472 |
where |
| 473 |
D: DataProvider<SegmenterBreakWordV1> |
| 474 |
+ DataProvider<SegmenterBreakWordOverrideV1> |
| 475 |
+ DataProvider<SegmenterDictionaryAutoV1> |
| 476 |
+ DataProvider<SegmenterDictionaryExtendedV1> |
| 477 |
+ DataProvider<SegmenterBreakGraphemeClusterV1> |
| 478 |
+ ?Sized, |
| 479 |
{ |
| 480 |
let mut s = Self::try_new_for_non_complex_scripts_unstable(provider, options)?; |
| 481 |
s.load_dictionary_unstable(provider)?; |
| 482 |
Ok(s) |
| 483 |
} |
| 484 |
|
| 485 |
/// Construct a [`WordSegmenter`] with an invariant locale and no support for |
| 486 |
/// scripts requiring complex context dependent word breaks (Chinese, Japanese, Khmer, Lao, Myanmar, and Thai). |
| 487 |
/// |
| 488 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 489 |
/// |
| 490 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 491 |
#[cfg(feature = "compiled_data")] |
| 492 |
pub const fn new_for_non_complex_scripts( |
| 493 |
_options: WordBreakInvariantOptions, |
| 494 |
) -> WordSegmenterBorrowed<'static> { |
| 495 |
WordSegmenterBorrowed(WordSegmenterBorrowedInner::V1 { |
| 496 |
data: Baked::SINGLETON_SEGMENTER_BREAK_WORD_V1, |
| 497 |
complex: ComplexPayloadsBorrowed::new(), |
| 498 |
locale_override: None, |
| 499 |
}) |
| 500 |
} |
| 501 |
|
| 502 |
icu_provider::gen_buffer_data_constructors!( |
| 503 |
(options: WordBreakOptions) -> error: DataError, |
| 504 |
functions: [ |
| 505 |
try_new_for_non_complex_scripts, |
| 506 |
try_new_for_non_complex_scripts_with_buffer_provider, |
| 507 |
try_new_for_non_complex_scripts_unstable, |
| 508 |
Self |
| 509 |
] |
| 510 |
); |
| 511 |
|
| 512 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_for_non_complex_scripts)] |
| 513 |
pub fn try_new_for_non_complex_scripts_unstable<D>( |
| 514 |
provider: &D, |
| 515 |
options: WordBreakOptions, |
| 516 |
) -> Result<Self, DataError> |
| 517 |
where |
| 518 |
D: DataProvider<SegmenterBreakWordV1> |
| 519 |
+ DataProvider<SegmenterBreakWordOverrideV1> |
| 520 |
+ DataProvider<SegmenterBreakGraphemeClusterV1> |
| 521 |
+ ?Sized, |
| 522 |
{ |
| 523 |
Ok(Self(WordSegmenterInner::V1 { |
| 524 |
payload: provider.load(Default::default())?.payload, |
| 525 |
complex: ComplexPayloads::try_new(provider)?, |
| 526 |
payload_locale_override: if let Some(locale) = options.content_locale { |
| 527 |
let locale = DataLocale::from(locale); |
| 528 |
let req = DataRequest { |
| 529 |
id: DataIdentifierBorrowed::for_locale(&locale), |
| 530 |
metadata: { |
| 531 |
let mut metadata = DataRequestMetadata::default(); |
| 532 |
metadata.silent = true; |
| 533 |
metadata |
| 534 |
}, |
| 535 |
}; |
| 536 |
provider |
| 537 |
.load(req) |
| 538 |
.allow_identifier_not_found()? |
| 539 |
.map(|r| r.payload) |
| 540 |
} else { |
| 541 |
None |
| 542 |
}, |
| 543 |
})) |
| 544 |
} |
| 545 |
|
| 546 |
/// Construct a [`WordSegmenter`] with an invariant locale and no support for |
| 547 |
/// scripts requiring complex context dependent word breaks (Chinese, Japanese, Khmer, Lao, Myanmar, and Thai). |
| 548 |
/// |
| 549 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 550 |
/// |
| 551 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 552 |
#[cfg(feature = "compiled_data")] |
| 553 |
#[cfg(feature = "unstable")] |
| 554 |
pub const fn new_neo_for_non_complex_scripts( |
| 555 |
_options: WordBreakInvariantOptions, |
| 556 |
) -> WordSegmenterBorrowed<'static> { |
| 557 |
WordSegmenterBorrowed(WordSegmenterBorrowedInner::V2 { |
| 558 |
data: Baked::SINGLETON_SEGMENTER_BREAK_WORD_V2, |
| 559 |
complex: ComplexPayloadsBorrowed::new(), |
| 560 |
}) |
| 561 |
} |
| 562 |
|
| 563 |
#[cfg(feature = "unstable")] |
| 564 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_neo_for_non_complex_scripts)] |
| 565 |
pub fn try_new_neo_for_non_complex_scripts_unstable<D>( |
| 566 |
provider: &D, |
| 567 |
_options: WordBreakOptions, |
| 568 |
) -> Result<Self, DataError> |
| 569 |
where |
| 570 |
D: DataProvider<SegmenterBreakWordV2> |
| 571 |
+ DataProvider<SegmenterBreakGraphemeClusterV1> |
| 572 |
+ ?Sized, |
| 573 |
{ |
| 574 |
Ok(Self(WordSegmenterInner::V2 { |
| 575 |
payload: provider.load(Default::default())?.payload, |
| 576 |
complex: ComplexPayloads::try_new(provider)?, |
| 577 |
})) |
| 578 |
} |
| 579 |
|
| 580 |
/// Loads LSTM data for a [`WordSegmenter`] constructed with |
| 581 |
/// [`WordSegmenter::new_for_non_complex_scripts`]. |
| 582 |
/// |
| 583 |
/// ✨ *Enabled with the `lstm` Cargo feature.* |
| 584 |
#[cfg(feature = "lstm")] |
| 585 |
pub fn load_lstm_unstable<D>(&mut self, provider: &D) -> Result<(), DataError> |
| 586 |
where |
| 587 |
D: DataProvider<SegmenterLstmAutoV1> + ?Sized, |
| 588 |
{ |
| 589 |
let complex = match self.0 { |
| 590 |
WordSegmenterInner::V1 { |
| 591 |
ref mut complex, .. |
| 592 |
} => complex, |
| 593 |
#[cfg(feature = "unstable")] |
| 594 |
WordSegmenterInner::V2 { |
| 595 |
ref mut complex, .. |
| 596 |
} => complex, |
| 597 |
}; |
| 598 |
complex.with_southeast_asian_lstms(provider)?; |
| 599 |
Ok(()) |
| 600 |
} |
| 601 |
|
| 602 |
/// A version of [`Self::load_lstm_unstable`] that uses custom data |
| 603 |
/// provided by a [`BufferProvider`]. |
| 604 |
/// |
| 605 |
/// ✨ *Enabled with the `serde` Cargo feature.* |
| 606 |
#[cfg(feature = "serde")] |
| 607 |
#[cfg(feature = "lstm")] |
| 608 |
pub fn load_lstm_with_buffer_provider( |
| 609 |
&mut self, |
| 610 |
provider: &(impl BufferProvider + ?Sized), |
| 611 |
) -> Result<(), DataError> { |
| 612 |
self.load_lstm_unstable(&provider.as_deserializing()) |
| 613 |
} |
| 614 |
|
| 615 |
/// Loads dictionary data for a [`WordSegmenter`] constructed with |
| 616 |
/// [`WordSegmenter::new_for_non_complex_scripts`]. |
| 617 |
pub fn load_dictionary_unstable<D>(&mut self, provider: &D) -> Result<(), DataError> |
| 618 |
where |
| 619 |
D: DataProvider<SegmenterDictionaryAutoV1> |
| 620 |
+ DataProvider<SegmenterDictionaryExtendedV1> |
| 621 |
+ ?Sized, |
| 622 |
{ |
| 623 |
let complex = match self.0 { |
| 624 |
WordSegmenterInner::V1 { |
| 625 |
ref mut complex, .. |
| 626 |
} => complex, |
| 627 |
#[cfg(feature = "unstable")] |
| 628 |
WordSegmenterInner::V2 { |
| 629 |
ref mut complex, .. |
| 630 |
} => complex, |
| 631 |
}; |
| 632 |
complex.with_southeast_asian_dictionaries(provider)?; |
| 633 |
complex.with_japanese_dictionary(provider)?; |
| 634 |
Ok(()) |
| 635 |
} |
| 636 |
|
| 637 |
/// A version of [`Self::load_dictionary_unstable`] that uses custom data |
| 638 |
/// provided by a [`BufferProvider`]. |
| 639 |
/// |
| 640 |
/// ✨ *Enabled with the `serde` Cargo feature.* |
| 641 |
#[cfg(feature = "serde")] |
| 642 |
pub fn load_dictionary_with_buffer_provider( |
| 643 |
&mut self, |
| 644 |
provider: &(impl BufferProvider + ?Sized), |
| 645 |
) -> Result<(), DataError> { |
| 646 |
self.load_dictionary_unstable(&provider.as_deserializing()) |
| 647 |
} |
| 648 |
|
| 649 |
/// Loads the best available complex script data for a [`WordSegmenter`] constructed with |
| 650 |
/// [`WordSegmenter::new_for_non_complex_scripts`]. |
| 651 |
#[cfg(feature = "auto")] |
| 652 |
pub fn load_auto_unstable<D>(&mut self, provider: &D) -> Result<(), DataError> |
| 653 |
where |
| 654 |
D: DataProvider<SegmenterDictionaryAutoV1> + DataProvider<SegmenterLstmAutoV1> + ?Sized, |
| 655 |
{ |
| 656 |
let complex = match self.0 { |
| 657 |
WordSegmenterInner::V1 { |
| 658 |
ref mut complex, .. |
| 659 |
} => complex, |
| 660 |
#[cfg(feature = "unstable")] |
| 661 |
WordSegmenterInner::V2 { |
| 662 |
ref mut complex, .. |
| 663 |
} => complex, |
| 664 |
}; |
| 665 |
complex.with_southeast_asian_lstms(provider)?; |
| 666 |
complex.with_japanese_dictionary(provider)?; |
| 667 |
Ok(()) |
| 668 |
} |
| 669 |
|
| 670 |
/// A version of [`Self::load_auto_unstable`] that uses custom data |
| 671 |
/// provided by a [`BufferProvider`]. |
| 672 |
/// |
| 673 |
/// ✨ *Enabled with the `serde` Cargo feature.* |
| 674 |
#[cfg(feature = "auto")] |
| 675 |
#[cfg(feature = "serde")] |
| 676 |
pub fn load_auto_with_buffer_provider( |
| 677 |
&mut self, |
| 678 |
provider: &(impl BufferProvider + ?Sized), |
| 679 |
) -> Result<(), DataError> { |
| 680 |
self.load_auto_unstable(&provider.as_deserializing()) |
| 681 |
} |
| 682 |
|
| 683 |
/// Constructs a borrowed version of this type for more efficient querying. |
| 684 |
/// |
| 685 |
/// Most useful methods for segmentation are on this type. |
| 686 |
pub fn as_borrowed(&self) -> WordSegmenterBorrowed<'_> { |
| 687 |
WordSegmenterBorrowed(match &self.0 { |
| 688 |
WordSegmenterInner::V1 { |
| 689 |
payload, |
| 690 |
complex, |
| 691 |
payload_locale_override, |
| 692 |
} => WordSegmenterBorrowedInner::V1 { |
| 693 |
data: payload.get(), |
| 694 |
complex: complex.as_borrowed(), |
| 695 |
locale_override: payload_locale_override.as_ref().map(|p| p.get()), |
| 696 |
}, |
| 697 |
#[cfg(feature = "unstable")] |
| 698 |
WordSegmenterInner::V2 { payload, complex } => WordSegmenterBorrowedInner::V2 { |
| 699 |
data: payload.get(), |
| 700 |
complex: complex.as_borrowed(), |
| 701 |
}, |
| 702 |
}) |
| 703 |
} |
| 704 |
} |
| 705 |
|
| 706 |
impl<'data> WordSegmenterBorrowed<'data> { |
| 707 |
/// Creates a word break iterator for an `str` (a UTF-8 string). |
| 708 |
/// |
| 709 |
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string. |
| 710 |
pub fn segment_str<'s>(self, input: &'s str) -> WordBreakIterator<'data, 's, Utf8> { |
| 711 |
WordBreakIterator(match self.0 { |
| 712 |
WordSegmenterBorrowedInner::V1 { |
| 713 |
data, |
| 714 |
complex, |
| 715 |
locale_override, |
| 716 |
} => WordBreakIteratorInner::V1(crate::rule_segmenter_v1::RuleBreakIterator { |
| 717 |
iter: input.char_indices(), |
| 718 |
len: input.len(), |
| 719 |
current_pos_data: None, |
| 720 |
result_cache: Vec::new(), |
| 721 |
data, |
| 722 |
complex: Some(complex), |
| 723 |
boundary_property: 0, |
| 724 |
locale_override, |
| 725 |
handle_complex: handle_complex_utf8, |
| 726 |
}), |
| 727 |
#[cfg(feature = "unstable")] |
| 728 |
WordSegmenterBorrowedInner::V2 { data, complex } => { |
| 729 |
WordBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new( |
| 730 |
input.char_indices(), |
| 731 |
data, |
| 732 |
None, |
| 733 |
Some(complex), |
| 734 |
)) |
| 735 |
} |
| 736 |
}) |
| 737 |
} |
| 738 |
|
| 739 |
/// Creates a word break iterator for a potentially ill-formed UTF8 string |
| 740 |
/// |
| 741 |
/// Invalid characters are treated as REPLACEMENT CHARACTER |
| 742 |
/// |
| 743 |
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string. |
| 744 |
pub fn segment_utf8<'s>( |
| 745 |
self, |
| 746 |
input: &'s [u8], |
| 747 |
) -> WordBreakIterator<'data, 's, PotentiallyIllFormedUtf8> { |
| 748 |
WordBreakIterator(match self.0 { |
| 749 |
WordSegmenterBorrowedInner::V1 { |
| 750 |
data, |
| 751 |
complex, |
| 752 |
locale_override, |
| 753 |
} => WordBreakIteratorInner::V1(crate::rule_segmenter_v1::RuleBreakIterator { |
| 754 |
iter: Utf8CharIndices::new(input), |
| 755 |
len: input.len(), |
| 756 |
current_pos_data: None, |
| 757 |
result_cache: Vec::new(), |
| 758 |
data, |
| 759 |
complex: Some(complex), |
| 760 |
boundary_property: 0, |
| 761 |
locale_override, |
| 762 |
handle_complex: handle_complex_utf8, |
| 763 |
}), |
| 764 |
#[cfg(feature = "unstable")] |
| 765 |
WordSegmenterBorrowedInner::V2 { data, complex } => { |
| 766 |
WordBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new( |
| 767 |
Utf8CharIndices::new(input), |
| 768 |
data, |
| 769 |
None, |
| 770 |
Some(complex), |
| 771 |
)) |
| 772 |
} |
| 773 |
}) |
| 774 |
} |
| 775 |
|
| 776 |
/// Creates a word break iterator for a Latin-1 (8-bit) string. |
| 777 |
/// |
| 778 |
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string. |
| 779 |
pub fn segment_latin1<'s>(self, input: &'s [u8]) -> WordBreakIterator<'data, 's, Latin1> { |
| 780 |
WordBreakIterator(match self.0 { |
| 781 |
WordSegmenterBorrowedInner::V1 { |
| 782 |
data, |
| 783 |
complex, |
| 784 |
locale_override, |
| 785 |
} => WordBreakIteratorInner::V1(crate::rule_segmenter_v1::RuleBreakIterator { |
| 786 |
iter: Latin1Indices::new(input), |
| 787 |
len: input.len(), |
| 788 |
current_pos_data: None, |
| 789 |
result_cache: Vec::new(), |
| 790 |
data, |
| 791 |
complex: Some(complex), |
| 792 |
boundary_property: 0, |
| 793 |
locale_override, |
| 794 |
handle_complex: crate::rule_segmenter_v1::empty_handle_complex, |
| 795 |
}), |
| 796 |
#[cfg(feature = "unstable")] |
| 797 |
WordSegmenterBorrowedInner::V2 { data, .. } => { |
| 798 |
WordBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new( |
| 799 |
Latin1Indices::new(input), |
| 800 |
data, |
| 801 |
None, |
| 802 |
None, |
| 803 |
)) |
| 804 |
} |
| 805 |
}) |
| 806 |
} |
| 807 |
|
| 808 |
/// Creates a word break iterator for a UTF-16 string. |
| 809 |
/// |
| 810 |
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string. |
| 811 |
pub fn segment_utf16<'s>(self, input: &'s [u16]) -> WordBreakIterator<'data, 's, Utf16> { |
| 812 |
WordBreakIterator(match self.0 { |
| 813 |
WordSegmenterBorrowedInner::V1 { |
| 814 |
data, |
| 815 |
complex, |
| 816 |
locale_override, |
| 817 |
} => WordBreakIteratorInner::V1(crate::rule_segmenter_v1::RuleBreakIterator { |
| 818 |
iter: Utf16Indices::new(input), |
| 819 |
len: input.len(), |
| 820 |
current_pos_data: None, |
| 821 |
result_cache: Vec::new(), |
| 822 |
data, |
| 823 |
complex: Some(complex), |
| 824 |
boundary_property: 0, |
| 825 |
locale_override, |
| 826 |
handle_complex: handle_complex_utf16, |
| 827 |
}), |
| 828 |
#[cfg(feature = "unstable")] |
| 829 |
WordSegmenterBorrowedInner::V2 { data, complex } => { |
| 830 |
WordBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new( |
| 831 |
Utf16Indices::new(input), |
| 832 |
data, |
| 833 |
None, |
| 834 |
Some(complex), |
| 835 |
)) |
| 836 |
} |
| 837 |
}) |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
impl WordSegmenterBorrowed<'static> { |
| 842 |
/// Loads LSTM data for a [`WordSegmenter`] constructed with |
| 843 |
/// [`WordSegmenter::new_for_non_complex_scripts`]. |
| 844 |
/// |
| 845 |
/// ✨ *Enabled with the `compiled_data` and `lstm` Cargo features.* |
| 846 |
#[cfg(feature = "lstm")] |
| 847 |
#[cfg(feature = "compiled_data")] |
| 848 |
pub fn load_lstm(&mut self) { |
| 849 |
let complex = match self.0 { |
| 850 |
WordSegmenterBorrowedInner::V1 { |
| 851 |
ref mut complex, .. |
| 852 |
} => complex, |
| 853 |
#[cfg(feature = "unstable")] |
| 854 |
WordSegmenterBorrowedInner::V2 { |
| 855 |
ref mut complex, .. |
| 856 |
} => complex, |
| 857 |
}; |
| 858 |
complex.with_southeast_asian_lstms(); |
| 859 |
} |
| 860 |
|
| 861 |
/// Loads dictionary data for a [`WordSegmenter`] constructed with |
| 862 |
/// [`WordSegmenter::new_for_non_complex_scripts`]. |
| 863 |
/// |
| 864 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 865 |
#[cfg(feature = "compiled_data")] |
| 866 |
pub fn load_dictionary(&mut self) { |
| 867 |
let complex = match self.0 { |
| 868 |
WordSegmenterBorrowedInner::V1 { |
| 869 |
ref mut complex, .. |
| 870 |
} => complex, |
| 871 |
#[cfg(feature = "unstable")] |
| 872 |
WordSegmenterBorrowedInner::V2 { |
| 873 |
ref mut complex, .. |
| 874 |
} => complex, |
| 875 |
}; |
| 876 |
complex.with_southeast_asian_dictionaries(); |
| 877 |
complex.with_japanese_dictionary(); |
| 878 |
} |
| 879 |
|
| 880 |
/// Loads the best available complex script data for a [`WordSegmenter`] constructed with |
| 881 |
/// [`WordSegmenter::new_for_non_complex_scripts`]. |
| 882 |
/// |
| 883 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 884 |
#[cfg(feature = "auto")] |
| 885 |
#[cfg(feature = "compiled_data")] |
| 886 |
pub fn load_auto(&mut self) { |
| 887 |
let complex = match self.0 { |
| 888 |
WordSegmenterBorrowedInner::V1 { |
| 889 |
ref mut complex, .. |
| 890 |
} => complex, |
| 891 |
#[cfg(feature = "unstable")] |
| 892 |
WordSegmenterBorrowedInner::V2 { |
| 893 |
ref mut complex, .. |
| 894 |
} => complex, |
| 895 |
}; |
| 896 |
complex.with_southeast_asian_lstms(); |
| 897 |
complex.with_japanese_dictionary(); |
| 898 |
} |
| 899 |
|
| 900 |
/// Cheaply converts a [`WordSegmenterBorrowed<'static>`] into a [`WordSegmenter`]. |
| 901 |
/// |
| 902 |
/// Note: Due to branching and indirection, using [`WordSegmenter`] might inhibit some |
| 903 |
/// compile-time optimizations that are possible with [`WordSegmenterBorrowed`]. |
| 904 |
pub fn static_to_owned(self) -> WordSegmenter { |
| 905 |
WordSegmenter(match self.0 { |
| 906 |
WordSegmenterBorrowedInner::V1 { |
| 907 |
data, |
| 908 |
complex, |
| 909 |
locale_override, |
| 910 |
} => WordSegmenterInner::V1 { |
| 911 |
payload: DataPayload::from_static_ref(data), |
| 912 |
complex: complex.static_to_owned(), |
| 913 |
payload_locale_override: locale_override.map(DataPayload::from_static_ref), |
| 914 |
}, |
| 915 |
#[cfg(feature = "unstable")] |
| 916 |
WordSegmenterBorrowedInner::V2 { data, complex } => WordSegmenterInner::V2 { |
| 917 |
payload: DataPayload::from_static_ref(data), |
| 918 |
complex: complex.static_to_owned(), |
| 919 |
}, |
| 920 |
}) |
| 921 |
} |
| 922 |
} |
| 923 |
|
| 924 |
fn handle_complex_utf8<T>( |
| 925 |
iter: &mut crate::rule_segmenter_v1::RuleBreakIterator<'_, '_, T>, |
| 926 |
left_codepoint: T::CharType, |
| 927 |
) -> Option<usize> |
| 928 |
where |
| 929 |
T: RuleBreakType<CharType = char>, |
| 930 |
{ |
| 931 |
// word segmenter doesn't define break rules for some scripts such as Thai. |
| 932 |
let start_iter = iter.iter.clone(); |
| 933 |
let start_point = iter.current_pos_data; |
| 934 |
let mut s = String::new(); |
| 935 |
s.push(left_codepoint); |
| 936 |
loop { |
| 937 |
debug_assert!(!iter.is_eof()); |
| 938 |
s.push(iter.get_current_codepoint()?); |
| 939 |
iter.advance_iter(); |
| 940 |
if let Some(current_break_property) = iter.get_current_break_property() { |
| 941 |
if current_break_property != iter.data.complex_property { |
| 942 |
break; |
| 943 |
} |
| 944 |
} else { |
| 945 |
// EOF |
| 946 |
break; |
| 947 |
} |
| 948 |
} |
| 949 |
|
| 950 |
// Restore iterator to move to head of complex string |
| 951 |
iter.iter = start_iter; |
| 952 |
iter.current_pos_data = start_point; |
| 953 |
#[expect(clippy::unwrap_used)] // iter.complex present for word segmenter |
| 954 |
let breaks = iter.complex.unwrap().segment_str(&s); |
| 955 |
iter.result_cache = breaks; |
| 956 |
let first_pos = *iter.result_cache.first()?; |
| 957 |
let mut i = left_codepoint.len_utf8(); |
| 958 |
loop { |
| 959 |
if i == first_pos { |
| 960 |
// Re-calculate breaking offset |
| 961 |
iter.result_cache = iter.result_cache.iter().skip(1).map(|r| r - i).collect(); |
| 962 |
return iter.get_current_position(); |
| 963 |
} |
| 964 |
debug_assert!( |
| 965 |
i < first_pos, |
| 966 |
"we should always arrive at first_pos: near index {:?}", |
| 967 |
iter.get_current_position() |
| 968 |
); |
| 969 |
i += iter.get_current_codepoint().map_or(0, T::char_len); |
| 970 |
iter.advance_iter(); |
| 971 |
if iter.is_eof() { |
| 972 |
iter.result_cache.clear(); |
| 973 |
return Some(iter.len); |
| 974 |
} |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
fn handle_complex_utf16<T>( |
| 979 |
iter: &mut crate::rule_segmenter_v1::RuleBreakIterator<'_, '_, T>, |
| 980 |
left_codepoint: T::CharType, |
| 981 |
) -> Option<usize> |
| 982 |
where |
| 983 |
T: RuleBreakType<CharType = u32>, |
| 984 |
{ |
| 985 |
// word segmenter doesn't define break rules for some scripts such as Thai. |
| 986 |
let start_iter = iter.iter.clone(); |
| 987 |
let start_point = iter.current_pos_data; |
| 988 |
let mut s = vec![left_codepoint as u16]; |
| 989 |
loop { |
| 990 |
debug_assert!(!iter.is_eof()); |
| 991 |
s.push(iter.get_current_codepoint()? as u16); |
| 992 |
iter.advance_iter(); |
| 993 |
if let Some(current_break_property) = iter.get_current_break_property() { |
| 994 |
if current_break_property != iter.data.complex_property { |
| 995 |
break; |
| 996 |
} |
| 997 |
} else { |
| 998 |
// EOF |
| 999 |
break; |
| 1000 |
} |
| 1001 |
} |
| 1002 |
|
| 1003 |
// Restore iterator to move to head of complex string |
| 1004 |
iter.iter = start_iter; |
| 1005 |
iter.current_pos_data = start_point; |
| 1006 |
#[expect(clippy::unwrap_used)] // iter.complex present for word segmenter |
| 1007 |
let breaks = iter.complex.unwrap().segment_utf16(&s); |
| 1008 |
iter.result_cache = breaks; |
| 1009 |
// result_cache vector is utf-16 index that is in BMP. |
| 1010 |
let first_pos = *iter.result_cache.first()?; |
| 1011 |
let mut i = 1; |
| 1012 |
loop { |
| 1013 |
if i == first_pos { |
| 1014 |
// Re-calculate breaking offset |
| 1015 |
iter.result_cache = iter.result_cache.iter().skip(1).map(|r| r - i).collect(); |
| 1016 |
return iter.get_current_position(); |
| 1017 |
} |
| 1018 |
debug_assert!( |
| 1019 |
i < first_pos, |
| 1020 |
"we should always arrive at first_pos: near index {:?}", |
| 1021 |
iter.get_current_position() |
| 1022 |
); |
| 1023 |
i += 1; |
| 1024 |
iter.advance_iter(); |
| 1025 |
if iter.is_eof() { |
| 1026 |
iter.result_cache.clear(); |
| 1027 |
return Some(iter.len); |
| 1028 |
} |
| 1029 |
} |
| 1030 |
} |
| 1031 |
|
| 1032 |
#[derive(Debug)] |
| 1033 |
#[cfg(feature = "unstable")] |
| 1034 |
struct ComplexWord<Y>(core::marker::PhantomData<Y>); |
| 1035 |
|
| 1036 |
#[cfg(feature = "unstable")] |
| 1037 |
impl<Y: RuleBreakType> crate::rule_segmenter_v2::ComplexHandler<Y> for ComplexWord<Y> { |
| 1038 |
const BREAK_AT_BOUNDARIES: bool = true; |
| 1039 |
type Cache = [usize; 16]; |
| 1040 |
const BREAK_STATUS: u8 = WordType::Letter as u8; |
| 1041 |
|
| 1042 |
type ComplexPayloads<'s> = Y::ComplexPayloads<'s>; |
| 1043 |
type ComplexPayload<'s> = Y::ComplexPayload<'s>; |
| 1044 |
|
| 1045 |
fn select<'data>( |
| 1046 |
complex_payloads: &Y::ComplexPayloads<'data>, |
| 1047 |
complex_script: ComplexScript, |
| 1048 |
) -> Option<Self::ComplexPayload<'data>> { |
| 1049 |
Y::select_complex(complex_payloads, complex_script) |
| 1050 |
} |
| 1051 |
|
| 1052 |
fn handle<'data, 's>( |
| 1053 |
complex_payloads: &Self::ComplexPayload<'data>, |
| 1054 |
iter: &Y::IterAttr<'s>, |
| 1055 |
past_complex: &Y::IterAttr<'s>, |
| 1056 |
) -> ComplexIterator<'data, 's, Y> { |
| 1057 |
Y::handle_complex(complex_payloads, iter, past_complex) |
| 1058 |
} |
| 1059 |
} |
| 1060 |
|
| 1061 |
#[test] |
| 1062 |
fn empty_string() { |
| 1063 |
let segmenter = |
| 1064 |
WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default()); |
| 1065 |
let breaks: Vec<usize> = segmenter.segment_str("").collect(); |
| 1066 |
assert_eq!(breaks, [0]); |
| 1067 |
} |
| 1068 |
|
| 1069 |
#[test] |
| 1070 |
fn empty_string_neo() { |
| 1071 |
let segmenter = |
| 1072 |
WordSegmenter::new_neo_for_non_complex_scripts(WordBreakInvariantOptions::default()); |
| 1073 |
let breaks: Vec<usize> = segmenter.segment_str("").collect(); |
| 1074 |
assert_eq!(breaks, [0]); |
| 1075 |
} |