-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathline.rs
1699 lines (1554 loc) · 60.6 KB
/
line.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::complex::*;
use crate::indices::*;
use crate::provider::*;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::char;
use core::str::CharIndices;
use icu_locale_core::subtags::language;
use icu_locale_core::LanguageIdentifier;
use icu_provider::prelude::*;
use utf8_iter::Utf8CharIndices;
// TODO(#1637): These constants should be data driven.
#[allow(dead_code)]
const UNKNOWN: u8 = 0;
#[allow(dead_code)]
const AI: u8 = 1;
#[allow(dead_code)]
const AK: u8 = 2;
#[allow(dead_code)]
const AL: u8 = 3;
#[allow(dead_code)]
const AL_DOTTED_CIRCLE: u8 = 4;
#[allow(dead_code)]
const AP: u8 = 5;
#[allow(dead_code)]
const AS: u8 = 6;
#[allow(dead_code)]
const B2: u8 = 7;
#[allow(dead_code)]
const BA: u8 = 8;
#[allow(dead_code)]
const BB: u8 = 9;
#[allow(dead_code)]
const BK: u8 = 10;
#[allow(dead_code)]
const CB: u8 = 11;
#[allow(dead_code)]
const CJ: u8 = 12;
#[allow(dead_code)]
const CL: u8 = 13;
#[allow(dead_code)]
const CM: u8 = 14;
#[allow(dead_code)]
const CP: u8 = 15;
#[allow(dead_code)]
const CR: u8 = 16;
#[allow(dead_code)]
const EB: u8 = 17;
#[allow(dead_code)]
const EM: u8 = 18;
#[allow(dead_code)]
const EX: u8 = 19;
#[allow(dead_code)]
const GL: u8 = 20;
#[allow(dead_code)]
const H2: u8 = 21;
#[allow(dead_code)]
const H3: u8 = 22;
#[allow(dead_code)]
const HL: u8 = 23;
#[allow(dead_code)]
const HY: u8 = 24;
#[allow(dead_code)]
const ID: u8 = 25;
#[allow(dead_code)]
const ID_CN: u8 = 26;
#[allow(dead_code)]
const IN: u8 = 27;
#[allow(dead_code)]
const IS: u8 = 28;
#[allow(dead_code)]
const JL: u8 = 29;
#[allow(dead_code)]
const JT: u8 = 30;
#[allow(dead_code)]
const JV: u8 = 31;
#[allow(dead_code)]
const LF: u8 = 32;
#[allow(dead_code)]
const NL: u8 = 33;
#[allow(dead_code)]
const NS: u8 = 34;
#[allow(dead_code)]
const NU: u8 = 35;
#[allow(dead_code)]
const OP_EA: u8 = 36;
#[allow(dead_code)]
const OP_OP30: u8 = 37;
#[allow(dead_code)]
const PO: u8 = 38;
#[allow(dead_code)]
const PO_EAW: u8 = 39;
#[allow(dead_code)]
const PR: u8 = 40;
#[allow(dead_code)]
const PR_EAW: u8 = 41;
#[allow(dead_code)]
const QU: u8 = 42;
#[allow(dead_code)]
const QU_PF: u8 = 43;
#[allow(dead_code)]
const QU_PI: u8 = 44;
#[allow(dead_code)]
const RI: u8 = 45;
#[allow(dead_code)]
const SA: u8 = 46;
#[allow(dead_code)]
const SP: u8 = 47;
#[allow(dead_code)]
const SY: u8 = 48;
#[allow(dead_code)]
const VF: u8 = 49;
#[allow(dead_code)]
const VI: u8 = 50;
#[allow(dead_code)]
const WJ: u8 = 51;
#[allow(dead_code)]
const XX: u8 = 52;
#[allow(dead_code)]
const ZW: u8 = 53;
#[allow(dead_code)]
const ZWJ: u8 = 54;
/// An enum specifies the strictness of line-breaking rules. It can be passed as
/// an argument when creating a line segmenter.
///
/// Each enum value has the same meaning with respect to the `line-break`
/// property values in the CSS Text spec. See the details in
/// <https://drafts.csswg.org/css-text-3/#line-break-property>.
#[non_exhaustive]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum LineBreakStrictness {
/// Breaks text using the least restrictive set of line-breaking rules.
/// Typically used for short lines, such as in newspapers.
/// <https://drafts.csswg.org/css-text-3/#valdef-line-break-loose>
Loose,
/// Breaks text using the most common set of line-breaking rules.
/// <https://drafts.csswg.org/css-text-3/#valdef-line-break-normal>
Normal,
/// Breaks text using the most stringent set of line-breaking rules.
/// <https://drafts.csswg.org/css-text-3/#valdef-line-break-strict>
///
/// This is the default behaviour of the Unicode Line Breaking Algorithm,
/// resolving class [CJ](https://www.unicode.org/reports/tr14/#CJ) to
/// [NS](https://www.unicode.org/reports/tr14/#NS);
/// see rule [LB1](https://www.unicode.org/reports/tr14/#LB1).
#[default]
Strict,
/// Breaks text assuming there is a soft wrap opportunity around every
/// typographic character unit, disregarding any prohibition against line
/// breaks. See more details in
/// <https://drafts.csswg.org/css-text-3/#valdef-line-break-anywhere>.
Anywhere,
}
/// An enum specifies the line break opportunities between letters. It can be
/// passed as an argument when creating a line segmenter.
///
/// Each enum value has the same meaning with respect to the `word-break`
/// property values in the CSS Text spec. See the details in
/// <https://drafts.csswg.org/css-text-3/#word-break-property>
#[non_exhaustive]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum LineBreakWordOption {
/// Words break according to their customary rules. See the details in
/// <https://drafts.csswg.org/css-text-3/#valdef-word-break-normal>.
#[default]
Normal,
/// Breaking is allowed within "words".
/// <https://drafts.csswg.org/css-text-3/#valdef-word-break-break-all>
BreakAll,
/// Breaking is forbidden within "word".
/// <https://drafts.csswg.org/css-text-3/#valdef-word-break-keep-all>
KeepAll,
}
/// Options to tailor line-breaking behavior.
#[non_exhaustive]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub struct LineBreakOptions<'a> {
/// Strictness of line-breaking rules. See [`LineBreakStrictness`].
///
/// Default is [`LineBreakStrictness::Strict`]
pub strictness: Option<LineBreakStrictness>,
/// Line break opportunities between letters. See [`LineBreakWordOption`].
///
/// Default is [`LineBreakStrictness::Normal`]
pub word_option: Option<LineBreakWordOption>,
/// Content locale for line segmenter
///
/// This allows more break opportunities when `LineBreakStrictness` is
/// `Normal` or `Loose`. See
/// <https://drafts.csswg.org/css-text-3/#line-break-property> for details.
/// This option has no effect in Latin-1 mode.
pub content_locale: Option<&'a LanguageIdentifier>,
}
#[derive(Debug)]
struct ResolvedLineBreakOptions {
strictness: LineBreakStrictness,
word_option: LineBreakWordOption,
ja_zh: bool,
}
impl From<LineBreakOptions<'_>> for ResolvedLineBreakOptions {
fn from(options: LineBreakOptions<'_>) -> Self {
let ja_zh = if let Some(content_locale) = options.content_locale.as_ref() {
content_locale.language == language!("ja") || content_locale.language == language!("zh")
} else {
false
};
Self {
strictness: options.strictness.unwrap_or_default(),
word_option: options.word_option.unwrap_or_default(),
ja_zh,
}
}
}
/// Line break iterator for an `str` (a UTF-8 string).
///
/// For examples of use, see [`LineSegmenter`].
pub type LineBreakIteratorUtf8<'l, 's> = LineBreakIterator<'l, 's, LineBreakTypeUtf8>;
/// Line break iterator for a potentially invalid UTF-8 string.
///
/// For examples of use, see [`LineSegmenter`].
pub type LineBreakIteratorPotentiallyIllFormedUtf8<'l, 's> =
LineBreakIterator<'l, 's, LineBreakTypePotentiallyIllFormedUtf8>;
/// Line break iterator for a Latin-1 (8-bit) string.
///
/// For examples of use, see [`LineSegmenter`].
pub type LineBreakIteratorLatin1<'l, 's> = LineBreakIterator<'l, 's, LineBreakTypeLatin1>;
/// Line break iterator for a UTF-16 string.
///
/// For examples of use, see [`LineSegmenter`].
pub type LineBreakIteratorUtf16<'l, 's> = LineBreakIterator<'l, 's, LineBreakTypeUtf16>;
/// Supports loading line break data, and creating line break iterators for different string
/// encodings.
///
/// The segmenter returns mandatory breaks (as defined by [definition LD7][LD7] of
/// Unicode Standard Annex #14, _Unicode Line Breaking Algorithm_) as well as
/// line break opportunities ([definition LD3][LD3]).
/// It does not distinguish them. Callers requiring that distinction can check
/// the Line_Break property of the code point preceding the break against those
/// listed in rules [LB4][LB4] and [LB5][LB5], special-casing the end of text
/// according to [LB3][LB3].
///
/// For consistency with the grapheme, word, and sentence segmenters, there is
/// always a breakpoint returned at index 0, but this breakpoint is not a
/// meaningful line break opportunity.
///
/// [LD3]: https://www.unicode.org/reports/tr14/#LD3
/// [LD7]: https://www.unicode.org/reports/tr14/#LD7
/// [LB3]: https://www.unicode.org/reports/tr14/#LB3
/// [LB4]: https://www.unicode.org/reports/tr14/#LB4
/// [LB5]: https://www.unicode.org/reports/tr14/#LB5
///
/// ```rust
/// # use icu::segmenter::LineSegmenter;
/// #
/// # let segmenter = LineSegmenter::new_auto(Default::default());
/// #
/// let text = "Summary\r\nThis annex…";
/// let breakpoints: Vec<usize> = segmenter.segment_str(text).collect();
/// // 9 and 22 are mandatory breaks, 14 is a line break opportunity.
/// assert_eq!(&breakpoints, &[0, 9, 14, 22]);
///
/// // There is a break opportunity between emoji, but not within the ZWJ sequence 🏳️🌈.
/// let flag_equation = "🏳️➕🌈🟰🏳️\u{200D}🌈";
/// let possible_first_lines: Vec<&str> =
/// segmenter.segment_str(flag_equation).skip(1).map(|i| &flag_equation[..i]).collect();
/// assert_eq!(
/// &possible_first_lines,
/// &[
/// "🏳️",
/// "🏳️➕",
/// "🏳️➕🌈",
/// "🏳️➕🌈🟰",
/// "🏳️➕🌈🟰🏳️🌈"
/// ]
/// );
/// ```
///
/// # Examples
///
/// Segment a string with default options:
///
/// ```rust
/// use icu::segmenter::LineSegmenter;
///
/// let segmenter = LineSegmenter::new_auto(Default::default());
///
/// let breakpoints: Vec<usize> =
/// segmenter.segment_str("Hello World").collect();
/// assert_eq!(&breakpoints, &[0, 6, 11]);
/// ```
///
/// Segment a string with CSS option overrides:
///
/// ```rust
/// use icu::segmenter::options::{
/// LineBreakOptions, LineBreakStrictness, LineBreakWordOption,
/// };
/// use icu::segmenter::LineSegmenter;
///
/// let mut options = LineBreakOptions::default();
/// options.strictness = Some(LineBreakStrictness::Strict);
/// options.word_option = Some(LineBreakWordOption::BreakAll);
/// options.content_locale = None;
/// let segmenter = LineSegmenter::new_auto(options);
///
/// let breakpoints: Vec<usize> =
/// segmenter.segment_str("Hello World").collect();
/// assert_eq!(&breakpoints, &[0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11]);
/// ```
///
/// Segment a Latin1 byte string:
///
/// ```rust
/// use icu::segmenter::LineSegmenter;
///
/// let segmenter = LineSegmenter::new_auto(Default::default());
///
/// let breakpoints: Vec<usize> =
/// segmenter.segment_latin1(b"Hello World").collect();
/// assert_eq!(&breakpoints, &[0, 6, 11]);
/// ```
///
/// Separate mandatory breaks from the break opportunities:
///
/// ```rust
/// use icu::properties::{props::LineBreak, CodePointMapData};
/// use icu::segmenter::LineSegmenter;
///
/// # let segmenter = LineSegmenter::new_auto(Default::default());
/// #
/// let text = "Summary\r\nThis annex…";
///
/// let mandatory_breaks: Vec<usize> = segmenter
/// .segment_str(text)
/// .into_iter()
/// .filter(|&i| {
/// text[..i].chars().next_back().map_or(false, |c| {
/// matches!(
/// CodePointMapData::<LineBreak>::new().get(c),
/// LineBreak::MandatoryBreak
/// | LineBreak::CarriageReturn
/// | LineBreak::LineFeed
/// | LineBreak::NextLine
/// ) || i == text.len()
/// })
/// })
/// .collect();
/// assert_eq!(&mandatory_breaks, &[9, 22]);
/// ```
#[derive(Debug)]
pub struct LineSegmenter {
options: ResolvedLineBreakOptions,
payload: DataPayload<SegmenterBreakLineV1>,
complex: ComplexPayloads,
}
impl LineSegmenter {
/// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
/// the best available compiled data for complex scripts (Khmer, Lao, Myanmar, and Thai).
///
/// The current behavior, which is subject to change, is to use the LSTM model when available.
///
/// See also [`Self::new_auto`].
///
/// ✨ *Enabled with the `compiled_data` and `auto` Cargo features.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
#[cfg(feature = "auto")]
#[cfg(feature = "compiled_data")]
pub fn new_auto(options: LineBreakOptions) -> Self {
Self::new_lstm(options)
}
#[cfg(feature = "auto")]
icu_provider::gen_buffer_data_constructors!(
(options: LineBreakOptions) -> error: DataError,
functions: [
new_auto: skip,
try_new_auto_with_buffer_provider,
try_new_auto_unstable,
Self,
]
);
#[cfg(feature = "auto")]
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_auto)]
pub fn try_new_auto_unstable<D>(
provider: &D,
options: LineBreakOptions,
) -> Result<Self, DataError>
where
D: DataProvider<SegmenterBreakLineV1>
+ DataProvider<SegmenterLstmAutoV1>
+ DataProvider<SegmenterBreakGraphemeClusterV1>
+ ?Sized,
{
Self::try_new_lstm_unstable(provider, options)
}
/// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
/// compiled LSTM data for complex scripts (Khmer, Lao, Myanmar, and Thai).
///
/// The LSTM, or Long Term Short Memory, is a machine learning model. It is smaller than
/// the full dictionary but more expensive during segmentation (inference).
///
/// See also [`Self::new_lstm`].
///
/// ✨ *Enabled with the `compiled_data` and `lstm` Cargo features.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
#[cfg(feature = "lstm")]
#[cfg(feature = "compiled_data")]
pub fn new_lstm(options: LineBreakOptions) -> Self {
Self {
options: options.into(),
payload: DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_SEGMENTER_BREAK_LINE_V1,
),
complex: ComplexPayloads::new_lstm(),
}
}
#[cfg(feature = "lstm")]
icu_provider::gen_buffer_data_constructors!(
(options: LineBreakOptions) -> error: DataError,
functions: [
try_new_lstm: skip,
try_new_lstm_with_buffer_provider,
try_new_lstm_unstable,
Self,
]
);
#[cfg(feature = "lstm")]
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_lstm)]
pub fn try_new_lstm_unstable<D>(
provider: &D,
options: LineBreakOptions,
) -> Result<Self, DataError>
where
D: DataProvider<SegmenterBreakLineV1>
+ DataProvider<SegmenterLstmAutoV1>
+ DataProvider<SegmenterBreakGraphemeClusterV1>
+ ?Sized,
{
Ok(Self {
options: options.into(),
payload: provider.load(Default::default())?.payload,
complex: ComplexPayloads::try_new_lstm(provider)?,
})
}
/// Constructs a [`LineSegmenter`] with an invariant locale, custom [`LineBreakOptions`], and
/// compiled dictionary data for complex scripts (Khmer, Lao, Myanmar, and Thai).
///
/// The dictionary model uses a list of words to determine appropriate breakpoints. It is
/// faster than the LSTM model but requires more data.
///
/// See also [`Self::new_dictionary`].
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
#[cfg(feature = "compiled_data")]
pub fn new_dictionary(options: LineBreakOptions) -> Self {
Self {
options: options.into(),
payload: DataPayload::from_static_ref(
crate::provider::Baked::SINGLETON_SEGMENTER_BREAK_LINE_V1,
),
// Line segmenter doesn't need to load CJ dictionary because UAX 14 rules handles CJK
// characters [1]. Southeast Asian languages however require complex context analysis
// [2].
//
// [1]: https://www.unicode.org/reports/tr14/#ID
// [2]: https://www.unicode.org/reports/tr14/#SA
complex: ComplexPayloads::new_southeast_asian(),
}
}
icu_provider::gen_buffer_data_constructors!(
(options: LineBreakOptions) -> error: DataError,
functions: [
new_dictionary: skip,
try_new_dictionary_with_buffer_provider,
try_new_dictionary_unstable,
Self,
]
);
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_dictionary)]
pub fn try_new_dictionary_unstable<D>(
provider: &D,
options: LineBreakOptions,
) -> Result<Self, DataError>
where
D: DataProvider<SegmenterBreakLineV1>
+ DataProvider<SegmenterDictionaryExtendedV1>
+ DataProvider<SegmenterBreakGraphemeClusterV1>
+ ?Sized,
{
Ok(Self {
options: options.into(),
payload: provider.load(Default::default())?.payload,
// Line segmenter doesn't need to load CJ dictionary because UAX 14 rules handles CJK
// characters [1]. Southeast Asian languages however require complex context analysis
// [2].
//
// [1]: https://www.unicode.org/reports/tr14/#ID
// [2]: https://www.unicode.org/reports/tr14/#SA
complex: ComplexPayloads::try_new_southeast_asian(provider)?,
})
}
/// Creates a line break iterator for an `str` (a UTF-8 string).
///
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
pub fn segment_str<'l, 's>(&'l self, input: &'s str) -> LineBreakIteratorUtf8<'l, 's> {
LineBreakIterator {
iter: input.char_indices(),
len: input.len(),
current_pos_data: None,
result_cache: Vec::new(),
data: self.payload.get(),
options: &self.options,
complex: &self.complex,
}
}
/// Creates a line break iterator for a potentially ill-formed UTF8 string
///
/// Invalid characters are treated as REPLACEMENT CHARACTER
///
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
pub fn segment_utf8<'l, 's>(
&'l self,
input: &'s [u8],
) -> LineBreakIteratorPotentiallyIllFormedUtf8<'l, 's> {
LineBreakIterator {
iter: Utf8CharIndices::new(input),
len: input.len(),
current_pos_data: None,
result_cache: Vec::new(),
data: self.payload.get(),
options: &self.options,
complex: &self.complex,
}
}
/// Creates a line break iterator for a Latin-1 (8-bit) string.
///
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
pub fn segment_latin1<'l, 's>(&'l self, input: &'s [u8]) -> LineBreakIteratorLatin1<'l, 's> {
LineBreakIterator {
iter: Latin1Indices::new(input),
len: input.len(),
current_pos_data: None,
result_cache: Vec::new(),
data: self.payload.get(),
options: &self.options,
complex: &self.complex,
}
}
/// Creates a line break iterator for a UTF-16 string.
///
/// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
pub fn segment_utf16<'l, 's>(&'l self, input: &'s [u16]) -> LineBreakIteratorUtf16<'l, 's> {
LineBreakIterator {
iter: Utf16Indices::new(input),
len: input.len(),
current_pos_data: None,
result_cache: Vec::new(),
data: self.payload.get(),
options: &self.options,
complex: &self.complex,
}
}
}
impl RuleBreakData<'_> {
fn get_linebreak_property_utf32_with_rule(
&self,
codepoint: u32,
strictness: LineBreakStrictness,
word_option: LineBreakWordOption,
) -> u8 {
// Note: Default value is 0 == UNKNOWN
let prop = self.property_table.get32(codepoint);
if word_option == LineBreakWordOption::BreakAll
|| strictness == LineBreakStrictness::Loose
|| strictness == LineBreakStrictness::Normal
{
return match prop {
CJ => ID, // All CJ's General_Category is Other_Letter (Lo).
_ => prop,
};
}
// CJ is treated as NS by default, yielding strict line breaking.
// https://www.unicode.org/reports/tr14/#CJ
prop
}
#[inline]
fn get_break_state_from_table(&self, left: u8, right: u8) -> BreakState {
let idx = (left as usize) * (self.property_count as usize) + (right as usize);
// We use unwrap_or to fall back to the base case and prevent panics on bad data.
self.break_state_table.get(idx).unwrap_or(BreakState::Keep)
}
#[inline]
fn use_complex_breaking_utf32(&self, codepoint: u32) -> bool {
let line_break_property = self.get_linebreak_property_utf32_with_rule(
codepoint,
LineBreakStrictness::Strict,
LineBreakWordOption::Normal,
);
line_break_property == SA
}
}
#[inline]
fn is_break_utf32_by_loose(
right_codepoint: u32,
left_prop: u8,
right_prop: u8,
ja_zh: bool,
) -> Option<bool> {
// breaks before hyphens
if right_prop == BA {
if left_prop == ID && (right_codepoint == 0x2010 || right_codepoint == 0x2013) {
return Some(true);
}
} else if right_prop == NS {
// breaks before certain CJK hyphen-like characters
if right_codepoint == 0x301C || right_codepoint == 0x30A0 {
return Some(ja_zh);
}
// breaks before iteration marks
if right_codepoint == 0x3005
|| right_codepoint == 0x303B
|| right_codepoint == 0x309D
|| right_codepoint == 0x309E
|| right_codepoint == 0x30FD
|| right_codepoint == 0x30FE
{
return Some(true);
}
// breaks before certain centered punctuation marks:
if right_codepoint == 0x30FB
|| right_codepoint == 0xFF1A
|| right_codepoint == 0xFF1B
|| right_codepoint == 0xFF65
|| right_codepoint == 0x203C
|| (0x2047..=0x2049).contains(&right_codepoint)
{
return Some(ja_zh);
}
} else if right_prop == IN {
// breaks between inseparable characters such as U+2025, U+2026 i.e. characters with the Unicode Line Break property IN
return Some(true);
} else if right_prop == EX {
// breaks before certain centered punctuation marks:
if right_codepoint == 0xFF01 || right_codepoint == 0xFF1F {
return Some(ja_zh);
}
}
// breaks before suffixes:
// Characters with the Unicode Line Break property PO and the East Asian Width property
if right_prop == PO_EAW {
return Some(ja_zh);
}
// breaks after prefixes:
// Characters with the Unicode Line Break property PR and the East Asian Width property
if left_prop == PR_EAW {
return Some(ja_zh);
}
None
}
/// A trait allowing for LineBreakIterator to be generalized to multiple string iteration methods.
///
/// This is implemented by ICU4X for several common string types.
///
/// <div class="stab unstable">
/// 🚫 This trait is sealed; it cannot be implemented by user code. If an API requests an item that implements this
/// trait, please consider using a type from the implementors listed below.
/// </div>
pub trait LineBreakType<'l, 's>: crate::private::Sealed {
/// The iterator over characters.
type IterAttr: Iterator<Item = (usize, Self::CharType)> + Clone;
/// The character type.
type CharType: Copy + Into<u32>;
#[doc(hidden)]
fn use_complex_breaking(iterator: &LineBreakIterator<'l, 's, Self>, c: Self::CharType) -> bool;
#[doc(hidden)]
fn get_linebreak_property_with_rule(
iterator: &LineBreakIterator<'l, 's, Self>,
c: Self::CharType,
) -> u8;
#[doc(hidden)]
fn get_current_position_character_len(iterator: &LineBreakIterator<'l, 's, Self>) -> usize;
#[doc(hidden)]
fn handle_complex_language(
iterator: &mut LineBreakIterator<'l, 's, Self>,
left_codepoint: Self::CharType,
) -> Option<usize>;
}
/// Implements the [`Iterator`] trait over the line break opportunities of the given string.
///
/// Lifetimes:
///
/// - `'l` = lifetime of the [`LineSegmenter`] object from which this iterator was created
/// - `'s` = lifetime of the string being segmented
///
/// The [`Iterator::Item`] is an [`usize`] representing index of a code unit
/// _after_ the break (for a break at the end of text, this index is the length
/// of the [`str`] or array of code units).
///
/// For examples of use, see [`LineSegmenter`].
#[derive(Debug)]
pub struct LineBreakIterator<'l, 's, Y: LineBreakType<'l, 's> + ?Sized> {
iter: Y::IterAttr,
len: usize,
current_pos_data: Option<(usize, Y::CharType)>,
result_cache: Vec<usize>,
data: &'l RuleBreakData<'l>,
options: &'l ResolvedLineBreakOptions,
complex: &'l ComplexPayloads,
}
impl<'l, 's, Y: LineBreakType<'l, 's>> Iterator for LineBreakIterator<'l, 's, Y> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
match self.check_eof() {
StringBoundaryPosType::Start => return Some(0),
StringBoundaryPosType::End => return None,
_ => (),
}
// If we have break point cache by previous run, return this result
if let Some(&first_pos) = self.result_cache.first() {
let mut i = 0;
loop {
if i == first_pos {
self.result_cache = self.result_cache.iter().skip(1).map(|r| r - i).collect();
return self.get_current_position();
}
i += Y::get_current_position_character_len(self);
self.advance_iter();
if self.is_eof() {
self.result_cache.clear();
return Some(self.len);
}
}
}
// The state prior to a sequence of CM and ZWJ affected by rule LB9.
let mut lb9_left: Option<u8> = None;
// Whether LB9 was applied to a ZWJ, so that breaks at the current
// position must be suppressed.
let mut lb8a_after_lb9 = false;
'a: loop {
debug_assert!(!self.is_eof());
let left_codepoint = self.get_current_codepoint()?;
let mut left_prop =
lb9_left.unwrap_or_else(|| self.get_linebreak_property(left_codepoint));
let after_zwj = lb8a_after_lb9 || (lb9_left.is_none() && left_prop == ZWJ);
self.advance_iter();
let Some(right_codepoint) = self.get_current_codepoint() else {
return Some(self.len);
};
let right_prop = self.get_linebreak_property(right_codepoint);
// NOTE(egg): The special-casing of `LineBreakStrictness::Anywhere` allows us to pass
// a test, but eventually that option should just be simplified to call the extended
// grapheme cluster segmenter.
if (right_prop == CM
|| (right_prop == ZWJ && self.options.strictness != LineBreakStrictness::Anywhere))
&& left_prop != BK
&& left_prop != CR
&& left_prop != LF
&& left_prop != NL
&& left_prop != SP
&& left_prop != ZW
{
lb9_left = Some(left_prop);
lb8a_after_lb9 = right_prop == ZWJ;
continue;
} else {
lb9_left = None;
lb8a_after_lb9 = false;
}
// CSS word-break property handling
match (self.options.word_option, left_prop, right_prop) {
(LineBreakWordOption::BreakAll, AL | NU | SA, _) => {
left_prop = ID;
}
// typographic letter units shouldn't be break
(
LineBreakWordOption::KeepAll,
AI | AL | ID | NU | HY | H2 | H3 | JL | JV | JT | CJ,
AI | AL | ID | NU | HY | H2 | H3 | JL | JV | JT | CJ,
) => {
continue;
}
_ => (),
}
// CSS line-break property handling
match self.options.strictness {
LineBreakStrictness::Normal => {
if self.is_break_by_normal(right_codepoint) && !after_zwj {
return self.get_current_position();
}
}
LineBreakStrictness::Loose => {
if let Some(breakable) = is_break_utf32_by_loose(
right_codepoint.into(),
left_prop,
right_prop,
self.options.ja_zh,
) {
if breakable && !after_zwj {
return self.get_current_position();
}
continue;
}
}
LineBreakStrictness::Anywhere => {
// TODO(egg): My reading of the CSS standard is that this
// should break around extended grapheme clusters, not at
// arbitrary code points, so this seems wrong.
return self.get_current_position();
}
_ => (),
};
// UAX14 doesn't have Thai etc, so use another way.
if self.options.word_option != LineBreakWordOption::BreakAll
&& Y::use_complex_breaking(self, left_codepoint)
&& Y::use_complex_breaking(self, right_codepoint)
{
let result = Y::handle_complex_language(self, left_codepoint);
if result.is_some() {
return result;
}
// I may have to fetch text until non-SA character?.
}
// If break_state is equals or grater than 0, it is alias of property.
match self.data.get_break_state_from_table(left_prop, right_prop) {
BreakState::Break | BreakState::NoMatch => {
if after_zwj {
continue;
} else {
return self.get_current_position();
}
}
BreakState::Keep => continue,
BreakState::Index(mut index) | BreakState::Intermediate(mut index) => {
let mut previous_iter = self.iter.clone();
let mut previous_pos_data = self.current_pos_data;
let mut previous_is_after_zwj = after_zwj;
// Since we are building up a state in this inner loop, we do not
// need an analogue of lb9_left; continuing the inner loop preserves
// `index` which is the current state, and thus implements the
// “treat as” rule.
let mut left_prop_pre_lb9 = right_prop;
// current state isn't resolved due to intermediating.
// Example, [AK] [AS] is processing LB28a, but if not matched after fetching
// data, we should break after [AK].
let is_intermediate_rule_no_match = if lb8a_after_lb9 {
// left was ZWJ so we don't break between ZWJ.
true
} else {
index > self.data.last_codepoint_property
};
loop {
self.advance_iter();
let after_zwj = left_prop_pre_lb9 == ZWJ;
let previous_break_state_is_cp_prop =
index <= self.data.last_codepoint_property;
let Some(prop) = self.get_current_linebreak_property() else {
// Reached EOF. But we are analyzing multiple characters now, so next break may be previous point.
let break_state = self
.data
.get_break_state_from_table(index, self.data.eot_property);
if break_state == BreakState::NoMatch {
self.iter = previous_iter;
self.current_pos_data = previous_pos_data;
if previous_is_after_zwj {
// Do not break [AK] [ZWJ] ÷ [AS] (eot).
continue 'a;
} else {
return self.get_current_position();
}
}
// EOF
return Some(self.len);
};
if (prop == CM || prop == ZWJ)
&& left_prop_pre_lb9 != BK
&& left_prop_pre_lb9 != CR
&& left_prop_pre_lb9 != LF
&& left_prop_pre_lb9 != NL
&& left_prop_pre_lb9 != SP
&& left_prop_pre_lb9 != ZW
{
left_prop_pre_lb9 = prop;
continue;
}
match self.data.get_break_state_from_table(index, prop) {
BreakState::Keep => continue 'a,
BreakState::NoMatch => {
self.iter = previous_iter;
self.current_pos_data = previous_pos_data;
if after_zwj {
// Break [AK] ÷ [AS] [ZWJ] [XX],
// but not [AK] [ZWJ] ÷ [AS] [ZWJ] [XX].
if is_intermediate_rule_no_match && !previous_is_after_zwj {
return self.get_current_position();
}
continue 'a;
} else if previous_is_after_zwj {
// Do not break [AK] [ZWJ] ÷ [AS] [XX].
continue 'a;
} else {
return self.get_current_position();
}
}
BreakState::Break => {
if after_zwj {
continue 'a;
} else {
return self.get_current_position();
}
}
BreakState::Intermediate(i) => {
index = i;
previous_iter = self.iter.clone();
previous_pos_data = self.current_pos_data;
previous_is_after_zwj = after_zwj;
}
BreakState::Index(i) => {
index = i;
if previous_break_state_is_cp_prop {
previous_iter = self.iter.clone();
previous_pos_data = self.current_pos_data;
previous_is_after_zwj = after_zwj;
}
}
}
left_prop_pre_lb9 = prop;
}
}
}