-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathcomparison.rs
More file actions
2768 lines (2548 loc) · 111 KB
/
comparison.rs
File metadata and controls
2768 lines (2548 loc) · 111 KB
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 ).
// Various collation-related algorithms and constants in this file are
// adapted from ICU4C and, therefore, are subject to the ICU license as
// described in LICENSE.
//! This module holds the `Collator` struct whose `compare_impl()` contains
//! the comparison of collation element sequences.
use alloc::collections::VecDeque;
use alloc::vec::Vec;
use crate::elements::CharacterAndClassAndTrieValue;
use crate::elements::CollationElement32;
use crate::elements::Tag;
use crate::elements::BACKWARD_COMBINING_MARKER;
use crate::elements::CE_BUFFER_SIZE;
use crate::elements::FALLBACK_CE32;
use crate::elements::NON_ROUND_TRIP_MARKER;
use crate::elements::{
char_from_u32, CollationElement, CollationElements, NonPrimary, FFFD_CE32,
HANGUL_SYLLABLE_MARKER, HIGH_ZEROS_MASK, LOW_ZEROS_MASK, NO_CE, NO_CE_PRIMARY,
NO_CE_QUATERNARY, NO_CE_SECONDARY, NO_CE_TERTIARY, OPTIMIZED_DIACRITICS_MAX_COUNT,
QUATERNARY_MASK,
};
use crate::options::CollatorOptionsBitField;
use crate::options::{AlternateHandling, CollatorOptions, ResolvedCollatorOptions, Strength};
use crate::preferences::{CollationCaseFirst, CollationNumericOrdering, CollationType};
use crate::provider::CollationData;
use crate::provider::CollationDiacritics;
use crate::provider::CollationDiacriticsV1;
use crate::provider::CollationJamo;
use crate::provider::CollationJamoV1;
use crate::provider::CollationMetadataV1;
use crate::provider::CollationReordering;
use crate::provider::CollationReorderingV1;
use crate::provider::CollationRootV1;
use crate::provider::CollationSpecialPrimaries;
use crate::provider::CollationSpecialPrimariesV1;
use crate::provider::CollationTailoringV1;
use core::cmp::Ordering;
use core::convert::Infallible;
use icu_normalizer::provider::DecompositionData;
use icu_normalizer::provider::DecompositionTables;
use icu_normalizer::provider::NormalizerNfdDataV1;
use icu_normalizer::provider::NormalizerNfdTablesV1;
use icu_normalizer::DecomposingNormalizerBorrowed;
use icu_normalizer::Decomposition;
use icu_provider::prelude::*;
use smallvec::SmallVec;
use utf16_iter::Utf16CharsEx;
use utf8_iter::Utf8CharsEx;
// Special sort key bytes for all levels.
const LEVEL_SEPARATOR_BYTE: u8 = 1;
/// Merge-sort-key separator.
///
/// Same as the unique primary and identical-level weights of U+FFFE. Must not
/// be used as primary compression low terminator. Otherwise usable.
const MERGE_SEPARATOR: char = '\u{fffe}';
const MERGE_SEPARATOR_BYTE: u8 = 2;
const MERGE_SEPARATOR_PRIMARY: u32 = 0x02000000;
/// Primary compression low terminator, must be greater than [`MERGE_SEPARATOR_BYTE`].
///
/// Reserved value in primary second byte if the lead byte is compressible.
/// Otherwise usable in all CE weight bytes.
const PRIMARY_COMPRESSION_LOW_BYTE: u8 = 3;
/// Primary compression high terminator.
///
/// Reserved value in primary second byte if the lead byte is compressible.
/// Otherwise usable in all CE weight bytes.
const PRIMARY_COMPRESSION_HIGH_BYTE: u8 = 0xff;
/// Default secondary/tertiary weight lead byte.
const COMMON_BYTE: u8 = 5;
const COMMON_WEIGHT16: u16 = 0x0500;
// Internal flags for sort key generation
const PRIMARY_LEVEL_FLAG: u8 = 0x01;
const SECONDARY_LEVEL_FLAG: u8 = 0x02;
const CASE_LEVEL_FLAG: u8 = 0x04;
const TERTIARY_LEVEL_FLAG: u8 = 0x08;
const QUATERNARY_LEVEL_FLAG: u8 = 0x10;
const LEVEL_MASKS: [u8; Strength::Identical as usize + 1] = [
PRIMARY_LEVEL_FLAG,
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG,
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG | TERTIARY_LEVEL_FLAG,
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG | TERTIARY_LEVEL_FLAG | QUATERNARY_LEVEL_FLAG,
0,
0,
0,
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG | TERTIARY_LEVEL_FLAG | QUATERNARY_LEVEL_FLAG,
];
// Internal constants for indexing into the below compression configurations
const WEIGHT_LOW: usize = 0;
const WEIGHT_MIDDLE: usize = 1;
const WEIGHT_HIGH: usize = 2;
const WEIGHT_MAX_COUNT: usize = 3;
// Secondary level: Compress up to 33 common weights as 05..25 or 25..45.
const SEC_COMMON: [u8; 4] = [COMMON_BYTE, COMMON_BYTE + 0x20, COMMON_BYTE + 0x40, 0x21];
// Case level, lowerFirst: Compress up to 7 common weights as 1..7 or 7..13.
const CASE_LOWER_FIRST_COMMON: [u8; 4] = [1, 7, 13, 7];
// Case level, upperFirst: Compress up to 13 common weights as 3..15.
const CASE_UPPER_FIRST_COMMON: [u8; 4] = [3, 0 /* unused */, 15, 13];
// Tertiary level only (no case): Compress up to 97 common weights as 05..65 or 65..C5.
const TER_ONLY_COMMON: [u8; 4] = [COMMON_BYTE, COMMON_BYTE + 0x60, COMMON_BYTE + 0xc0, 0x61];
// Tertiary with case, lowerFirst: Compress up to 33 common weights as 05..25 or 25..45.
const TER_LOWER_FIRST_COMMON: [u8; 4] = [COMMON_BYTE, COMMON_BYTE + 0x20, COMMON_BYTE + 0x40, 0x21];
// Tertiary with case, upperFirst: Compress up to 33 common weights as 85..A5 or A5..C5.
const TER_UPPER_FIRST_COMMON: [u8; 4] = [
COMMON_BYTE + 0x80,
COMMON_BYTE + 0x80 + 0x20,
COMMON_BYTE + 0x80 + 0x40,
0x21,
];
const QUAT_COMMON: [u8; 4] = [0x1c, 0x1c + 0x70, 0x1c + 0xe0, 0x71];
const QUAT_SHIFTED_LIMIT_BYTE: u8 = QUAT_COMMON[WEIGHT_LOW] - 1; // 0x1b
// Do not use byte values 0, 1, 2 because they are separators in sort keys.
const SLOPE_MIN: i32 = 3;
const SLOPE_MAX: i32 = 0xff;
const SLOPE_MIDDLE: i32 = 0x81;
const SLOPE_TAIL_COUNT: i32 = SLOPE_MAX - SLOPE_MIN + 1;
const SLOPE_SINGLE: i32 = 80;
const SLOPE_LEAD_2: i32 = 42;
const SLOPE_LEAD_3: i32 = 3;
// The difference value range for single-byters.
const SLOPE_REACH_POS_1: i32 = SLOPE_SINGLE;
const SLOPE_REACH_NEG_1: i32 = -SLOPE_SINGLE;
// The difference value range for double-byters.
const SLOPE_REACH_POS_2: i32 = SLOPE_LEAD_2 * SLOPE_TAIL_COUNT + (SLOPE_LEAD_2 - 1);
const SLOPE_REACH_NEG_2: i32 = -SLOPE_REACH_POS_2 - 1;
// The difference value range for 3-byters.
const SLOPE_REACH_POS_3: i32 = SLOPE_LEAD_3 * SLOPE_TAIL_COUNT * SLOPE_TAIL_COUNT
+ (SLOPE_LEAD_3 - 1) * SLOPE_TAIL_COUNT
+ (SLOPE_TAIL_COUNT - 1);
const SLOPE_REACH_NEG_3: i32 = -SLOPE_REACH_POS_3 - 1;
// The lead byte start values.
const SLOPE_START_POS_2: i32 = SLOPE_MIDDLE + SLOPE_SINGLE + 1;
const SLOPE_START_POS_3: i32 = SLOPE_START_POS_2 + SLOPE_LEAD_2;
const SLOPE_START_NEG_2: i32 = SLOPE_MIDDLE + SLOPE_REACH_NEG_1;
const SLOPE_START_NEG_3: i32 = SLOPE_START_NEG_2 - SLOPE_LEAD_2;
struct AnyQuaternaryAccumulator(u32);
impl AnyQuaternaryAccumulator {
#[inline(always)]
pub fn new() -> Self {
AnyQuaternaryAccumulator(0)
}
#[inline(always)]
pub fn accumulate(&mut self, non_primary: NonPrimary) {
self.0 |= non_primary.bits()
}
#[inline(always)]
pub fn has_quaternary(&self) -> bool {
self.0 & u32::from(QUATERNARY_MASK) != 0
}
}
/// `true` iff `i` is greater or equal to `start` and less or equal
/// to `end`.
#[inline(always)]
fn in_inclusive_range16(i: u16, start: u16, end: u16) -> bool {
i.wrapping_sub(start) <= (end - start)
}
/// Helper trait for getting a `char` iterator from Latin1 data.
///
/// ✨ *Enabled with the `latin1` Cargo feature.*
#[cfg(feature = "latin1")]
trait Latin1Chars {
fn latin1_chars(&self) -> impl DoubleEndedIterator<Item = char>;
}
#[cfg(feature = "latin1")]
impl Latin1Chars for [u8] {
fn latin1_chars(&self) -> impl DoubleEndedIterator<Item = char> {
self.iter().map(|b| char::from(*b))
}
}
/// Finds the identical prefix of `left` and `right` containing
/// Latin1.
///
/// Returns the identical prefix, the part of `left` after the
/// prefix, and the part of `right` after the prefix.
///
/// ✨ *Enabled with the `latin1` Cargo feature.*
#[cfg(feature = "latin1")]
fn split_prefix_latin1<'a, 'b>(left: &'a [u8], right: &'b [u8]) -> (&'a [u8], &'a [u8], &'b [u8]) {
let i = left
.iter()
.zip(right.iter())
.take_while(|(l, r)| l == r)
.count();
if let Some((head, left_tail)) = left.split_at_checked(i) {
if let Some(right_tail) = right.get(i..) {
return (head, left_tail, right_tail);
}
}
(&[], left, right)
}
/// Finds the identical prefix of `left` containing Latin1
/// and `right` containing potentially ill-formed UTF-16.
///
/// Returns the identical prefix, the part of `left` after the
/// prefix, and the part of `right` after the prefix.
///
/// ✨ *Enabled with the `latin1` Cargo feature.*
#[cfg(feature = "latin1")]
fn split_prefix_latin1_utf16<'a, 'b>(
left: &'a [u8],
right: &'b [u16],
) -> (&'a [u8], &'a [u8], &'b [u16]) {
let i = left
.iter()
.zip(right.iter())
.take_while(|(l, r)| u16::from(**l) == **r)
.count();
if let Some((head, left_tail)) = left.split_at_checked(i) {
if let Some(right_tail) = right.get(i..) {
return (head, left_tail, right_tail);
}
}
(&[], left, right)
}
/// Finds the identical prefix of `left` and `right` containing
/// potentially ill-formed UTF-16, while avoiding splitting a
/// well-formed surrogate pair. In case of ill-formed
/// UTF-16, the prefix is not guaranteed to be maximal.
///
/// Returns the identical prefix, the part of `left` after the
/// prefix, and the part of `right` after the prefix.
fn split_prefix_u16<'a, 'b>(
left: &'a [u16],
right: &'b [u16],
) -> (&'a [u16], &'a [u16], &'b [u16]) {
let mut i = left
.iter()
.zip(right.iter())
.take_while(|(l, r)| l == r)
.count();
if i != 0 {
if let Some(&last) = left.get(i.wrapping_sub(1)) {
if in_inclusive_range16(last, 0xD800, 0xDBFF) {
i -= 1;
}
if let Some((head, left_tail)) = left.split_at_checked(i) {
if let Some(right_tail) = right.get(i..) {
return (head, left_tail, right_tail);
}
}
}
}
(&[], left, right)
}
/// Finds the identical prefix of `left` and `right` containing
/// potentially ill-formed UTF-8, while avoiding splitting a UTF-8
/// byte sequence. In case of ill-formed UTF-8, the prefix is
/// not guaranteed to be maximal.
///
/// Returns the identical prefix, the part of `left` after the
/// prefix, and the part of `right` after the prefix.
fn split_prefix_u8<'a, 'b>(left: &'a [u8], right: &'b [u8]) -> (&'a [u8], &'a [u8], &'b [u8]) {
let mut i = left
.iter()
.zip(right.iter())
.take_while(|(l, r)| l == r)
.count();
if i != 0 {
// Tails must not start with a UTF-8 continuation
// byte unless it's the first byte of the original
// slice.
// First, left and right differ, but since they
// are the same afterwards, one of them needs checking
// only once.
if let Some(right_first) = right.get(i) {
if (right_first & 0b1100_0000) == 0b1000_0000 {
i -= 1;
}
}
while i != 0 {
if let Some(left_first) = left.get(i) {
if (left_first & 0b1100_0000) == 0b1000_0000 {
i -= 1;
continue;
}
}
break;
}
if let Some((head, left_tail)) = left.split_at_checked(i) {
if let Some(right_tail) = right.get(i..) {
return (head, left_tail, right_tail);
}
}
}
(&[], left, right)
}
/// Finds the identical prefix of `left` and `right` containing
/// guaranteed well-format UTF-8.
///
/// Returns the identical prefix, the part of `left` after the
/// prefix, and the part of `right` after the prefix.
fn split_prefix<'a, 'b>(left: &'a str, right: &'b str) -> (&'a str, &'a str, &'b str) {
let left_bytes = left.as_bytes();
let right_bytes = right.as_bytes();
let mut i = left_bytes
.iter()
.zip(right_bytes.iter())
.take_while(|(l, r)| l == r)
.count();
if i != 0 {
// Tails must not start with a UTF-8 continuation
// byte.
// Since the inputs are valid UTF-8, the first byte
// of either input slice cannot be a contination slice,
// so we may rely on finding a lead byte when walking
// backwards.
// Since the inputs are valid UTF-8, if a tail starts
// with a continuation, both tails must start with a
// continuation, since the most recent lead byte must
// be equal, so the difference is within valid UTF-8
// sequences of equal length.
// Therefore, it's sufficient to examine only one of
// the sides.
loop {
if let Some(left_first) = left_bytes.get(i) {
if (left_first & 0b1100_0000) == 0b1000_0000 {
i -= 1;
continue;
}
}
break;
}
// The methods below perform useless UTF-8 boundary checks,
// since we just checked. However, avoiding `unsafe` to
// make this code easier to audit.
if let Some((head, left_tail)) = left.split_at_checked(i) {
if let Some(right_tail) = right.get(i..) {
return (head, left_tail, right_tail);
}
}
}
("", left, right)
}
/// Holder struct for payloads that are locale-dependent. (For code
/// reuse between owned and borrowed cases.)
#[derive(Debug)]
struct LocaleSpecificDataHolder {
tailoring: Option<DataPayload<CollationTailoringV1>>,
diacritics: DataPayload<CollationDiacriticsV1>,
reordering: Option<DataPayload<CollationReorderingV1>>,
merged_options: CollatorOptionsBitField,
lithuanian_dot_above: bool,
}
icu_locale_core::preferences::define_preferences!(
/// The preferences for collation.
///
/// # Preferences
///
/// Examples for using the different preferences below can be found in the [crate-level docs](crate).
///
/// ## Case First
///
/// See the [spec](https://www.unicode.org/reports/tr35/tr35-collation.html#Case_Parameters).
/// This is the BCP47 key `kf`. Three possibilities: [`CollationCaseFirst::False`] (default,
/// except for Danish and Maltese), [`CollationCaseFirst::Lower`], and [`CollationCaseFirst::Upper`]
/// (default for Danish and Maltese).
///
/// ## Numeric
///
/// This is the BCP47 key `kn`. When set to [`CollationNumericOrdering::True`], any sequence of decimal
/// digits (General_Category = Nd) is sorted at the primary level according to the
/// numeric value. The default is [`CollationNumericOrdering::False`].
[Copy]
CollatorPreferences,
{
/// The collation type. This corresponds to the `-u-co` BCP-47 tag.
collation_type: CollationType,
/// Treatment of case. (Large and small kana differences are treated as case differences.)
/// This corresponds to the `-u-kf` BCP-47 tag.
case_first: CollationCaseFirst,
/// When set to `True`, any sequence of decimal digits is sorted at a primary level according
/// to the numeric value.
/// This corresponds to the `-u-kn` BPC-47 tag.
numeric_ordering: CollationNumericOrdering
}
);
impl LocaleSpecificDataHolder {
/// The constructor code reused between owned and borrowed cases.
fn try_new_unstable_internal<D>(
provider: &D,
prefs: CollatorPreferences,
options: CollatorOptions,
) -> Result<Self, DataError>
where
D: DataProvider<CollationTailoringV1>
+ DataProvider<CollationDiacriticsV1>
+ DataProvider<CollationMetadataV1>
+ DataProvider<CollationReorderingV1>
+ ?Sized,
{
let marker_attributes = prefs
.collation_type
.as_ref()
// all collation types are valid marker attributes
.map(|c| DataMarkerAttributes::from_str_or_panic(c.as_str()))
.unwrap_or_default();
let data_locale = CollationTailoringV1::make_locale(prefs.locale_preferences);
let req = DataRequest {
id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
marker_attributes,
&data_locale,
),
metadata: {
let mut metadata = DataRequestMetadata::default();
metadata.silent = true;
metadata
},
};
let fallback_req = DataRequest {
id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
Default::default(),
&data_locale,
),
..Default::default()
};
let metadata_payload: DataPayload<CollationMetadataV1> = provider
.load(req)
.or_else(|_| provider.load(fallback_req))?
.payload;
let metadata = metadata_payload.get();
let tailoring: Option<DataPayload<CollationTailoringV1>> = if metadata.tailored() {
Some(
provider
.load(req)
.or_else(|_| provider.load(fallback_req))?
.payload,
)
} else {
None
};
let reordering: Option<DataPayload<CollationReorderingV1>> = if metadata.reordering() {
Some(
provider
.load(req)
.or_else(|_| provider.load(fallback_req))?
.payload,
)
} else {
None
};
if let Some(reordering) = &reordering {
if reordering.get().reorder_table.len() != 256 {
return Err(DataError::custom("invalid").with_marker(CollationReorderingV1::INFO));
}
}
let tailored_diacritics = metadata.tailored_diacritics();
let diacritics: DataPayload<CollationDiacriticsV1> = provider
.load(if tailored_diacritics {
req
} else {
Default::default()
})?
.payload;
if tailored_diacritics {
// In the tailored case we accept a shorter table in which case the tailoring is
// responsible for supplying the missing values in the trie.
// As of June 2022, none of the collations actually use a shortened table.
// Vietnamese and Ewe load a full-length alternative table and the rest use
// the default one.
if diacritics.get().secondaries.len() > OPTIMIZED_DIACRITICS_MAX_COUNT {
return Err(DataError::custom("invalid").with_marker(CollationDiacriticsV1::INFO));
}
} else if diacritics.get().secondaries.len() != OPTIMIZED_DIACRITICS_MAX_COUNT {
return Err(DataError::custom("invalid").with_marker(CollationDiacriticsV1::INFO));
}
let mut altered_defaults = CollatorOptionsBitField::default();
if metadata.alternate_shifted() {
altered_defaults.set_alternate_handling(Some(AlternateHandling::Shifted));
}
if metadata.backward_second_level() {
altered_defaults.set_backward_second_level(Some(true));
}
altered_defaults.set_case_first(Some(metadata.case_first()));
altered_defaults.set_max_variable(Some(metadata.max_variable()));
let mut merged_options = CollatorOptionsBitField::from(options);
merged_options.set_case_first(prefs.case_first);
merged_options.set_numeric_from_enum(prefs.numeric_ordering);
merged_options.set_defaults(altered_defaults);
Ok(LocaleSpecificDataHolder {
tailoring,
diacritics,
merged_options,
reordering,
lithuanian_dot_above: metadata.lithuanian_dot_above(),
})
}
}
/// Compares strings according to culturally-relevant ordering.
#[derive(Debug)]
pub struct Collator {
special_primaries: DataPayload<CollationSpecialPrimariesV1>,
root: DataPayload<CollationRootV1>,
tailoring: Option<DataPayload<CollationTailoringV1>>,
jamo: DataPayload<CollationJamoV1>,
diacritics: DataPayload<CollationDiacriticsV1>,
options: CollatorOptionsBitField,
reordering: Option<DataPayload<CollationReorderingV1>>,
decompositions: DataPayload<NormalizerNfdDataV1>,
tables: DataPayload<NormalizerNfdTablesV1>,
lithuanian_dot_above: bool,
}
impl Collator {
/// Constructs a borrowed version of this type for more efficient querying.
pub fn as_borrowed(&self) -> CollatorBorrowed<'_> {
CollatorBorrowed {
special_primaries: self.special_primaries.get(),
root: self.root.get(),
tailoring: self.tailoring.as_ref().map(|s| s.get()),
jamo: self.jamo.get(),
diacritics: self.diacritics.get(),
options: self.options,
reordering: self.reordering.as_ref().map(|s| s.get()),
decompositions: self.decompositions.get(),
tables: self.tables.get(),
lithuanian_dot_above: self.lithuanian_dot_above,
}
}
/// Creates `CollatorBorrowed` for the given locale and options from compiled data.
#[cfg(feature = "compiled_data")]
pub fn try_new(
prefs: CollatorPreferences,
options: CollatorOptions,
) -> Result<CollatorBorrowed<'static>, DataError> {
CollatorBorrowed::try_new(prefs, options)
}
icu_provider::gen_buffer_data_constructors!(
(prefs: CollatorPreferences, options: CollatorOptions) -> error: DataError,
functions: [
try_new: skip,
try_new_with_buffer_provider,
try_new_unstable,
Self
]
);
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
pub fn try_new_unstable<D>(
provider: &D,
prefs: CollatorPreferences,
options: CollatorOptions,
) -> Result<Self, DataError>
where
D: DataProvider<CollationSpecialPrimariesV1>
+ DataProvider<CollationRootV1>
+ DataProvider<CollationTailoringV1>
+ DataProvider<CollationDiacriticsV1>
+ DataProvider<CollationJamoV1>
+ DataProvider<CollationMetadataV1>
+ DataProvider<CollationReorderingV1>
+ DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ ?Sized,
{
Self::try_new_unstable_internal(
provider,
provider.load(Default::default())?.payload,
provider.load(Default::default())?.payload,
provider.load(Default::default())?.payload,
provider.load(Default::default())?.payload,
provider.load(Default::default())?.payload,
prefs,
options,
)
}
#[expect(clippy::too_many_arguments)]
fn try_new_unstable_internal<D>(
provider: &D,
root: DataPayload<CollationRootV1>,
decompositions: DataPayload<NormalizerNfdDataV1>,
tables: DataPayload<NormalizerNfdTablesV1>,
jamo: DataPayload<CollationJamoV1>,
special_primaries: DataPayload<CollationSpecialPrimariesV1>,
prefs: CollatorPreferences,
options: CollatorOptions,
) -> Result<Self, DataError>
where
D: DataProvider<CollationRootV1>
+ DataProvider<CollationTailoringV1>
+ DataProvider<CollationDiacriticsV1>
+ DataProvider<CollationMetadataV1>
+ DataProvider<CollationReorderingV1>
+ ?Sized,
{
let locale_dependent =
LocaleSpecificDataHolder::try_new_unstable_internal(provider, prefs, options)?;
Ok(Collator {
special_primaries,
root,
tailoring: locale_dependent.tailoring,
jamo,
diacritics: locale_dependent.diacritics,
options: locale_dependent.merged_options,
reordering: locale_dependent.reordering,
decompositions,
tables,
lithuanian_dot_above: locale_dependent.lithuanian_dot_above,
})
}
}
macro_rules! compare {
($(#[$meta:meta])*,
$compare:ident,
$left_slice:ty,
$right_slice:ty,
$split_prefix:ident,
$left_to_iter:ident,
$right_to_iter:ident,
) => {
$(#[$meta])*
pub fn $compare(&self, left: &$left_slice, right: &$right_slice) -> Ordering {
let (head, left_tail, right_tail) = $split_prefix(left, right);
if left_tail.is_empty() && right_tail.is_empty() {
return Ordering::Equal;
}
let ret = self.compare_impl(left_tail.$left_to_iter(), right_tail.$right_to_iter(), head.$left_to_iter().rev());
if self.options.strength() == Strength::Identical && ret == Ordering::Equal {
return Decomposition::new(left_tail.$left_to_iter(), self.decompositions, self.tables).map(|c| if c != MERGE_SEPARATOR { c as i32 } else { -1i32 }).cmp(
Decomposition::new(right_tail.$right_to_iter(), self.decompositions, self.tables).map(|c| if c != MERGE_SEPARATOR { c as i32 } else { -1i32 }),
);
}
ret
}
}
}
/// Compares strings according to culturally-relevant ordering,
/// borrowed version.
#[derive(Debug)]
pub struct CollatorBorrowed<'a> {
special_primaries: &'a CollationSpecialPrimaries<'a>,
root: &'a CollationData<'a>,
tailoring: Option<&'a CollationData<'a>>,
jamo: &'a CollationJamo<'a>,
diacritics: &'a CollationDiacritics<'a>,
options: CollatorOptionsBitField,
reordering: Option<&'a CollationReordering<'a>>,
decompositions: &'a DecompositionData<'a>,
tables: &'a DecompositionTables<'a>,
lithuanian_dot_above: bool,
}
impl CollatorBorrowed<'static> {
/// Creates a collator for the given locale and options from compiled data.
#[cfg(feature = "compiled_data")]
pub fn try_new(
prefs: CollatorPreferences,
options: CollatorOptions,
) -> Result<Self, DataError> {
// These are assigned to locals in order to keep the code after these assignments
// copypaste-compatible with `Collator::try_new_unstable_internal`.
let provider = &crate::provider::Baked;
let decompositions = icu_normalizer::provider::Baked::SINGLETON_NORMALIZER_NFD_DATA_V1;
let tables = icu_normalizer::provider::Baked::SINGLETON_NORMALIZER_NFD_TABLES_V1;
let root = crate::provider::Baked::SINGLETON_COLLATION_ROOT_V1;
let jamo = crate::provider::Baked::SINGLETON_COLLATION_JAMO_V1;
let locale_dependent =
LocaleSpecificDataHolder::try_new_unstable_internal(provider, prefs, options)?;
let special_primaries = crate::provider::Baked::SINGLETON_COLLATION_SPECIAL_PRIMARIES_V1;
// Attribute belongs closer to `unwrap`, but
// https://github.com/rust-lang/rust/issues/15701
#[expect(clippy::unwrap_used)]
Ok(CollatorBorrowed {
special_primaries,
root,
// Unwrap is OK, because we know we have the baked provider.
tailoring: locale_dependent.tailoring.map(|s| s.get_static().unwrap()),
jamo,
// Unwrap is OK, because we know we have the baked provider.
diacritics: locale_dependent.diacritics.get_static().unwrap(),
options: locale_dependent.merged_options,
// Unwrap is OK, because we know we have the baked provider.
reordering: locale_dependent.reordering.map(|s| s.get_static().unwrap()),
decompositions,
tables,
lithuanian_dot_above: locale_dependent.lithuanian_dot_above,
})
}
/// Cheaply converts a [`CollatorBorrowed<'static>`] into a [`Collator`].
///
/// Note: Due to branching and indirection, using [`Collator`] might inhibit some
/// compile-time optimizations that are possible with [`CollatorBorrowed`].
pub const fn static_to_owned(self) -> Collator {
Collator {
special_primaries: DataPayload::from_static_ref(self.special_primaries),
root: DataPayload::from_static_ref(self.root),
tailoring: if let Some(s) = self.tailoring {
// `map` not available in const context
Some(DataPayload::from_static_ref(s))
} else {
None
},
jamo: DataPayload::from_static_ref(self.jamo),
diacritics: DataPayload::from_static_ref(self.diacritics),
options: self.options,
reordering: if let Some(s) = self.reordering {
// `map` not available in const context
Some(DataPayload::from_static_ref(s))
} else {
None
},
decompositions: DataPayload::from_static_ref(self.decompositions),
tables: DataPayload::from_static_ref(self.tables),
lithuanian_dot_above: self.lithuanian_dot_above,
}
}
}
impl<'a> CollatorBorrowed<'a> {
/// The resolved options showing how the default options, the requested options,
/// and the options from locale data were combined.
pub fn resolved_options(&self) -> ResolvedCollatorOptions {
self.options.into()
}
compare!(
/// Compare guaranteed well-formed UTF-8 slices.
,
compare,
str,
str,
split_prefix,
chars,
chars,
);
compare!(
/// Compare potentially ill-formed UTF-8 slices. Ill-formed input is compared
/// as if errors had been replaced with REPLACEMENT CHARACTERs according
/// to the WHATWG Encoding Standard.
,
compare_utf8,
[u8],
[u8],
split_prefix_u8,
chars,
chars,
);
compare!(
/// Compare potentially ill-formed UTF-16 slices. Unpaired surrogates
/// are compared as if each one was a REPLACEMENT CHARACTER.
,
compare_utf16,
[u16],
[u16],
split_prefix_u16,
chars,
chars,
);
compare!(
/// Compare Latin1 slices.
///
/// ✨ *Enabled with the `latin1` Cargo feature.*
#[cfg(feature = "latin1")]
,
compare_latin1,
[u8],
[u8],
split_prefix_latin1,
latin1_chars,
latin1_chars,
);
compare!(
/// Compare Latin1 slice with potentially ill-formed UTF-16
/// slice.
///
/// If you need to compare a potentially ill-formed UTF-16
/// slice with a Latin1 slice, swap the arguments and
/// call `reverse()` on the return value.
///
/// ✨ *Enabled with the `latin1` Cargo feature.*
#[cfg(feature = "latin1")]
,
compare_latin1_utf16,
[u8],
[u16],
split_prefix_latin1_utf16,
latin1_chars,
chars,
);
#[inline(always)]
fn tailoring_or_root(&self) -> &'a CollationData<'a> {
if let Some(tailoring) = &self.tailoring {
tailoring
} else {
// If the root collation is valid for the locale,
// use the root as the tailoring so that reads from the
// tailoring always succeed.
//
// TODO(#2011): Do we instead want to have an untailored
// copypaste of the iterator that omits the tailoring
// branches for performance at the expense of code size
// and having to maintain both a tailoring-capable and
// a tailoring-incapable version of the iterator?
// Or, in order not to flip the branch prediction around,
// should we have a no-op tailoring that contains a
// specially-crafted CodePointTrie that always returns
// a FALLBACK_CE32 after a single branch?
self.root
}
}
#[inline(always)]
fn numeric_primary(&self) -> Option<u8> {
if self.options.numeric() {
Some(self.special_primaries.numeric_primary)
} else {
None
}
}
#[inline(always)]
fn variable_top(&self) -> u32 {
if self.options.alternate_handling() == AlternateHandling::NonIgnorable {
0
} else {
// +1 so that we can use "<" and primary ignorables test out early.
self.special_primaries
.last_primary_for_group(self.options.max_variable())
+ 1
}
}
/// The implementation of the comparison operation.
///
/// `head_chars` is an iterator _backward_ over the identical
/// prefix and `left_chars` and `right_chars` are iterators
/// _forward_ over the parts after the identical prefix.
fn compare_impl<
L: Iterator<Item = char>,
R: Iterator<Item = char>,
H: Iterator<Item = char>,
>(
&self,
left_chars: L,
right_chars: R,
mut head_chars: H,
) -> Ordering {
// Sadly, it looks like variable CEs and backward second level
// require us to store the full 64-bit CEs instead of storing only
// the NonPrimary part.
//
// TODO(#2008): Consider having two monomorphizations of this method:
// one that can deal with variables shifted to quaternary and
// backward second level and another that doesn't support that
// and only stores `NonPrimary` in `left_ces` and `right_ces`
// with double the number of stack allocated elements.
// Note: These are used only after the identical prefix skipping,
// but initializing these up here improves performance at the time
// of writing. Presumably the source order affects the stack frame
// layout.
let mut left_ces: SmallVec<[CollationElement; CE_BUFFER_SIZE]> = SmallVec::new();
let mut right_ces: SmallVec<[CollationElement; CE_BUFFER_SIZE]> = SmallVec::new();
// The algorithm comes from CollationCompare::compareUpToQuaternary in ICU4C.
let mut any_variable = false;
let variable_top = self.variable_top();
let tailoring = self.tailoring_or_root();
let numeric_primary = self.numeric_primary();
let jamo = self.jamo.as_array();
let mut left = CollationElements::new(
left_chars,
self.root,
tailoring,
jamo,
&self.diacritics.secondaries,
self.decompositions,
self.tables,
numeric_primary,
self.lithuanian_dot_above,
);
let mut right = CollationElements::new(
right_chars,
self.root,
tailoring,
self.jamo.as_array(),
&self.diacritics.secondaries,
self.decompositions,
self.tables,
numeric_primary,
self.lithuanian_dot_above,
);
// Start identical prefix
// The logic here to check whether the boundary found by skipping
// the identical prefix is safe is complicated compared to the ICU4C
// approach of having a set of characters that are unsafe as the character
// immediately following the identical prefix. However, the approach here
// avoids extra data, and working on the main data avoids the bug
// possibility of data structures not being mutually consistent.
// This code intentionally does not keep around the `CollationElement32`s
// that have been read from the collation data tries, because keeping
// them around turned out to be a pessimization: There would be added
// branches on the hot path of the algorithm that maps characters to
// collation elements, and the element size of the upcoming buffer
// would grow.
//
// However, the values read from the normalization trie _are_ kept around,
// since there is already a place where to put them.
// This loop is only broken out of as goto forward.
#[expect(clippy::never_loop)]
'prefix: loop {
if let Some(mut head_last_c) = head_chars.next() {
let norm_trie = &self.decompositions.trie;
let mut head_last = CharacterAndClassAndTrieValue::new_with_trie_val(
head_last_c,
norm_trie.get(head_last_c),
);
let mut head_last_ce32 = CollationElement32::default();
let mut head_last_ok = false;
if let Some(left_different) = left.iter_next_before_init() {
left.prepend_upcoming_before_init(left_different.clone());
if let Some(right_different) = right.iter_next_before_init() {
// Note: left_different and right_different may both be U+FFFD.
right.prepend_upcoming_before_init(right_different.clone());
// The base logic is that a boundary between two starters
// that decompose to selves is safe iff the starter
// before the boundary can't contract a starter, the
// starter after the boundary doesn't have a prefix
// condition, and, with the numeric mode enabled,
// they aren't both numeric.
//
// This base logic is then extended with Hangul