Debian Codegraph @

debian/rust-vendor/icu_segmenter/src/line.rs

raw
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 icu_locale_core::LanguageIdentifier;
10 use icu_locale_core::subtags::{Language, language};
11 use icu_provider::prelude::*;
12
13 mod v1;
14 /// The Unicode 17 line breaking implementation, used with `SegmenterBreakLineV3` data.
15 #[cfg(any(feature = "unstable", feature = "datagen"))]
16 #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
17 mod v3;
18
19 /// An enum specifies the strictness of line-breaking rules. It can be passed as
20 /// an argument when creating a line segmenter.
21 ///
22 /// Each enum value has the same meaning with respect to the `line-break`
23 /// property values in the CSS Text spec. See the details in
24 /// <https://drafts.csswg.org/css-text-3/#line-break-property>.
25 #[non_exhaustive]
26 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
27 pub enum LineBreakStrictness {
28 /// Breaks text using the least restrictive set of line-breaking rules.
29 /// Typically used for short lines, such as in newspapers.
30 /// <https://drafts.csswg.org/css-text-3/#valdef-line-break-loose>
31 Loose,
32
33 /// Breaks text using the most common set of line-breaking rules.
34 /// <https://drafts.csswg.org/css-text-3/#valdef-line-break-normal>
35 Normal,
36
37 /// Breaks text using the most stringent set of line-breaking rules.
38 /// <https://drafts.csswg.org/css-text-3/#valdef-line-break-strict>
39 ///
40 /// This is the default behaviour of the Unicode Line Breaking Algorithm,
41 /// resolving class [CJ](https://www.unicode.org/reports/tr14/#CJ) to
42 /// [NS](https://www.unicode.org/reports/tr14/#NS);
43 /// see rule [LB1](https://www.unicode.org/reports/tr14/#LB1).
44 #[default]
45 Strict,
46
47 /// Breaks text assuming there is a soft wrap opportunity around every
48 /// typographic character unit, disregarding any prohibition against line
49 /// breaks. See more details in
50 /// <https://drafts.csswg.org/css-text-3/#valdef-line-break-anywhere>.
51 Anywhere,
52 }
53
54 /// An enum specifies the line break opportunities between letters. It can be
55 /// passed as an argument when creating a line segmenter.
56 ///
57 /// Each enum value has the same meaning with respect to the `word-break`
58 /// property values in the CSS Text spec. See the details in
59 /// <https://drafts.csswg.org/css-text-3/#word-break-property>
60 #[non_exhaustive]
61 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
62 pub enum LineBreakWordOption {
63 /// Words break according to their customary rules. See the details in
64 /// <https://drafts.csswg.org/css-text-3/#valdef-word-break-normal>.
65 #[default]
66 Normal,
67
68 /// Breaking is allowed within "words".
69 /// <https://drafts.csswg.org/css-text-3/#valdef-word-break-break-all>
70 BreakAll,
71
72 /// Breaking is forbidden within "word".
73 /// <https://drafts.csswg.org/css-text-3/#valdef-word-break-keep-all>
74 KeepAll,
75 }
76
77 /// Options to tailor line-breaking behavior.
78 #[non_exhaustive]
79 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
80 pub struct LineBreakOptions<'a> {
81 /// Strictness of line-breaking rules. See [`LineBreakStrictness`].
82 ///
83 /// Default is [`LineBreakStrictness::Strict`]
84 pub strictness: Option<LineBreakStrictness>,
85
86 /// Line break opportunities between letters. See [`LineBreakWordOption`].
87 ///
88 /// Default is [`LineBreakStrictness::Normal`]
89 pub word_option: Option<LineBreakWordOption>,
90
91 /// Content locale for line segmenter
92 ///
93 /// This allows more break opportunities when `LineBreakStrictness` is
94 /// `Normal` or `Loose`. See
95 /// <https://drafts.csswg.org/css-text-3/#line-break-property> for details.
96 /// This option has no effect in Latin-1 mode.
97 pub content_locale: Option<&'a LanguageIdentifier>,
98 }
99
100 impl LineBreakOptions<'_> {
101 /// `const` version of [`Default::default`]
102 pub const fn default() -> Self {
103 Self {
104 strictness: None,
105 word_option: None,
106 content_locale: None,
107 }
108 }
109 }
110
111 #[derive(Debug, Clone, Copy)]
112 pub(crate) struct ResolvedLineBreakOptions {
113 pub(crate) strictness: LineBreakStrictness,
114 pub(crate) word_option: LineBreakWordOption,
115 pub(crate) ja_zh: bool,
116 }
117
118 impl LineBreakOptions<'_> {
119 pub(crate) const fn resolve(self) -> ResolvedLineBreakOptions {
120 ResolvedLineBreakOptions {
121 strictness: match self.strictness {
122 Some(s) => s,
123 None => LineBreakStrictness::Strict,
124 },
125 word_option: match self.word_option {
126 Some(s) => s,
127 None => LineBreakWordOption::Normal,
128 },
129 ja_zh: if let Some(content_locale) = self.content_locale.as_ref() {
130 const JA: Language = language!("ja");
131 const ZH: Language = language!("zh");
132 matches!(content_locale.language, JA | ZH)
133 } else {
134 false
135 },
136 }
137 }
138 }
139
140 /// Supports loading line break data, and creating line break iterators for different string
141 /// encodings.
142 ///
143 /// Most segmentation methods live on [`LineSegmenterBorrowed`], which can be obtained via
144 /// [`LineSegmenter::new_auto()`] (etc) or [`LineSegmenter::as_borrowed()`].
145 ///
146 /// The segmenter returns mandatory breaks (as defined by [definition LD7][LD7] of
147 /// Unicode Standard Annex #14, _Unicode Line Breaking Algorithm_) as well as
148 /// line break opportunities ([definition LD3][LD3]).
149 /// It does not distinguish them. Callers requiring that distinction can check
150 /// the `Line_Break` property of the code point preceding the break against those
151 /// listed in rules [LB4][LB4] and [LB5][LB5], special-casing the end of text
152 /// according to [LB3][LB3].
153 ///
154 /// For consistency with the grapheme, word, and sentence segmenters, there is
155 /// always a breakpoint returned at index 0, but this breakpoint is not a
156 /// meaningful line break opportunity.
157 ///
158 /// Line segmenter is currently compatible with [Unicode Standard Annex #14][UAX14] (Version 15.1.0).
159 /// The `*_17_*` and `*_neo_*` constructors, which require the `unstable` Cargo feature, implement Version 17.0.0.
160 ///
161 /// [UAX14]: https://www.unicode.org/reports/tr14/tr14-55.html
162 ///
163 /// [LD3]: https://www.unicode.org/reports/tr14/#LD3
164 /// [LD7]: https://www.unicode.org/reports/tr14/#LD7
165 /// [LB3]: https://www.unicode.org/reports/tr14/#LB3
166 /// [LB4]: https://www.unicode.org/reports/tr14/#LB4
167 /// [LB5]: https://www.unicode.org/reports/tr14/#LB5
168 ///
169 /// ```rust
170 /// # use icu::segmenter::LineSegmenter;
171 /// #
172 /// # let segmenter = LineSegmenter::new_auto(Default::default());
173 /// #
174 /// let text = "Summary\r\nThis annex…";
175 /// let breakpoints: Vec<usize> = segmenter.segment_str(text).collect();
176 /// // 9 and 22 are mandatory breaks, 14 is a line break opportunity.
177 /// assert_eq!(&breakpoints, &[0, 9, 14, 22]);
178 ///
179 /// // There is a break opportunity between emoji, but not within the ZWJ sequence 🏳️‍🌈.
180 /// let flag_equation = "🏳️➕🌈🟰🏳️\u{200D}🌈";
181 /// let possible_first_lines: Vec<&str> =
182 /// segmenter.segment_str(flag_equation).skip(1).map(|i| &flag_equation[..i]).collect();
183 /// assert_eq!(
184 /// &possible_first_lines,
185 /// &[
186 /// "🏳️",
187 /// "🏳️➕",
188 /// "🏳️➕🌈",
189 /// "🏳️➕🌈🟰",
190 /// "🏳️➕🌈🟰🏳️‍🌈"
191 /// ]
192 /// );
193 /// ```
194 ///
195 /// # Examples
196 ///
197 /// Segment a string with default options:
198 ///
199 /// ```rust
200 /// use icu::segmenter::LineSegmenter;
201 ///
202 /// let segmenter = LineSegmenter::new_auto(Default::default());
203 ///
204 /// let breakpoints: Vec<usize> =
205 /// segmenter.segment_str("Hello World").collect();
206 /// assert_eq!(&breakpoints, &[0, 6, 11]);
207 /// ```
208 ///
209 /// Segment a string with CSS option overrides:
210 ///
211 /// ```rust
212 /// use icu::segmenter::LineSegmenter;
213 /// use icu::segmenter::options::{
214 /// LineBreakOptions, LineBreakStrictness, LineBreakWordOption,
215 /// };
216 ///
217 /// let mut options = LineBreakOptions::default();
218 /// options.strictness = Some(LineBreakStrictness::Strict);
219 /// options.word_option = Some(LineBreakWordOption::BreakAll);
220 /// options.content_locale = None;
221 /// let segmenter = LineSegmenter::new_auto(options);
222 ///
223 /// let breakpoints: Vec<usize> =
224 /// segmenter.segment_str("Hello World").collect();
225 /// assert_eq!(&breakpoints, &[0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11]);
226 /// ```
227 ///
228 /// Segment a Latin1 byte string:
229 ///
230 /// ```rust
231 /// use icu::segmenter::LineSegmenter;
232 ///
233 /// let segmenter = LineSegmenter::new_auto(Default::default());
234 ///
235 /// let breakpoints: Vec<usize> =
236 /// segmenter.segment_latin1(b"Hello World").collect();
237 /// assert_eq!(&breakpoints, &[0, 6, 11]);
238 /// ```
239 ///
240 /// Separate mandatory breaks from the break opportunities:
241 ///
242 /// ```rust
243 /// use icu::properties::{CodePointMapData, props::LineBreak};
244 /// use icu::segmenter::LineSegmenter;
245 ///
246 /// # let segmenter = LineSegmenter::new_auto(Default::default());
247 /// #
248 /// let text = "Summary\r\nThis annex…";
249 ///
250 /// let mandatory_breaks: Vec<usize> = segmenter
251 /// .segment_str(text)
252 /// .filter(|&i| {
253 /// text[..i].chars().next_back().is_some_and(|c| {
254 /// matches!(
255 /// CodePointMapData::<LineBreak>::new().get(c),
256 /// LineBreak::MandatoryBreak
257 /// | LineBreak::CarriageReturn
258 /// | LineBreak::LineFeed
259 /// | LineBreak::NextLine
260 /// ) || i == text.len()
261 /// })
262 /// })
263 /// .collect();
264 /// assert_eq!(&mandatory_breaks, &[9, 22]);
265 /// ```
266 #[derive(Debug)]
267 pub struct LineSegmenter(LineSegmenterInner);
268
269 #[derive(Debug)]
270 enum LineSegmenterInner {
271 V1 {
272 options: ResolvedLineBreakOptions,
273 data: DataPayload<SegmenterBreakLineV1>,
274 complex: ComplexPayloads,
275 },
276 #[cfg(feature = "unstable")]
277 V2 {
278 data: DataPayload<SegmenterBreakLineV2>,
279 tailoring: Option<DataPayload<SegmenterBreakLineOverrideV2>>,
280 complex: ComplexPayloads,
281 },
282 #[cfg(feature = "unstable")]
283 V3 {
284 options: ResolvedLineBreakOptions,
285 data: DataPayload<SegmenterBreakLineV3>,
286 complex: ComplexPayloads,
287 },
288 }
289
290 /// Segments a string into lines (borrowed version).
291 ///
292 /// See [`LineSegmenter`] for examples.
293 #[derive(Clone, Debug, Copy)]
294 pub struct LineSegmenterBorrowed<'data>(LineSegmenterBorrowedInner<'data>);
295
296 #[derive(Debug, Clone, Copy)]
297 enum LineSegmenterBorrowedInner<'data> {
298 V1 {
299 options: ResolvedLineBreakOptions,
300 data: &'data RuleBreakData<'data>,
301 complex: ComplexPayloadsBorrowed<'data>,
302 },
303 #[cfg(feature = "unstable")]
304 V2 {
305 data: &'data SegmenterStateMachine<'data>,
306 tailoring: Option<&'data SegmenterStateMachineOverride<'data>>,
307 complex: ComplexPayloadsBorrowed<'data>,
308 },
309 #[cfg(feature = "unstable")]
310 V3 {
311 options: ResolvedLineBreakOptions,
312 data: &'data RuleBreakData<'data>,
313 complex: ComplexPayloadsBorrowed<'data>,
314 },
315 }
316
317 impl LineSegmenter {
318 /// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
319 /// the best available compiled data for complex scripts (Khmer, Lao, Myanmar, and Thai).
320 ///
321 /// The current behavior, which is subject to change, is to use the LSTM model when available.
322 ///
323 /// See also [`Self::new_auto`].
324 ///
325 /// ✨ *Enabled with the `compiled_data` and `auto` Cargo features.*
326 ///
327 /// [📚 Help choosing a constructor](icu_provider::constructors)
328 #[cfg(feature = "auto")]
329 #[cfg(feature = "compiled_data")]
330 pub fn new_auto(options: LineBreakOptions) -> LineSegmenterBorrowed<'static> {
331 Self::new_lstm(options)
332 }
333
334 #[cfg(feature = "auto")]
335 icu_provider::gen_buffer_data_constructors!(
336 (options: LineBreakOptions) -> error: DataError,
337 functions: [
338 new_auto: skip,
339 try_new_auto_with_buffer_provider,
340 try_new_auto_unstable,
341 Self,
342 ]
343 );
344
345 #[cfg(feature = "auto")]
346 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_auto)]
347 pub fn try_new_auto_unstable<D>(
348 provider: &D,
349 options: LineBreakOptions,
350 ) -> Result<Self, DataError>
351 where
352 D: DataProvider<SegmenterBreakLineV1>
353 + DataProvider<SegmenterLstmAutoV1>
354 + DataProvider<SegmenterBreakGraphemeClusterV1>
355 + ?Sized,
356 {
357 Self::try_new_lstm_unstable(provider, options)
358 }
359
360 /// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
361 /// compiled LSTM data for complex scripts (Khmer, Lao, Myanmar, and Thai).
362 ///
363 /// The LSTM, or Long Term Short Memory, is a machine learning model. It is smaller than
364 /// the full dictionary but more expensive during segmentation (inference).
365 ///
366 /// See also [`Self::new_lstm`].
367 ///
368 /// ✨ *Enabled with the `compiled_data` and `lstm` Cargo features.*
369 ///
370 /// [📚 Help choosing a constructor](icu_provider::constructors)
371 #[cfg(feature = "lstm")]
372 #[cfg(feature = "compiled_data")]
373 pub fn new_lstm(options: LineBreakOptions) -> LineSegmenterBorrowed<'static> {
374 let mut s = Self::new_for_non_complex_scripts(options);
375 s.load_lstm();
376 s
377 }
378
379 #[cfg(feature = "lstm")]
380 icu_provider::gen_buffer_data_constructors!(
381 (options: LineBreakOptions) -> error: DataError,
382 functions: [
383 try_new_lstm: skip,
384 try_new_lstm_with_buffer_provider,
385 try_new_lstm_unstable,
386 Self,
387 ]
388 );
389
390 #[cfg(feature = "lstm")]
391 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_lstm)]
392 pub fn try_new_lstm_unstable<D>(
393 provider: &D,
394 options: LineBreakOptions,
395 ) -> Result<Self, DataError>
396 where
397 D: DataProvider<SegmenterBreakLineV1>
398 + DataProvider<SegmenterLstmAutoV1>
399 + DataProvider<SegmenterBreakGraphemeClusterV1>
400 + ?Sized,
401 {
402 let mut s = Self::try_new_for_non_complex_scripts_unstable(provider, options)?;
403 s.load_lstm_unstable(provider)?;
404 Ok(s)
405 }
406
407 /// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
408 /// compiled dictionary data for complex scripts (Khmer, Lao, Myanmar, and Thai).
409 ///
410 /// The dictionary model uses a list of words to determine appropriate breakpoints. It is
411 /// faster than the LSTM model but requires more data.
412 ///
413 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
414 ///
415 /// [📚 Help choosing a constructor](icu_provider::constructors)
416 #[cfg(feature = "compiled_data")]
417 pub fn new_dictionary(options: LineBreakOptions) -> LineSegmenterBorrowed<'static> {
418 let mut s = Self::new_for_non_complex_scripts(options);
419 s.load_dictionary();
420 s
421 }
422
423 icu_provider::gen_buffer_data_constructors!(
424 (options: LineBreakOptions) -> error: DataError,
425 functions: [
426 new_dictionary: skip,
427 try_new_dictionary_with_buffer_provider,
428 try_new_dictionary_unstable,
429 Self,
430 ]
431 );
432
433 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_dictionary)]
434 pub fn try_new_dictionary_unstable<D>(
435 provider: &D,
436 options: LineBreakOptions,
437 ) -> Result<Self, DataError>
438 where
439 D: DataProvider<SegmenterBreakLineV1>
440 + DataProvider<SegmenterDictionaryExtendedV1>
441 + DataProvider<SegmenterBreakGraphemeClusterV1>
442 + ?Sized,
443 {
444 let mut s = Self::try_new_for_non_complex_scripts_unstable(provider, options)?;
445 s.load_dictionary_unstable(provider)?;
446 Ok(s)
447 }
448
449 /// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
450 /// no support for scripts requiring complex context dependent line breaks (Khmer, Lao, Myanmar, Thai).
451 ///
452 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
453 ///
454 /// [📚 Help choosing a constructor](icu_provider::constructors)
455 #[cfg(feature = "compiled_data")]
456 pub const fn new_for_non_complex_scripts(
457 options: LineBreakOptions,
458 ) -> LineSegmenterBorrowed<'static> {
459 LineSegmenterBorrowed(LineSegmenterBorrowedInner::V1 {
460 options: options.resolve(),
461 data: Baked::SINGLETON_SEGMENTER_BREAK_LINE_V1,
462 complex: ComplexPayloadsBorrowed::new(),
463 })
464 }
465
466 /// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
467 /// no support for scripts requiring complex context dependent line breaks (Khmer, Lao, Myanmar, Thai).
468 ///
469 /// ✨ *Enabled with the `unstable` Cargo feature.*
470 ///
471 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
472 ///
473 /// [📚 Help choosing a constructor](icu_provider::constructors)
474 #[cfg(feature = "unstable")]
475 #[cfg(feature = "compiled_data")]
476 pub const fn new_17_for_non_complex_scripts(
477 options: LineBreakOptions,
478 ) -> LineSegmenterBorrowed<'static> {
479 LineSegmenterBorrowed(LineSegmenterBorrowedInner::V3 {
480 options: options.resolve(),
481 data: Baked::SINGLETON_SEGMENTER_BREAK_LINE_V3,
482 complex: ComplexPayloadsBorrowed::new(),
483 })
484 }
485
486 icu_provider::gen_buffer_data_constructors!(
487 (options: LineBreakOptions) -> error: DataError,
488 functions: [
489 new_for_non_complex_scripts: skip,
490 try_new_for_non_complex_scripts_with_buffer_provider,
491 try_new_for_non_complex_scripts_unstable,
492 Self,
493 ]
494 );
495
496 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_for_non_complex_scripts)]
497 pub fn try_new_for_non_complex_scripts_unstable<D>(
498 provider: &D,
499 options: LineBreakOptions,
500 ) -> Result<Self, DataError>
501 where
502 D: DataProvider<SegmenterBreakLineV1>
503 + DataProvider<SegmenterBreakGraphemeClusterV1>
504 + ?Sized,
505 {
506 Ok(Self(LineSegmenterInner::V1 {
507 data: provider.load(Default::default())?.payload,
508 options: options.resolve(),
509 complex: ComplexPayloads::try_new(provider)?,
510 }))
511 }
512
513 #[cfg(feature = "unstable")]
514 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_17_for_non_complex_scripts)]
515 pub fn try_new_17_for_non_complex_script_unstable<D>(
516 provider: &D,
517 options: LineBreakOptions,
518 ) -> Result<Self, DataError>
519 where
520 D: DataProvider<SegmenterBreakLineV3>
521 + DataProvider<SegmenterBreakGraphemeClusterV1>
522 + ?Sized,
523 {
524 Ok(Self(LineSegmenterInner::V3 {
525 data: provider.load(Default::default())?.payload,
526 options: options.resolve(),
527 complex: ComplexPayloads::try_new(provider)?,
528 }))
529 }
530
531 /// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
532 /// no support for scripts requiring complex context dependent line breaks (Khmer, Lao, Myanmar, Thai).
533 ///
534 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
535 ///
536 /// [📚 Help choosing a constructor](icu_provider::constructors)
537 #[cfg(feature = "compiled_data")]
538 #[cfg(feature = "unstable")]
539 pub const fn new_neo_for_non_complex_scripts(
540 options: LineBreakOptions,
541 ) -> LineSegmenterBorrowed<'static> {
542 const _: () = assert!(
543 Baked::SEGMENTER_BREAK_LINE_V2_CHECKSUM
544 == Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_CHECKSUM
545 );
546
547 let options = options.resolve();
548 LineSegmenterBorrowed(LineSegmenterBorrowedInner::V2 {
549 data: Baked::SINGLETON_SEGMENTER_BREAK_LINE_V2,
550 tailoring: match (options.ja_zh, options.strictness, options.word_option) {
551 (_, _, LineBreakWordOption::BreakAll) => {
552 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_BREAKALL)
553 }
554 (_, _, LineBreakWordOption::KeepAll) => {
555 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_KEEPALL)
556 }
557 (true, LineBreakStrictness::Loose, LineBreakWordOption::Normal) => {
558 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_JA_LOOSE)
559 }
560 (false, LineBreakStrictness::Loose, LineBreakWordOption::Normal) => {
561 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_LOOSE)
562 }
563 (true, LineBreakStrictness::Normal, LineBreakWordOption::Normal) => {
564 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_JA_NORMAL)
565 }
566 (false, LineBreakStrictness::Normal, LineBreakWordOption::Normal) => {
567 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_NORMAL)
568 }
569 (true, LineBreakStrictness::Strict, LineBreakWordOption::Normal) => {
570 Some(Baked::SEGMENTER_BREAK_LINE_OVERRIDE_V2_UND_JA)
571 }
572 (false, LineBreakStrictness::Strict, LineBreakWordOption::Normal) => None,
573 (_, LineBreakStrictness::Anywhere, _) => {
574 // Return a line segmenter that is actually a grapheme cluster segmenter.
575 return LineSegmenterBorrowed(LineSegmenterBorrowedInner::V2 {
576 data: Baked::SINGLETON_SEGMENTER_BREAK_GRAPHEME_CLUSTER_V2,
577 tailoring: None,
578 complex: ComplexPayloadsBorrowed::new_neo(),
579 });
580 }
581 },
582 complex: ComplexPayloadsBorrowed::new_neo(),
583 })
584 }
585
586 #[cfg(feature = "unstable")]
587 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_neo_for_non_complex_scripts)]
588 pub fn try_new_neo_for_non_complex_scripts_unstable<D>(
589 provider: &D,
590 options: LineBreakOptions,
591 ) -> Result<Self, DataError>
592 where
593 D: DataProvider<SegmenterBreakLineV2>
594 + DataProvider<SegmenterBreakGraphemeClusterV2>
595 + DataProvider<SegmenterBreakLineOverrideV2>
596 + ?Sized,
597 {
598 let options = options.resolve();
599
600 let data = provider.load(Default::default())?;
601
602 let id = match (options.ja_zh, options.strictness, options.word_option) {
603 (_, _, LineBreakWordOption::BreakAll) => {
604 Some(const { DataMarkerAttributes::from_str_or_panic("breakall") })
605 }
606 (_, _, LineBreakWordOption::KeepAll) => {
607 Some(const { DataMarkerAttributes::from_str_or_panic("keepall") })
608 }
609 (true, LineBreakStrictness::Loose, LineBreakWordOption::Normal) => {
610 Some(const { DataMarkerAttributes::from_str_or_panic("ja-loose") })
611 }
612 (false, LineBreakStrictness::Loose, LineBreakWordOption::Normal) => {
613 Some(const { DataMarkerAttributes::from_str_or_panic("loose") })
614 }
615 (true, LineBreakStrictness::Normal, LineBreakWordOption::Normal) => {
616 Some(const { DataMarkerAttributes::from_str_or_panic("ja-normal") })
617 }
618 (false, LineBreakStrictness::Normal, LineBreakWordOption::Normal) => {
619 Some(const { DataMarkerAttributes::from_str_or_panic("normal") })
620 }
621 (true, LineBreakStrictness::Strict, LineBreakWordOption::Normal) => {
622 Some(const { DataMarkerAttributes::from_str_or_panic("ja") })
623 }
624 (false, LineBreakStrictness::Strict, LineBreakWordOption::Normal) => None,
625 (_, LineBreakStrictness::Anywhere, _) => {
626 // Return a line segmenter that is actually a grapheme cluster segmenter.
627 return Ok(Self(LineSegmenterInner::V2 {
628 data: DataProvider::<SegmenterBreakGraphemeClusterV2>::load(
629 provider,
630 Default::default(),
631 )?
632 .payload
633 .cast(),
634 tailoring: None,
635 complex: ComplexPayloads::try_new_neo(provider)?,
636 }));
637 }
638 };
639
640 let tailoring = id
641 .map(|id| {
642 provider.load(DataRequest {
643 id: DataIdentifierBorrowed::for_marker_attributes(id),
644 metadata: Default::default(),
645 })
646 })
647 .transpose()?;
648
649 if let Some(ref tailoring) = tailoring
650 && let Some(id) = id
651 && data.metadata.checksum != tailoring.metadata.checksum
652 {
653 return Err(
654 DataErrorKind::InconsistentData(SegmenterBreakLineV2::INFO).with_req(
655 SegmenterBreakLineOverrideV2::INFO,
656 DataRequest {
657 id: DataIdentifierBorrowed::for_marker_attributes(id),
658 metadata: Default::default(),
659 },
660 ),
661 );
662 }
663
664 Ok(Self(LineSegmenterInner::V2 {
665 data: data.payload,
666 complex: ComplexPayloads::try_new_neo(provider)?,
667 tailoring: tailoring.map(|d| d.payload),
668 }))
669 }
670
671 /// Loads LSTM data for a [`LineSegmenter`] constructed with
672 /// [`LineSegmenter::new_for_non_complex_scripts`].
673 ///
674 /// ✨ *Enabled with the `lstm` Cargo feature.*
675 #[cfg(feature = "lstm")]
676 pub fn load_lstm_unstable<D>(&mut self, provider: &D) -> Result<(), DataError>
677 where
678 D: DataProvider<SegmenterLstmAutoV1> + ?Sized,
679 {
680 // Line segmenter doesn't need to load CJ dictionary because UAX 14 rules handles CJK
681 // characters [1]. Southeast Asian languages however require complex context analysis
682 // [2].
683 //
684 // [1]: https://www.unicode.org/reports/tr14/#ID
685 // [2]: https://www.unicode.org/reports/tr14/#SA
686 match self.0 {
687 LineSegmenterInner::V1 {
688 ref mut complex, ..
689 } => complex,
690 #[cfg(feature = "unstable")]
691 LineSegmenterInner::V2 {
692 ref mut complex, ..
693 } => complex,
694 #[cfg(feature = "unstable")]
695 LineSegmenterInner::V3 {
696 ref mut complex, ..
697 } => complex,
698 }
699 .with_southeast_asian_lstms(provider)
700 }
701
702 /// A version of [`Self::load_lstm_unstable`] that uses custom data
703 /// provided by a [`BufferProvider`].
704 ///
705 /// ✨ *Enabled with the `serde` Cargo feature.*
706 #[cfg(feature = "serde")]
707 #[cfg(feature = "lstm")]
708 pub fn load_lstm_with_buffer_provider(
709 &mut self,
710 provider: &(impl BufferProvider + ?Sized),
711 ) -> Result<(), DataError> {
712 self.load_lstm_unstable(&provider.as_deserializing())
713 }
714
715 /// Loads dictionary data for a [`LineSegmenter`] constructed with
716 /// [`LineSegmenter::new_for_non_complex_scripts`].
717 pub fn load_dictionary_unstable<D>(&mut self, provider: &D) -> Result<(), DataError>
718 where
719 D: DataProvider<SegmenterDictionaryExtendedV1> + ?Sized,
720 {
721 // Line segmenter doesn't need to load CJ dictionary because UAX 14 rules handles CJK
722 // characters [1]. Southeast Asian languages however require complex context analysis
723 // [2].
724 //
725 // [1]: https://www.unicode.org/reports/tr14/#ID
726 // [2]: https://www.unicode.org/reports/tr14/#SA
727 match self.0 {
728 LineSegmenterInner::V1 {
729 ref mut complex, ..
730 } => complex,
731 #[cfg(feature = "unstable")]
732 LineSegmenterInner::V2 {
733 ref mut complex, ..
734 } => complex,
735 #[cfg(feature = "unstable")]
736 LineSegmenterInner::V3 {
737 ref mut complex, ..
738 } => complex,
739 }
740 .with_southeast_asian_dictionaries(provider)
741 }
742
743 /// A version of [`Self::load_dictionary_unstable`] that uses custom data
744 /// provided by a [`BufferProvider`].
745 ///
746 /// ✨ *Enabled with the `serde` Cargo feature.*
747 #[cfg(feature = "serde")]
748 pub fn load_dictionary_with_buffer_provider(
749 &mut self,
750 provider: &(impl BufferProvider + ?Sized),
751 ) -> Result<(), DataError> {
752 self.load_dictionary_unstable(&provider.as_deserializing())
753 }
754
755 /// Constructs a borrowed version of this type for more efficient querying.
756 ///
757 /// Most useful methods for segmentation are on this type.
758 pub fn as_borrowed(&self) -> LineSegmenterBorrowed<'_> {
759 LineSegmenterBorrowed(match &self.0 {
760 LineSegmenterInner::V1 {
761 data,
762 options,
763 complex,
764 } => LineSegmenterBorrowedInner::V1 {
765 options: *options,
766 data: data.get(),
767 complex: complex.as_borrowed(),
768 },
769 #[cfg(feature = "unstable")]
770 LineSegmenterInner::V2 {
771 data,
772 tailoring,
773 complex,
774 } => LineSegmenterBorrowedInner::V2 {
775 data: data.get(),
776 tailoring: tailoring.as_ref().map(|t| t.get()),
777 complex: complex.as_borrowed(),
778 },
779 #[cfg(feature = "unstable")]
780 LineSegmenterInner::V3 {
781 data,
782 options,
783 complex,
784 } => LineSegmenterBorrowedInner::V3 {
785 options: *options,
786 data: data.get(),
787 complex: complex.as_borrowed(),
788 },
789 })
790 }
791 }
792
793 impl<'data> LineSegmenterBorrowed<'data> {
794 /// Creates a line break iterator for an `str` (a UTF-8 string).
795 ///
796 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
797 pub fn segment_str<'s>(self, input: &'s str) -> LineBreakIterator<'data, 's, Utf8> {
798 LineBreakIterator(match self.0 {
799 LineSegmenterBorrowedInner::V1 {
800 options,
801 data,
802 complex,
803 } => LineBreakIteratorInner::V1(v1::LineBreakIteratorV1::new(
804 input.char_indices(),
805 input.len(),
806 data,
807 options,
808 complex,
809 v1::line_handle_complex_utf8,
810 )),
811 #[cfg(feature = "unstable")]
812 LineSegmenterBorrowedInner::V2 {
813 data,
814 tailoring,
815 complex,
816 } => LineBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new(
817 input.char_indices(),
818 data,
819 tailoring,
820 Some(complex),
821 )),
822 #[cfg(feature = "unstable")]
823 LineSegmenterBorrowedInner::V3 {
824 options,
825 data,
826 complex,
827 } => LineBreakIteratorInner::V3(v3::LineBreakIteratorV3::new(
828 input.char_indices(),
829 input.len(),
830 data,
831 options,
832 complex,
833 v3::line_handle_complex_utf8,
834 )),
835 })
836 }
837 /// Creates a line break iterator for a potentially ill-formed UTF8 string
838 ///
839 /// Invalid characters are treated as REPLACEMENT CHARACTER
840 ///
841 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
842 pub fn segment_utf8<'s>(
843 self,
844 input: &'s [u8],
845 ) -> LineBreakIterator<'data, 's, PotentiallyIllFormedUtf8> {
846 LineBreakIterator(match self.0 {
847 LineSegmenterBorrowedInner::V1 {
848 data,
849 options,
850 complex,
851 } => LineBreakIteratorInner::V1(v1::LineBreakIteratorV1::new(
852 Utf8CharIndices::new(input),
853 input.len(),
854 data,
855 options,
856 complex,
857 v1::line_handle_complex_utf8,
858 )),
859 #[cfg(feature = "unstable")]
860 LineSegmenterBorrowedInner::V2 {
861 data,
862 tailoring,
863 complex,
864 } => LineBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new(
865 Utf8CharIndices::new(input),
866 data,
867 tailoring,
868 Some(complex),
869 )),
870 #[cfg(feature = "unstable")]
871 LineSegmenterBorrowedInner::V3 {
872 data,
873 options,
874 complex,
875 } => LineBreakIteratorInner::V3(v3::LineBreakIteratorV3::new(
876 Utf8CharIndices::new(input),
877 input.len(),
878 data,
879 options,
880 complex,
881 v3::line_handle_complex_utf8,
882 )),
883 })
884 }
885
886 /// Creates a line break iterator for a Latin-1 (8-bit) string.
887 ///
888 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
889 pub fn segment_latin1<'s>(self, input: &'s [u8]) -> LineBreakIterator<'data, 's, Latin1> {
890 LineBreakIterator(match self.0 {
891 LineSegmenterBorrowedInner::V1 {
892 data,
893 options,
894 complex,
895 } => LineBreakIteratorInner::V1(v1::LineBreakIteratorV1::new(
896 Latin1Indices::new(input),
897 input.len(),
898 data,
899 options,
900 complex,
901 |_, _| None,
902 )),
903 #[cfg(feature = "unstable")]
904 LineSegmenterBorrowedInner::V2 {
905 data, tailoring, ..
906 } => LineBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new(
907 Latin1Indices::new(input),
908 data,
909 tailoring,
910 None,
911 )),
912 #[cfg(feature = "unstable")]
913 LineSegmenterBorrowedInner::V3 {
914 data,
915 options,
916 complex,
917 } => LineBreakIteratorInner::V3(v3::LineBreakIteratorV3::new(
918 Latin1Indices::new(input),
919 input.len(),
920 data,
921 options,
922 complex,
923 |_, _| None,
924 )),
925 })
926 }
927
928 /// Creates a line break iterator for a UTF-16 string.
929 ///
930 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
931 pub fn segment_utf16<'s>(self, input: &'s [u16]) -> LineBreakIterator<'data, 's, Utf16> {
932 LineBreakIterator(match self.0 {
933 LineSegmenterBorrowedInner::V1 {
934 data,
935 options,
936 complex,
937 } => LineBreakIteratorInner::V1(v1::LineBreakIteratorV1::new(
938 Utf16Indices::new(input),
939 input.len(),
940 data,
941 options,
942 complex,
943 v1::line_handle_complex_utf16,
944 )),
945 #[cfg(feature = "unstable")]
946 LineSegmenterBorrowedInner::V2 {
947 data,
948 tailoring,
949 complex,
950 } => LineBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator::new(
951 Utf16Indices::new(input),
952 data,
953 tailoring,
954 Some(complex),
955 )),
956 #[cfg(feature = "unstable")]
957 LineSegmenterBorrowedInner::V3 {
958 data,
959 options,
960 complex,
961 } => LineBreakIteratorInner::V3(v3::LineBreakIteratorV3::new(
962 Utf16Indices::new(input),
963 input.len(),
964 data,
965 options,
966 complex,
967 v3::line_handle_complex_utf16,
968 )),
969 })
970 }
971 }
972
973 impl LineSegmenterBorrowed<'static> {
974 /// Loads LSTM data for a [`LineSegmenter`] constructed with
975 /// [`LineSegmenter::new_for_non_complex_scripts`].
976 ///
977 /// ✨ *Enabled with the `compiled_data` and `lstm` Cargo features.*
978 #[cfg(feature = "lstm")]
979 #[cfg(feature = "compiled_data")]
980 pub fn load_lstm(&mut self) {
981 // Line segmenter doesn't need to load CJ dictionary because UAX 14 rules handles CJK
982 // characters [1]. Southeast Asian languages however require complex context analysis
983 // [2].
984 //
985 // [1]: https://www.unicode.org/reports/tr14/#ID
986 // [2]: https://www.unicode.org/reports/tr14/#SA,
987 match self.0 {
988 LineSegmenterBorrowedInner::V1 {
989 ref mut complex, ..
990 } => complex,
991 #[cfg(feature = "unstable")]
992 LineSegmenterBorrowedInner::V2 {
993 ref mut complex, ..
994 } => complex,
995 #[cfg(feature = "unstable")]
996 LineSegmenterBorrowedInner::V3 {
997 ref mut complex, ..
998 } => complex,
999 }
1000 .with_southeast_asian_lstms()
1001 }
1002
1003 /// Loads dictionary data for a [`LineSegmenter`] constructed with
1004 /// [`LineSegmenter::new_for_non_complex_scripts`].
1005 ///
1006 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1007 #[cfg(feature = "compiled_data")]
1008 pub fn load_dictionary(&mut self) {
1009 // Line segmenter doesn't need to load CJ dictionary because UAX 14 rules handles CJK
1010 // characters [1]. Southeast Asian languages however require complex context analysis
1011 // [2].
1012 //
1013 // [1]: https://www.unicode.org/reports/tr14/#ID
1014 // [2]: https://www.unicode.org/reports/tr14/#SA
1015 match self.0 {
1016 LineSegmenterBorrowedInner::V1 {
1017 ref mut complex, ..
1018 } => complex,
1019 #[cfg(feature = "unstable")]
1020 LineSegmenterBorrowedInner::V2 {
1021 ref mut complex, ..
1022 } => complex,
1023 #[cfg(feature = "unstable")]
1024 LineSegmenterBorrowedInner::V3 {
1025 ref mut complex, ..
1026 } => complex,
1027 }
1028 .with_southeast_asian_dictionaries()
1029 }
1030
1031 /// Cheaply converts a [`LineSegmenterBorrowed<'static>`] into a [`LineSegmenter`].
1032 ///
1033 /// Note: Due to branching and indirection, using [`LineSegmenter`] might inhibit some
1034 /// compile-time optimizations that are possible with [`LineSegmenterBorrowed`].
1035 pub fn static_to_owned(self) -> LineSegmenter {
1036 LineSegmenter(match self.0 {
1037 LineSegmenterBorrowedInner::V1 {
1038 data,
1039 options,
1040 complex,
1041 } => LineSegmenterInner::V1 {
1042 data: DataPayload::from_static_ref(data),
1043 complex: complex.static_to_owned(),
1044 options,
1045 },
1046 #[cfg(feature = "unstable")]
1047 LineSegmenterBorrowedInner::V2 {
1048 data,
1049 tailoring,
1050 complex,
1051 } => LineSegmenterInner::V2 {
1052 data: DataPayload::from_static_ref(data),
1053 complex: complex.static_to_owned(),
1054 tailoring: tailoring.map(DataPayload::from_static_ref),
1055 },
1056 #[cfg(feature = "unstable")]
1057 LineSegmenterBorrowedInner::V3 {
1058 data,
1059 options,
1060 complex,
1061 } => LineSegmenterInner::V3 {
1062 data: DataPayload::from_static_ref(data),
1063 complex: complex.static_to_owned(),
1064 options,
1065 },
1066 })
1067 }
1068 }
1069
1070 /// Implements the [`Iterator`] trait over the line break opportunities of the given string.
1071 ///
1072 /// Lifetimes:
1073 ///
1074 /// - `'l` = lifetime of the [`LineSegmenter`] object from which this iterator was created
1075 /// - `'s` = lifetime of the string being segmented
1076 ///
1077 /// The [`Iterator::Item`] is an [`usize`] representing index of a code unit
1078 /// _after_ the break (for a break at the end of text, this index is the length
1079 /// of the [`str`] or array of code units).
1080 ///
1081 /// For examples of use, see [`LineSegmenter`].
1082 #[derive(Debug)]
1083 pub struct LineBreakIterator<'data, 's, Y: RuleBreakType>(LineBreakIteratorInner<'data, 's, Y>);
1084
1085 #[derive(Debug)]
1086 enum LineBreakIteratorInner<'data, 's, Y: RuleBreakType> {
1087 V1(v1::LineBreakIteratorV1<'data, 's, Y>),
1088 #[cfg(feature = "unstable")]
1089 V2(crate::rule_segmenter_v2::RuleBreakIterator<'data, 's, Y, ComplexLine<Y>>),
1090 #[cfg(feature = "unstable")]
1091 V3(v3::LineBreakIteratorV3<'data, 's, Y>),
1092 }
1093
1094 impl<Y: RuleBreakType> Iterator for LineBreakIterator<'_, '_, Y> {
1095 type Item = usize;
1096
1097 fn next(&mut self) -> Option<Self::Item> {
1098 match self.0 {
1099 LineBreakIteratorInner::V1(ref mut iter) => iter.next(),
1100 #[cfg(feature = "unstable")]
1101 LineBreakIteratorInner::V2(ref mut iter) => iter.next(),
1102 #[cfg(feature = "unstable")]
1103 LineBreakIteratorInner::V3(ref mut iter) => iter.next(),
1104 }
1105 }
1106 }
1107
1108 #[cfg(feature = "unstable")]
1109 impl<Y: RuleBreakType> LineBreakIterator<'_, '_, Y> {
1110 /// Returns whether the last break was mandatory
1111 pub fn is_mandatory(&self) -> bool {
1112 match self.0 {
1113 LineBreakIteratorInner::V1(_) => false,
1114 #[cfg(feature = "unstable")]
1115 LineBreakIteratorInner::V2(ref iter) => iter.last_accepting_status() == (true as u8),
1116 #[cfg(feature = "unstable")]
1117 LineBreakIteratorInner::V3(_) => false,
1118 }
1119 }
1120 }
1121
1122 #[derive(Debug)]
1123 #[cfg(feature = "unstable")]
1124 struct ComplexLine<Y>(core::marker::PhantomData<Y>);
1125
1126 #[cfg(feature = "unstable")]
1127 impl<Y: RuleBreakType> crate::rule_segmenter_v2::ComplexHandler<Y> for ComplexLine<Y> {
1128 const BREAK_AT_BOUNDARIES: bool = false;
1129 const BREAK_STATUS: u8 = false as u8;
1130 type Cache = [usize; 16];
1131
1132 type ComplexPayloads<'s> = Y::ComplexPayloads<'s>;
1133 type ComplexPayload<'s> = Y::ComplexPayload<'s>;
1134
1135 fn select<'data>(
1136 complex_payloads: &Self::ComplexPayloads<'data>,
1137 complex_script: ComplexScript,
1138 ) -> Option<Self::ComplexPayload<'data>> {
1139 Y::select_complex(complex_payloads, complex_script)
1140 }
1141
1142 fn handle<'data, 's>(
1143 complex_payload: &Self::ComplexPayload<'data>,
1144 iter: &Y::IterAttr<'s>,
1145 past_complex: &Y::IterAttr<'s>,
1146 ) -> ComplexIterator<'data, 's, Y> {
1147 Y::handle_complex(complex_payload, iter, past_complex)
1148 }
1149 }
1150
1151 #[cfg(test)]
1152 mod tests {
1153 use super::*;
1154 use crate::LineSegmenterBorrowed;
1155 use crate::*;
1156
1157 include!("../tests/helpers.rs.raw");
1158
1159 #[test]
1160 fn test_mandatory() {
1161 let mut actual_breaks = LineSegmenter::new_neo_for_non_complex_scripts(Default::default())
1162 .segment_str("this has a mandatory\nline break");
1163
1164 assert_eq!(actual_breaks.next(), Some(0));
1165 assert_eq!(actual_breaks.is_mandatory(), false);
1166 assert_eq!(actual_breaks.next(), Some(5));
1167 assert_eq!(actual_breaks.is_mandatory(), false);
1168 assert_eq!(actual_breaks.next(), Some(9));
1169 assert_eq!(actual_breaks.is_mandatory(), false);
1170 assert_eq!(actual_breaks.next(), Some(11));
1171 assert_eq!(actual_breaks.is_mandatory(), false);
1172 assert_eq!(actual_breaks.next(), Some(21));
1173 assert_eq!(actual_breaks.is_mandatory(), true);
1174 assert_eq!(actual_breaks.next(), Some(26));
1175 assert_eq!(actual_breaks.is_mandatory(), false);
1176 assert_eq!(actual_breaks.next(), Some(31));
1177 assert_eq!(actual_breaks.is_mandatory(), true);
1178 assert_eq!(actual_breaks.next(), None);
1179 }
1180
1181 #[test]
1182 fn linebreak() {
1183 let segmenter = LineSegmenter::new_dictionary(Default::default());
1184
1185 check_line("hello world", &["hello ", "world"], segmenter);
1186
1187 check_line("$10 $10", &["$10 ", "$10"], segmenter);
1188
1189 // LB10
1190
1191 // LB14
1192 check_line("[ abc def", &["[ abc ", "def"], segmenter);
1193
1194 // LB15 used to prevent the break at 6, but has been removed in Unicode 15.1.
1195 check_line("abc\u{0022} (def", &["abc\u{0022} ", "(def"], segmenter);
1196
1197 // Instead, in Unicode 15.1, LB15a and LB15b prevent these breaks.
1198 check_line("« miaou »", &["« miaou »"], segmenter);
1199
1200 // But not these:
1201 check_line(
1202 "Die Katze hat »miau« gesagt.",
1203 &["Die ", "Katze ", "hat ", "»miau« ", "gesagt."],
1204 segmenter,
1205 );
1206
1207 // LB16
1208 check_line("\u{0029}\u{203C}", &["\u{0029}\u{203C}"], segmenter);
1209 check_line("\u{0029} \u{203C}", &["\u{0029} \u{203C}"], segmenter);
1210
1211 // LB17
1212 check_line("\u{2014}\u{2014}aa", &["\u{2014}\u{2014}", "aa"], segmenter);
1213 check_line(
1214 "\u{2014} \u{2014}aa",
1215 &["\u{2014} \u{2014}", "aa"],
1216 segmenter,
1217 );
1218
1219 check_line(
1220 "\u{2014}\u{2014} \u{2014}\u{2014}123 abc",
1221 &["\u{2014}\u{2014} \u{2014}\u{2014}", "123 ", "abc"],
1222 segmenter,
1223 );
1224
1225 // LB25
1226 check_line("(0,1)+(2,3)", &["(0,1)+(2,3)"], segmenter);
1227
1228 check_line("—— ——123 abc", &["—— ——", "123 ", "abc"], segmenter);
1229 check_line(
1230 "\u{1F3FB} \u{1F3FB}",
1231 &["\u{1F3FB} ", "\u{1F3FB}"],
1232 segmenter,
1233 );
1234 }
1235
1236 #[test]
1237 fn linebreak_17() {
1238 let segmenter = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1239
1240 check_line("hello world", &["hello ", "world"], segmenter);
1241
1242 check_line("$10 $10", &["$10 ", "$10"], segmenter);
1243
1244 // LB10
1245
1246 // LB14
1247 check_line("[ abc def", &["[ abc ", "def"], segmenter);
1248
1249 // LB15 used to prevent the break at 6, but has been removed in Unicode 15.1.
1250 check_line("abc\u{0022} (def", &["abc\u{0022} ", "(def"], segmenter);
1251
1252 // Instead, in Unicode 15.1, LB15a and LB15b prevent these breaks.
1253 check_line("« miaou »", &["« miaou »"], segmenter);
1254
1255 // But not these:
1256 check_line(
1257 "Die Katze hat »miau« gesagt.",
1258 &["Die ", "Katze ", "hat ", "»miau« ", "gesagt."],
1259 segmenter,
1260 );
1261
1262 // LB16
1263 check_line("\u{0029}\u{203C}", &["\u{0029}\u{203C}"], segmenter);
1264 check_line("\u{0029} \u{203C}", &["\u{0029} \u{203C}"], segmenter);
1265
1266 // LB17
1267 check_line("\u{2014}\u{2014}aa", &["\u{2014}\u{2014}", "aa"], segmenter);
1268 check_line(
1269 "\u{2014} \u{2014}aa",
1270 &["\u{2014} \u{2014}", "aa"],
1271 segmenter,
1272 );
1273
1274 check_line(
1275 "\u{2014}\u{2014} \u{2014}\u{2014}123 abc",
1276 &["\u{2014}\u{2014} \u{2014}\u{2014}", "123 ", "abc"],
1277 segmenter,
1278 );
1279
1280 // LB25
1281 check_line("(0,1)+(2,3)", &["(0,1)+(2,3)"], segmenter);
1282
1283 check_line("—— ——123 abc", &["—— ——", "123 ", "abc"], segmenter);
1284 check_line(
1285 "\u{1F3FB} \u{1F3FB}",
1286 &["\u{1F3FB} ", "\u{1F3FB}"],
1287 segmenter,
1288 );
1289 }
1290
1291 #[test]
1292 fn linebreak_neo() {
1293 let segmenter = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1294
1295 check_line("hello world", &["hello ", "world"], segmenter);
1296
1297 check_line("$10 $10", &["$10 ", "$10"], segmenter);
1298
1299 // LB10
1300
1301 // LB14
1302 check_line("[ abc def", &["[ abc ", "def"], segmenter);
1303
1304 // LB15 used to prevent the break at 6, but has been removed in Unicode 15.1.
1305 check_line("abc\u{0022} (def", &["abc\u{0022} ", "(def"], segmenter);
1306
1307 // Instead, in Unicode 15.1, LB15a and LB15b prevent these breaks.
1308 check_line("« miaou »", &["« miaou »"], segmenter);
1309
1310 // But not these:
1311 check_line(
1312 "Die Katze hat »miau« gesagt.",
1313 &["Die ", "Katze ", "hat ", "»miau« ", "gesagt."],
1314 segmenter,
1315 );
1316
1317 // LB16
1318 check_line("\u{0029}\u{203C}", &["\u{0029}\u{203C}"], segmenter);
1319 check_line("\u{0029} \u{203C}", &["\u{0029} \u{203C}"], segmenter);
1320
1321 // LB17
1322 check_line("\u{2014}\u{2014}aa", &["\u{2014}\u{2014}", "aa"], segmenter);
1323 check_line(
1324 "\u{2014} \u{2014}aa",
1325 &["\u{2014} \u{2014}", "aa"],
1326 segmenter,
1327 );
1328
1329 check_line(
1330 "\u{2014}\u{2014} \u{2014}\u{2014}123 abc",
1331 &["\u{2014}\u{2014} \u{2014}\u{2014}", "123 ", "abc"],
1332 segmenter,
1333 );
1334
1335 // LB25
1336 check_line("(0,1)+(2,3)", &["(0,1)+(2,3)"], segmenter);
1337
1338 check_line("—— ——123 abc", &["—— ——", "123 ", "abc"], segmenter);
1339 check_line(
1340 "\u{1F3FB} \u{1F3FB}",
1341 &["\u{1F3FB} ", "\u{1F3FB}"],
1342 segmenter,
1343 );
1344 }
1345
1346 #[test]
1347 fn thai_line_break() {
1348 check_line(
1349 "ภาษาไทยภาษาไทย",
1350 &["ภาษา", "ไทย", "ภาษา", "ไทย"],
1351 LineSegmenter::new_lstm(Default::default()),
1352 );
1353
1354 check_line(
1355 "ภาษาไทยภาษาไทย",
1356 &["ภาษา", "ไทย", "ภาษา", "ไทย"],
1357 LineSegmenter::new_dictionary(Default::default()),
1358 );
1359
1360 check_line(
1361 "ภาษา",
1362 &["ภาษา"],
1363 LineSegmenter::new_lstm(Default::default()),
1364 );
1365
1366 check_line(
1367 "ภาษา",
1368 &["ภาษา"],
1369 LineSegmenter::new_dictionary(Default::default()),
1370 );
1371 }
1372
1373 #[test]
1374 fn thai_line_break_17() {
1375 check_line(
1376 "ภาษาไทยภาษาไทย",
1377 &["ภาษา", "ไทย", "ภาษา", "ไทย"],
1378 {
1379 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1380 s.load_lstm();
1381 s
1382 },
1383 );
1384
1385 check_line(
1386 "ภาษาไทยภาษาไทย",
1387 &["ภาษา", "ไทย", "ภาษา", "ไทย"],
1388 {
1389 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1390 s.load_dictionary();
1391 s
1392 },
1393 );
1394
1395 check_line("ภาษา", &["ภาษา"], {
1396 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1397 s.load_lstm();
1398 s
1399 });
1400
1401 check_line("ภาษา", &["ภาษา"], {
1402 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1403 s.load_dictionary();
1404 s
1405 });
1406 }
1407
1408 #[test]
1409 fn thai_line_break_neo() {
1410 check_line(
1411 "ภาษาไทยภาษาไทย",
1412 &["ภาษา", "ไทย", "ภาษา", "ไทย"],
1413 {
1414 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1415 s.load_lstm();
1416 s
1417 },
1418 );
1419
1420 check_line(
1421 "ภาษาไทยภาษาไทย",
1422 &["ภาษา", "ไทย", "ภาษา", "ไทย"],
1423 {
1424 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1425 s.load_dictionary();
1426 s
1427 },
1428 );
1429
1430 check_line("ภาษา", &["ภาษา"], {
1431 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1432 s.load_lstm();
1433 s
1434 });
1435
1436 check_line("ภาษา", &["ภาษา"], {
1437 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1438 s.load_dictionary();
1439 s
1440 });
1441
1442 // # 8243
1443 check_line(
1444 "ก\u{2060}รุ\u{2060}ง",
1445 &["ก\u{2060}รุ\u{2060}ง"],
1446 {
1447 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1448 s.load_dictionary();
1449 s
1450 },
1451 );
1452 }
1453
1454 #[test]
1455 fn burmese_line_break() {
1456 // "Burmese Language" in Burmese
1457
1458 check_line(
1459 "မြန်မာဘာသာစကား",
1460 &["မြန်", "မာ", "ဘာသာ", "စကား"],
1461 LineSegmenter::new_lstm(Default::default()),
1462 );
1463
1464 check_line(
1465 "မြန်မာဘာသာစကား",
1466 &["မြန်မာဘာသာ", "စကား"],
1467 LineSegmenter::new_dictionary(Default::default()),
1468 );
1469 }
1470
1471 #[test]
1472 fn burmese_line_break_17() {
1473 // "Burmese Language" in Burmese
1474
1475 check_line(
1476 "မြန်မာဘာသာစကား",
1477 &["မြန်", "မာ", "ဘာသာ", "စကား"],
1478 {
1479 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1480 s.load_lstm();
1481 s
1482 },
1483 );
1484
1485 check_line(
1486 "မြန်မာဘာသာစကား",
1487 &["မြန်မာဘာသာ", "စကား"],
1488 {
1489 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1490 s.load_dictionary();
1491 s
1492 },
1493 );
1494 }
1495
1496 #[test]
1497 fn burmese_line_break_neo() {
1498 // "Burmese Language" in Burmese
1499
1500 check_line(
1501 "မြန်မာဘာသာစကား",
1502 &["မြန်", "မာ", "ဘာသာ", "စကား"],
1503 {
1504 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1505 s.load_lstm();
1506 s
1507 },
1508 );
1509
1510 check_line(
1511 "မြန်မာဘာသာစကား",
1512 &["မြန်မာဘာသာ", "စကား"],
1513 {
1514 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1515 s.load_dictionary();
1516 s
1517 },
1518 );
1519 }
1520
1521 #[test]
1522 fn khmer_line_break() {
1523 check_line(
1524 "សេចក្ដីប្រកាសជាសកលស្ដីពីសិទ្ធិមនុស្ស",
1525 &["សេចក្ដីប្រកាស", "ជាស", "កល", "ស្ដីពី", "សិទ្ធិមនុស្ស"],
1526 LineSegmenter::new_lstm(Default::default()),
1527 );
1528
1529 check_line(
1530 "សេចក្ដីប្រកាសជាសកលស្ដីពីសិទ្ធិមនុស្ស",
1531 &["សេចក្ដីប្រកាស", "ជាស", "កល", "ស្ដីពី", "សិទ្ធិមនុស្ស"],
1532 LineSegmenter::new_dictionary(Default::default()),
1533 );
1534 }
1535
1536 #[test]
1537 fn khmer_line_break_17() {
1538 check_line(
1539 "សេចក្ដីប្រកាសជាសកលស្ដីពីសិទ្ធិមនុស្ស",
1540 &["សេចក្ដីប្រកាស", "ជាស", "កល", "ស្ដីពី", "សិទ្ធិមនុស្ស"],
1541 {
1542 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1543 s.load_lstm();
1544 s
1545 },
1546 );
1547
1548 check_line(
1549 "សេចក្ដីប្រកាសជាសកលស្ដីពីសិទ្ធិមនុស្ស",
1550 &["សេចក្ដីប្រកាស", "ជាស", "កល", "ស្ដីពី", "សិទ្ធិមនុស្ស"],
1551 {
1552 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1553 s.load_dictionary();
1554 s
1555 },
1556 );
1557 }
1558
1559 #[test]
1560 fn khmer_line_break_neo() {
1561 check_line(
1562 "សេចក្ដីប្រកាសជាសកលស្ដីពីសិទ្ធិមនុស្ស",
1563 &["សេចក្ដីប្រកាស", "ជាស", "កល", "ស្ដីពី", "សិទ្ធិមនុស្ស"],
1564 {
1565 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1566 s.load_lstm();
1567 s
1568 },
1569 );
1570
1571 check_line(
1572 "សេចក្ដីប្រកាសជាសកលស្ដីពីសិទ្ធិមនុស្ស",
1573 &["សេចក្ដីប្រកាស", "ជាស", "កល", "ស្ដីពី", "សិទ្ធិមនុស្ស"],
1574 {
1575 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1576 s.load_dictionary();
1577 s
1578 },
1579 );
1580
1581 // #7218
1582 check_line(
1583 "អស់ នឹង មាន",
1584 &["អស់ ", "នឹង ", "មាន"],
1585 {
1586 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1587 s.load_dictionary();
1588 s
1589 },
1590 );
1591 }
1592
1593 #[test]
1594 fn lao_line_break() {
1595 check_line(
1596 "ກ່ຽວກັບສິດຂອງມະນຸດ",
1597 &["ກ່ຽວ", "ກັບ", "ສິດ", "ຂອງ", "ມະນຸດ"],
1598 LineSegmenter::new_lstm(Default::default()),
1599 );
1600
1601 check_line(
1602 "ກ່ຽວກັບສິດຂອງມະນຸດ",
1603 &["ກ່ຽວກັບ", "ສິດ", "ຂອງ", "ມະນຸດ"],
1604 LineSegmenter::new_dictionary(Default::default()),
1605 );
1606 }
1607
1608 #[test]
1609 fn lao_line_break_17() {
1610 check_line(
1611 "ກ່ຽວກັບສິດຂອງມະນຸດ",
1612 &["ກ່ຽວ", "ກັບ", "ສິດ", "ຂອງ", "ມະນຸດ"],
1613 {
1614 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1615 s.load_lstm();
1616 s
1617 },
1618 );
1619
1620 check_line(
1621 "ກ່ຽວກັບສິດຂອງມະນຸດ",
1622 &["ກ່ຽວກັບ", "ສິດ", "ຂອງ", "ມະນຸດ"],
1623 {
1624 let mut s = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1625 s.load_dictionary();
1626 s
1627 },
1628 );
1629 }
1630
1631 #[test]
1632 fn lao_line_break_neo() {
1633 check_line(
1634 "ກ່ຽວກັບສິດຂອງມະນຸດ",
1635 &["ກ່ຽວ", "ກັບ", "ສິດ", "ຂອງ", "ມະນຸດ"],
1636 {
1637 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1638 s.load_lstm();
1639 s
1640 },
1641 );
1642
1643 check_line(
1644 "ກ່ຽວກັບສິດຂອງມະນຸດ",
1645 &["ກ່ຽວກັບ", "ສິດ", "ຂອງ", "ມະນຸດ"],
1646 {
1647 let mut s = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1648 s.load_dictionary();
1649 s
1650 },
1651 );
1652 }
1653
1654 #[test]
1655 fn empty_string() {
1656 let segmenter = LineSegmenter::new_for_non_complex_scripts(Default::default());
1657 let breaks: Vec<usize> = segmenter.segment_str("").collect();
1658 assert_eq!(breaks, [0]);
1659 }
1660
1661 #[test]
1662 fn empty_string_17() {
1663 let segmenter = LineSegmenter::new_17_for_non_complex_scripts(Default::default());
1664 let breaks: Vec<usize> = segmenter.segment_str("").collect();
1665 assert_eq!(breaks, [0]);
1666 }
1667
1668 #[test]
1669 fn empty_string_neo() {
1670 let segmenter = LineSegmenter::new_neo_for_non_complex_scripts(Default::default());
1671 let breaks: Vec<usize> = segmenter.segment_str("").collect();
1672 assert_eq!(breaks, [0]);
1673 }
1674 }