| 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 |
// Various collation-related algorithms and constants in this file are |
| 6 |
// adapted from ICU4C and, therefore, are subject to the ICU license as |
| 7 |
// described in LICENSE. |
| 8 |
|
| 9 |
//! This module holds the `Collator` struct whose `compare_impl()` contains |
| 10 |
//! the comparison of collation element sequences. |
| 11 |
|
| 12 |
use alloc::collections::VecDeque; |
| 13 |
use alloc::vec::Vec; |
| 14 |
|
| 15 |
use crate::elements::BACKWARD_COMBINING_MARKER; |
| 16 |
use crate::elements::CE_BUFFER_SIZE; |
| 17 |
use crate::elements::CharacterAndClassAndTrieValue; |
| 18 |
use crate::elements::CollationElement32; |
| 19 |
use crate::elements::FALLBACK_CE32; |
| 20 |
use crate::elements::NON_ROUND_TRIP_MARKER; |
| 21 |
use crate::elements::Tag; |
| 22 |
use crate::elements::{ |
| 23 |
CollationElement, CollationElements, FFFD_CE32, HANGUL_SYLLABLE_MARKER, HIGH_ZEROS_MASK, |
| 24 |
LOW_ZEROS_MASK, NO_CE, NO_CE_PRIMARY, NO_CE_QUATERNARY, NO_CE_SECONDARY, NO_CE_TERTIARY, |
| 25 |
NonPrimary, OPTIMIZED_DIACRITICS_MAX_COUNT, QUATERNARY_MASK, char_from_u32, |
| 26 |
}; |
| 27 |
use crate::options::CollatorOptionsBitField; |
| 28 |
use crate::options::{AlternateHandling, CollatorOptions, ResolvedCollatorOptions, Strength}; |
| 29 |
use crate::preferences::{CollationCaseFirst, CollationNumericOrdering, CollationType}; |
| 30 |
use crate::provider::CollationData; |
| 31 |
use crate::provider::CollationDiacritics; |
| 32 |
use crate::provider::CollationDiacriticsV1; |
| 33 |
use crate::provider::CollationJamo; |
| 34 |
use crate::provider::CollationJamoV1; |
| 35 |
use crate::provider::CollationMetadata; |
| 36 |
use crate::provider::CollationMetadataV1; |
| 37 |
use crate::provider::CollationReordering; |
| 38 |
use crate::provider::CollationReorderingV1; |
| 39 |
use crate::provider::CollationRootV1; |
| 40 |
use crate::provider::CollationSpecialPrimaries; |
| 41 |
use crate::provider::CollationSpecialPrimariesV1; |
| 42 |
use crate::provider::CollationTailoringV1; |
| 43 |
use core::cmp::Ordering; |
| 44 |
use core::convert::Infallible; |
| 45 |
use icu_normalizer::DecomposingNormalizerBorrowed; |
| 46 |
use icu_normalizer::Decomposition; |
| 47 |
use icu_normalizer::provider::DecompositionData; |
| 48 |
use icu_normalizer::provider::DecompositionTables; |
| 49 |
use icu_normalizer::provider::NormalizerNfdDataV1; |
| 50 |
use icu_normalizer::provider::NormalizerNfdTablesV1; |
| 51 |
use icu_provider::prelude::*; |
| 52 |
use smallvec::SmallVec; |
| 53 |
use utf8_iter::Utf8CharsEx; |
| 54 |
use utf16_iter::Utf16CharsEx; |
| 55 |
|
| 56 |
// Special sort key bytes for all levels. |
| 57 |
const LEVEL_SEPARATOR_BYTE: u8 = 1; |
| 58 |
|
| 59 |
/// Merge-sort-key separator. |
| 60 |
/// |
| 61 |
/// Same as the unique primary and identical-level weights of U+FFFE. Must not |
| 62 |
/// be used as primary compression low terminator. Otherwise usable. |
| 63 |
const MERGE_SEPARATOR: char = '\u{fffe}'; |
| 64 |
const MERGE_SEPARATOR_BYTE: u8 = 2; |
| 65 |
const MERGE_SEPARATOR_PRIMARY: u32 = 0x02000000; |
| 66 |
|
| 67 |
/// Primary compression low terminator, must be greater than [`MERGE_SEPARATOR_BYTE`]. |
| 68 |
/// |
| 69 |
/// Reserved value in primary second byte if the lead byte is compressible. |
| 70 |
/// Otherwise usable in all CE weight bytes. |
| 71 |
const PRIMARY_COMPRESSION_LOW_BYTE: u8 = 3; |
| 72 |
|
| 73 |
/// Primary compression high terminator. |
| 74 |
/// |
| 75 |
/// Reserved value in primary second byte if the lead byte is compressible. |
| 76 |
/// Otherwise usable in all CE weight bytes. |
| 77 |
const PRIMARY_COMPRESSION_HIGH_BYTE: u8 = 0xff; |
| 78 |
|
| 79 |
/// Default secondary/tertiary weight lead byte. |
| 80 |
const COMMON_BYTE: u8 = 5; |
| 81 |
const COMMON_WEIGHT16: u16 = 0x0500; |
| 82 |
|
| 83 |
// Internal flags for sort key generation |
| 84 |
const PRIMARY_LEVEL_FLAG: u8 = 0x01; |
| 85 |
const SECONDARY_LEVEL_FLAG: u8 = 0x02; |
| 86 |
const CASE_LEVEL_FLAG: u8 = 0x04; |
| 87 |
const TERTIARY_LEVEL_FLAG: u8 = 0x08; |
| 88 |
const QUATERNARY_LEVEL_FLAG: u8 = 0x10; |
| 89 |
|
| 90 |
const LEVEL_MASKS: [u8; Strength::Identical as usize + 1] = [ |
| 91 |
PRIMARY_LEVEL_FLAG, |
| 92 |
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG, |
| 93 |
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG | TERTIARY_LEVEL_FLAG, |
| 94 |
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG | TERTIARY_LEVEL_FLAG | QUATERNARY_LEVEL_FLAG, |
| 95 |
0, |
| 96 |
0, |
| 97 |
0, |
| 98 |
PRIMARY_LEVEL_FLAG | SECONDARY_LEVEL_FLAG | TERTIARY_LEVEL_FLAG | QUATERNARY_LEVEL_FLAG, |
| 99 |
]; |
| 100 |
|
| 101 |
// Internal constants for indexing into the below compression configurations |
| 102 |
const WEIGHT_LOW: usize = 0; |
| 103 |
const WEIGHT_MIDDLE: usize = 1; |
| 104 |
const WEIGHT_HIGH: usize = 2; |
| 105 |
const WEIGHT_MAX_COUNT: usize = 3; |
| 106 |
|
| 107 |
// Secondary level: Compress up to 33 common weights as 05..25 or 25..45. |
| 108 |
const SEC_COMMON: [u8; 4] = [COMMON_BYTE, COMMON_BYTE + 0x20, COMMON_BYTE + 0x40, 0x21]; |
| 109 |
|
| 110 |
// Case level, lowerFirst: Compress up to 7 common weights as 1..7 or 7..13. |
| 111 |
const CASE_LOWER_FIRST_COMMON: [u8; 4] = [1, 7, 13, 7]; |
| 112 |
|
| 113 |
// Case level, upperFirst: Compress up to 13 common weights as 3..15. |
| 114 |
const CASE_UPPER_FIRST_COMMON: [u8; 4] = [3, 0 /* unused */, 15, 13]; |
| 115 |
|
| 116 |
// Tertiary level only (no case): Compress up to 97 common weights as 05..65 or 65..C5. |
| 117 |
const TER_ONLY_COMMON: [u8; 4] = [COMMON_BYTE, COMMON_BYTE + 0x60, COMMON_BYTE + 0xc0, 0x61]; |
| 118 |
|
| 119 |
// Tertiary with case, lowerFirst: Compress up to 33 common weights as 05..25 or 25..45. |
| 120 |
const TER_LOWER_FIRST_COMMON: [u8; 4] = [COMMON_BYTE, COMMON_BYTE + 0x20, COMMON_BYTE + 0x40, 0x21]; |
| 121 |
|
| 122 |
// Tertiary with case, upperFirst: Compress up to 33 common weights as 85..A5 or A5..C5. |
| 123 |
const TER_UPPER_FIRST_COMMON: [u8; 4] = [ |
| 124 |
COMMON_BYTE + 0x80, |
| 125 |
COMMON_BYTE + 0x80 + 0x20, |
| 126 |
COMMON_BYTE + 0x80 + 0x40, |
| 127 |
0x21, |
| 128 |
]; |
| 129 |
|
| 130 |
const QUAT_COMMON: [u8; 4] = [0x1c, 0x1c + 0x70, 0x1c + 0xe0, 0x71]; |
| 131 |
const QUAT_SHIFTED_LIMIT_BYTE: u8 = QUAT_COMMON[WEIGHT_LOW] - 1; // 0x1b |
| 132 |
|
| 133 |
// Do not use byte values 0, 1, 2 because they are separators in sort keys. |
| 134 |
const SLOPE_MIN: i32 = 3; |
| 135 |
const SLOPE_MAX: i32 = 0xff; |
| 136 |
const SLOPE_MIDDLE: i32 = 0x81; |
| 137 |
const SLOPE_TAIL_COUNT: i32 = SLOPE_MAX - SLOPE_MIN + 1; |
| 138 |
const SLOPE_SINGLE: i32 = 80; |
| 139 |
const SLOPE_LEAD_2: i32 = 42; |
| 140 |
const SLOPE_LEAD_3: i32 = 3; |
| 141 |
|
| 142 |
// The difference value range for single-byters. |
| 143 |
const SLOPE_REACH_POS_1: i32 = SLOPE_SINGLE; |
| 144 |
const SLOPE_REACH_NEG_1: i32 = -SLOPE_SINGLE; |
| 145 |
|
| 146 |
// The difference value range for double-byters. |
| 147 |
const SLOPE_REACH_POS_2: i32 = SLOPE_LEAD_2 * SLOPE_TAIL_COUNT + (SLOPE_LEAD_2 - 1); |
| 148 |
const SLOPE_REACH_NEG_2: i32 = -SLOPE_REACH_POS_2 - 1; |
| 149 |
|
| 150 |
// The difference value range for 3-byters. |
| 151 |
const SLOPE_REACH_POS_3: i32 = SLOPE_LEAD_3 * SLOPE_TAIL_COUNT * SLOPE_TAIL_COUNT |
| 152 |
+ (SLOPE_LEAD_3 - 1) * SLOPE_TAIL_COUNT |
| 153 |
+ (SLOPE_TAIL_COUNT - 1); |
| 154 |
const SLOPE_REACH_NEG_3: i32 = -SLOPE_REACH_POS_3 - 1; |
| 155 |
|
| 156 |
// The lead byte start values. |
| 157 |
const SLOPE_START_POS_2: i32 = SLOPE_MIDDLE + SLOPE_SINGLE + 1; |
| 158 |
const SLOPE_START_POS_3: i32 = SLOPE_START_POS_2 + SLOPE_LEAD_2; |
| 159 |
const SLOPE_START_NEG_2: i32 = SLOPE_MIDDLE + SLOPE_REACH_NEG_1; |
| 160 |
const SLOPE_START_NEG_3: i32 = SLOPE_START_NEG_2 - SLOPE_LEAD_2; |
| 161 |
|
| 162 |
trait Reorder: Copy { |
| 163 |
fn reorder(self, p: u32) -> u32; |
| 164 |
} |
| 165 |
|
| 166 |
#[derive(Clone, Copy)] |
| 167 |
struct NoReorder; |
| 168 |
|
| 169 |
impl Reorder for NoReorder { |
| 170 |
#[inline(always)] |
| 171 |
fn reorder(self, p: u32) -> u32 { |
| 172 |
p |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
impl Reorder for &CollationReordering<'_> { |
| 177 |
#[inline(always)] |
| 178 |
fn reorder(self, p: u32) -> u32 { |
| 179 |
CollationReordering::reorder(self, p) |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
struct AnyQuaternaryAccumulator(u32); |
| 184 |
|
| 185 |
impl AnyQuaternaryAccumulator { |
| 186 |
#[inline(always)] |
| 187 |
pub fn new() -> Self { |
| 188 |
AnyQuaternaryAccumulator(0) |
| 189 |
} |
| 190 |
#[inline(always)] |
| 191 |
pub fn accumulate(&mut self, non_primary: NonPrimary) { |
| 192 |
self.0 |= non_primary.bits() |
| 193 |
} |
| 194 |
#[inline(always)] |
| 195 |
pub fn has_quaternary(&self) -> bool { |
| 196 |
self.0 & u32::from(QUATERNARY_MASK) != 0 |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
/// `true` iff `i` is greater or equal to `start` and less or equal |
| 201 |
/// to `end`. |
| 202 |
#[inline(always)] |
| 203 |
fn in_inclusive_range16(i: u16, start: u16, end: u16) -> bool { |
| 204 |
i.wrapping_sub(start) <= (end - start) |
| 205 |
} |
| 206 |
|
| 207 |
/// Helper trait for getting a `char` iterator from Latin1 data. |
| 208 |
/// |
| 209 |
/// ✨ *Enabled with the `latin1` Cargo feature.* |
| 210 |
#[cfg(feature = "latin1")] |
| 211 |
trait Latin1Chars { |
| 212 |
fn latin1_chars(&self) -> impl DoubleEndedIterator<Item = char>; |
| 213 |
} |
| 214 |
|
| 215 |
#[cfg(feature = "latin1")] |
| 216 |
impl Latin1Chars for [u8] { |
| 217 |
fn latin1_chars(&self) -> impl DoubleEndedIterator<Item = char> { |
| 218 |
self.iter().map(|b| char::from(*b)) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
/// Finds the identical prefix of `left` and `right` containing |
| 223 |
/// Latin1. |
| 224 |
/// |
| 225 |
/// Returns the identical prefix, the part of `left` after the |
| 226 |
/// prefix, and the part of `right` after the prefix. |
| 227 |
/// |
| 228 |
/// ✨ *Enabled with the `latin1` Cargo feature.* |
| 229 |
#[cfg(feature = "latin1")] |
| 230 |
fn split_prefix_latin1<'a, 'b>(left: &'a [u8], right: &'b [u8]) -> (&'a [u8], &'a [u8], &'b [u8]) { |
| 231 |
let i = left |
| 232 |
.iter() |
| 233 |
.zip(right.iter()) |
| 234 |
.take_while(|(l, r)| l == r) |
| 235 |
.count(); |
| 236 |
if let Some((head, left_tail)) = left.split_at_checked(i) |
| 237 |
&& let Some(right_tail) = right.get(i..) |
| 238 |
{ |
| 239 |
return (head, left_tail, right_tail); |
| 240 |
} |
| 241 |
(&[], left, right) |
| 242 |
} |
| 243 |
|
| 244 |
/// Finds the identical prefix of `left` containing Latin1 |
| 245 |
/// and `right` containing potentially ill-formed UTF-16. |
| 246 |
/// |
| 247 |
/// Returns the identical prefix, the part of `left` after the |
| 248 |
/// prefix, and the part of `right` after the prefix. |
| 249 |
/// |
| 250 |
/// ✨ *Enabled with the `latin1` Cargo feature.* |
| 251 |
#[cfg(feature = "latin1")] |
| 252 |
fn split_prefix_latin1_utf16<'a, 'b>( |
| 253 |
left: &'a [u8], |
| 254 |
right: &'b [u16], |
| 255 |
) -> (&'a [u8], &'a [u8], &'b [u16]) { |
| 256 |
let i = left |
| 257 |
.iter() |
| 258 |
.zip(right.iter()) |
| 259 |
.take_while(|(l, r)| u16::from(**l) == **r) |
| 260 |
.count(); |
| 261 |
if let Some((head, left_tail)) = left.split_at_checked(i) |
| 262 |
&& let Some(right_tail) = right.get(i..) |
| 263 |
{ |
| 264 |
return (head, left_tail, right_tail); |
| 265 |
} |
| 266 |
(&[], left, right) |
| 267 |
} |
| 268 |
|
| 269 |
/// Finds the identical prefix of `left` and `right` containing |
| 270 |
/// potentially ill-formed UTF-16, while avoiding splitting a |
| 271 |
/// well-formed surrogate pair. In case of ill-formed |
| 272 |
/// UTF-16, the prefix is not guaranteed to be maximal. |
| 273 |
/// |
| 274 |
/// Returns the identical prefix, the part of `left` after the |
| 275 |
/// prefix, and the part of `right` after the prefix. |
| 276 |
fn split_prefix_u16<'a, 'b>( |
| 277 |
left: &'a [u16], |
| 278 |
right: &'b [u16], |
| 279 |
) -> (&'a [u16], &'a [u16], &'b [u16]) { |
| 280 |
let mut i = left |
| 281 |
.iter() |
| 282 |
.zip(right.iter()) |
| 283 |
.take_while(|(l, r)| l == r) |
| 284 |
.count(); |
| 285 |
if i != 0 |
| 286 |
&& let Some(&last) = left.get(i.wrapping_sub(1)) |
| 287 |
{ |
| 288 |
if in_inclusive_range16(last, 0xD800, 0xDBFF) { |
| 289 |
i -= 1; |
| 290 |
} |
| 291 |
if let Some((head, left_tail)) = left.split_at_checked(i) |
| 292 |
&& let Some(right_tail) = right.get(i..) |
| 293 |
{ |
| 294 |
return (head, left_tail, right_tail); |
| 295 |
} |
| 296 |
} |
| 297 |
(&[], left, right) |
| 298 |
} |
| 299 |
|
| 300 |
/// Finds the identical prefix of `left` and `right` containing |
| 301 |
/// potentially ill-formed UTF-8, while avoiding splitting a UTF-8 |
| 302 |
/// byte sequence. In case of ill-formed UTF-8, the prefix is |
| 303 |
/// not guaranteed to be maximal. |
| 304 |
/// |
| 305 |
/// Returns the identical prefix, the part of `left` after the |
| 306 |
/// prefix, and the part of `right` after the prefix. |
| 307 |
fn split_prefix_u8<'a, 'b>(left: &'a [u8], right: &'b [u8]) -> (&'a [u8], &'a [u8], &'b [u8]) { |
| 308 |
let mut i = left |
| 309 |
.iter() |
| 310 |
.zip(right.iter()) |
| 311 |
.take_while(|(l, r)| l == r) |
| 312 |
.count(); |
| 313 |
if i != 0 { |
| 314 |
// Tails must not start with a UTF-8 continuation |
| 315 |
// byte unless it's the first byte of the original |
| 316 |
// slice. |
| 317 |
|
| 318 |
// First, left and right differ, but since they |
| 319 |
// are the same afterwards, one of them needs checking |
| 320 |
// only once. |
| 321 |
if let Some(right_first) = right.get(i) |
| 322 |
&& (right_first & 0b1100_0000) == 0b1000_0000 |
| 323 |
{ |
| 324 |
i -= 1; |
| 325 |
} |
| 326 |
while i != 0 { |
| 327 |
if let Some(left_first) = left.get(i) |
| 328 |
&& (left_first & 0b1100_0000) == 0b1000_0000 |
| 329 |
{ |
| 330 |
i -= 1; |
| 331 |
continue; |
| 332 |
} |
| 333 |
break; |
| 334 |
} |
| 335 |
if let Some((head, left_tail)) = left.split_at_checked(i) |
| 336 |
&& let Some(right_tail) = right.get(i..) |
| 337 |
{ |
| 338 |
return (head, left_tail, right_tail); |
| 339 |
} |
| 340 |
} |
| 341 |
(&[], left, right) |
| 342 |
} |
| 343 |
|
| 344 |
/// Finds the identical prefix of `left` and `right` containing |
| 345 |
/// guaranteed well-format UTF-8. |
| 346 |
/// |
| 347 |
/// Returns the identical prefix, the part of `left` after the |
| 348 |
/// prefix, and the part of `right` after the prefix. |
| 349 |
fn split_prefix<'a, 'b>(left: &'a str, right: &'b str) -> (&'a str, &'a str, &'b str) { |
| 350 |
let left_bytes = left.as_bytes(); |
| 351 |
let right_bytes = right.as_bytes(); |
| 352 |
let mut i = left_bytes |
| 353 |
.iter() |
| 354 |
.zip(right_bytes.iter()) |
| 355 |
.take_while(|(l, r)| l == r) |
| 356 |
.count(); |
| 357 |
if i != 0 { |
| 358 |
// Tails must not start with a UTF-8 continuation |
| 359 |
// byte. |
| 360 |
|
| 361 |
// Since the inputs are valid UTF-8, the first byte |
| 362 |
// of either input slice cannot be a contination slice, |
| 363 |
// so we may rely on finding a lead byte when walking |
| 364 |
// backwards. |
| 365 |
|
| 366 |
// Since the inputs are valid UTF-8, if a tail starts |
| 367 |
// with a continuation, both tails must start with a |
| 368 |
// continuation, since the most recent lead byte must |
| 369 |
// be equal, so the difference is within valid UTF-8 |
| 370 |
// sequences of equal length. |
| 371 |
|
| 372 |
// Therefore, it's sufficient to examine only one of |
| 373 |
// the sides. |
| 374 |
loop { |
| 375 |
if let Some(left_first) = left_bytes.get(i) |
| 376 |
&& (left_first & 0b1100_0000) == 0b1000_0000 |
| 377 |
{ |
| 378 |
i -= 1; |
| 379 |
continue; |
| 380 |
} |
| 381 |
break; |
| 382 |
} |
| 383 |
// The methods below perform useless UTF-8 boundary checks, |
| 384 |
// since we just checked. However, avoiding `unsafe` to |
| 385 |
// make this code easier to audit. |
| 386 |
if let Some((head, left_tail)) = left.split_at_checked(i) |
| 387 |
&& let Some(right_tail) = right.get(i..) |
| 388 |
{ |
| 389 |
return (head, left_tail, right_tail); |
| 390 |
} |
| 391 |
} |
| 392 |
("", left, right) |
| 393 |
} |
| 394 |
|
| 395 |
/// Holder struct for payloads that are locale-dependent. (For code |
| 396 |
/// reuse between owned and borrowed cases.) |
| 397 |
#[derive(Debug)] |
| 398 |
struct LocaleSpecificDataHolder { |
| 399 |
tailoring: Option<DataPayload<CollationTailoringV1>>, |
| 400 |
diacritics: DataPayload<CollationDiacriticsV1>, |
| 401 |
reordering: Option<DataPayload<CollationReorderingV1>>, |
| 402 |
metadata: CollationMetadata, |
| 403 |
} |
| 404 |
|
| 405 |
icu_locale_core::preferences::define_preferences!( |
| 406 |
/// The preferences for collation. |
| 407 |
/// |
| 408 |
/// # Preferences |
| 409 |
/// |
| 410 |
/// Examples for using the different preferences below can be found in the [crate-level docs](crate). |
| 411 |
/// |
| 412 |
/// ## Case First |
| 413 |
/// |
| 414 |
/// See the [spec](https://www.unicode.org/reports/tr35/tr35-collation.html#Case_Parameters). |
| 415 |
/// This is the BCP47 key `kf`. Three possibilities: [`CollationCaseFirst::False`] (default, |
| 416 |
/// except for Danish and Maltese), [`CollationCaseFirst::Lower`], and [`CollationCaseFirst::Upper`] |
| 417 |
/// (default for Danish and Maltese). |
| 418 |
/// |
| 419 |
/// ## Numeric |
| 420 |
/// |
| 421 |
/// This is the BCP47 key `kn`. When set to [`CollationNumericOrdering::True`], any sequence of decimal |
| 422 |
/// digits (General_Category = Nd) is sorted at the primary level according to the |
| 423 |
/// numeric value. The default is [`CollationNumericOrdering::False`]. |
| 424 |
[Copy] |
| 425 |
CollatorPreferences, |
| 426 |
{ |
| 427 |
/// The collation type. This corresponds to the `-u-co` BCP-47 tag. |
| 428 |
collation_type: CollationType, |
| 429 |
/// Treatment of case. (Large and small kana differences are treated as case differences.) |
| 430 |
/// This corresponds to the `-u-kf` BCP-47 tag. |
| 431 |
case_first: CollationCaseFirst, |
| 432 |
/// When set to `True`, any sequence of decimal digits is sorted at a primary level according |
| 433 |
/// to the numeric value. |
| 434 |
/// This corresponds to the `-u-kn` BPC-47 tag. |
| 435 |
numeric_ordering: CollationNumericOrdering |
| 436 |
} |
| 437 |
); |
| 438 |
|
| 439 |
impl LocaleSpecificDataHolder { |
| 440 |
/// The constructor code reused between owned and borrowed cases. |
| 441 |
fn try_new_unstable<D>(provider: &D, prefs: CollatorPreferences) -> Result<Self, DataError> |
| 442 |
where |
| 443 |
D: DataProvider<CollationTailoringV1> |
| 444 |
+ DataProvider<CollationDiacriticsV1> |
| 445 |
+ DataProvider<CollationMetadataV1> |
| 446 |
+ DataProvider<CollationReorderingV1> |
| 447 |
+ ?Sized, |
| 448 |
{ |
| 449 |
let marker_attributes = prefs |
| 450 |
.collation_type |
| 451 |
.as_ref() |
| 452 |
// all collation types are valid marker attributes |
| 453 |
.map(|c| DataMarkerAttributes::from_str_or_panic(c.as_str())) |
| 454 |
.unwrap_or_default(); |
| 455 |
|
| 456 |
let data_locale = CollationTailoringV1::make_locale(prefs.locale_preferences); |
| 457 |
let req = DataRequest { |
| 458 |
id: DataIdentifierBorrowed::for_marker_attributes_and_locale( |
| 459 |
marker_attributes, |
| 460 |
&data_locale, |
| 461 |
), |
| 462 |
metadata: { |
| 463 |
let mut metadata = DataRequestMetadata::default(); |
| 464 |
metadata.silent = true; |
| 465 |
metadata |
| 466 |
}, |
| 467 |
}; |
| 468 |
|
| 469 |
let fallback_req = DataRequest { |
| 470 |
id: DataIdentifierBorrowed::for_marker_attributes_and_locale( |
| 471 |
Default::default(), |
| 472 |
&data_locale, |
| 473 |
), |
| 474 |
..Default::default() |
| 475 |
}; |
| 476 |
|
| 477 |
let metadata_payload: DataPayload<CollationMetadataV1> = provider |
| 478 |
.load(req) |
| 479 |
.or_else(|_| provider.load(fallback_req))? |
| 480 |
.payload; |
| 481 |
|
| 482 |
let metadata = *metadata_payload.get(); |
| 483 |
|
| 484 |
let tailoring: Option<DataPayload<CollationTailoringV1>> = if metadata.tailored() { |
| 485 |
Some( |
| 486 |
provider |
| 487 |
.load(req) |
| 488 |
.or_else(|_| provider.load(fallback_req))? |
| 489 |
.payload, |
| 490 |
) |
| 491 |
} else { |
| 492 |
None |
| 493 |
}; |
| 494 |
|
| 495 |
let reordering: Option<DataPayload<CollationReorderingV1>> = if metadata.reordering() { |
| 496 |
Some( |
| 497 |
provider |
| 498 |
.load(req) |
| 499 |
.or_else(|_| provider.load(fallback_req))? |
| 500 |
.payload, |
| 501 |
) |
| 502 |
} else { |
| 503 |
None |
| 504 |
}; |
| 505 |
|
| 506 |
if let Some(reordering) = &reordering |
| 507 |
&& reordering.get().reorder_table.len() != 256 |
| 508 |
{ |
| 509 |
return Err(DataError::custom("invalid").with_marker(CollationReorderingV1::INFO)); |
| 510 |
} |
| 511 |
|
| 512 |
let tailored_diacritics = metadata.tailored_diacritics(); |
| 513 |
let diacritics: DataPayload<CollationDiacriticsV1> = provider |
| 514 |
.load(if tailored_diacritics { |
| 515 |
req |
| 516 |
} else { |
| 517 |
Default::default() |
| 518 |
})? |
| 519 |
.payload; |
| 520 |
|
| 521 |
if tailored_diacritics { |
| 522 |
// In the tailored case we accept a shorter table in which case the tailoring is |
| 523 |
// responsible for supplying the missing values in the trie. |
| 524 |
// As of June 2022, none of the collations actually use a shortened table. |
| 525 |
// Vietnamese and Ewe load a full-length alternative table and the rest use |
| 526 |
// the default one. |
| 527 |
if diacritics.get().secondaries.len() > OPTIMIZED_DIACRITICS_MAX_COUNT { |
| 528 |
return Err(DataError::custom("invalid").with_marker(CollationDiacriticsV1::INFO)); |
| 529 |
} |
| 530 |
} else if diacritics.get().secondaries.len() != OPTIMIZED_DIACRITICS_MAX_COUNT { |
| 531 |
return Err(DataError::custom("invalid").with_marker(CollationDiacriticsV1::INFO)); |
| 532 |
} |
| 533 |
|
| 534 |
Ok(LocaleSpecificDataHolder { |
| 535 |
tailoring, |
| 536 |
diacritics, |
| 537 |
metadata, |
| 538 |
reordering, |
| 539 |
}) |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
/// Compares strings according to culturally-relevant ordering. |
| 544 |
#[derive(Debug)] |
| 545 |
pub struct Collator { |
| 546 |
special_primaries: DataPayload<CollationSpecialPrimariesV1>, |
| 547 |
root: DataPayload<CollationRootV1>, |
| 548 |
tailoring: Option<DataPayload<CollationTailoringV1>>, |
| 549 |
jamo: DataPayload<CollationJamoV1>, |
| 550 |
diacritics: DataPayload<CollationDiacriticsV1>, |
| 551 |
options: CollatorOptionsBitField, |
| 552 |
reordering: Option<DataPayload<CollationReorderingV1>>, |
| 553 |
decompositions: DataPayload<NormalizerNfdDataV1>, |
| 554 |
tables: DataPayload<NormalizerNfdTablesV1>, |
| 555 |
} |
| 556 |
|
| 557 |
impl Collator { |
| 558 |
/// Constructs a borrowed version of this type for more efficient querying. |
| 559 |
pub fn as_borrowed(&self) -> CollatorBorrowed<'_> { |
| 560 |
CollatorBorrowed { |
| 561 |
special_primaries: self.special_primaries.get(), |
| 562 |
root: self.root.get(), |
| 563 |
tailoring: self.tailoring.as_ref().map(|s| s.get()), |
| 564 |
jamo: self.jamo.get(), |
| 565 |
diacritics: self.diacritics.get(), |
| 566 |
options: self.options, |
| 567 |
reordering: self.reordering.as_ref().map(|s| s.get()), |
| 568 |
decompositions: self.decompositions.get(), |
| 569 |
tables: self.tables.get(), |
| 570 |
} |
| 571 |
} |
| 572 |
|
| 573 |
/// Creates `CollatorBorrowed` for the given locale and options from compiled data. |
| 574 |
#[cfg(feature = "compiled_data")] |
| 575 |
pub fn try_new( |
| 576 |
prefs: CollatorPreferences, |
| 577 |
options: CollatorOptions, |
| 578 |
) -> Result<CollatorBorrowed<'static>, DataError> { |
| 579 |
CollatorBorrowed::try_new(prefs, options) |
| 580 |
} |
| 581 |
|
| 582 |
icu_provider::gen_buffer_data_constructors!( |
| 583 |
(prefs: CollatorPreferences, options: CollatorOptions) -> error: DataError, |
| 584 |
functions: [ |
| 585 |
try_new: skip, |
| 586 |
try_new_with_buffer_provider, |
| 587 |
try_new_unstable, |
| 588 |
Self |
| 589 |
] |
| 590 |
); |
| 591 |
|
| 592 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)] |
| 593 |
pub fn try_new_unstable<D>( |
| 594 |
provider: &D, |
| 595 |
prefs: CollatorPreferences, |
| 596 |
options: CollatorOptions, |
| 597 |
) -> Result<Self, DataError> |
| 598 |
where |
| 599 |
D: DataProvider<CollationSpecialPrimariesV1> |
| 600 |
+ DataProvider<CollationRootV1> |
| 601 |
+ DataProvider<CollationTailoringV1> |
| 602 |
+ DataProvider<CollationDiacriticsV1> |
| 603 |
+ DataProvider<CollationJamoV1> |
| 604 |
+ DataProvider<CollationMetadataV1> |
| 605 |
+ DataProvider<CollationReorderingV1> |
| 606 |
+ DataProvider<NormalizerNfdDataV1> |
| 607 |
+ DataProvider<NormalizerNfdTablesV1> |
| 608 |
+ ?Sized, |
| 609 |
{ |
| 610 |
let root = provider.load(Default::default())?.payload; |
| 611 |
let decompositions = provider.load(Default::default())?.payload; |
| 612 |
let tables = provider.load(Default::default())?.payload; |
| 613 |
let jamo = provider.load(Default::default())?.payload; |
| 614 |
let special_primaries = provider.load(Default::default())?.payload; |
| 615 |
|
| 616 |
let LocaleSpecificDataHolder { |
| 617 |
tailoring, |
| 618 |
diacritics, |
| 619 |
reordering, |
| 620 |
metadata, |
| 621 |
} = LocaleSpecificDataHolder::try_new_unstable(provider, prefs)?; |
| 622 |
|
| 623 |
Ok(Collator { |
| 624 |
special_primaries, |
| 625 |
root, |
| 626 |
tailoring, |
| 627 |
jamo, |
| 628 |
diacritics, |
| 629 |
options: options.resolve(metadata, prefs.case_first, prefs.numeric_ordering), |
| 630 |
reordering, |
| 631 |
decompositions, |
| 632 |
tables, |
| 633 |
}) |
| 634 |
} |
| 635 |
} |
| 636 |
|
| 637 |
macro_rules! compare { |
| 638 |
($(#[$meta:meta])*, |
| 639 |
$compare:ident, |
| 640 |
$left_slice:ty, |
| 641 |
$right_slice:ty, |
| 642 |
$split_prefix:ident, |
| 643 |
$left_to_iter:ident, |
| 644 |
$right_to_iter:ident, |
| 645 |
) => { |
| 646 |
$(#[$meta])* |
| 647 |
pub fn $compare(&self, left: &$left_slice, right: &$right_slice) -> Ordering { |
| 648 |
let (head, left_tail, right_tail) = $split_prefix(left, right); |
| 649 |
if left_tail.is_empty() && right_tail.is_empty() { |
| 650 |
return Ordering::Equal; |
| 651 |
} |
| 652 |
let ret = self.compare_impl(left_tail.$left_to_iter(), right_tail.$right_to_iter(), head.$left_to_iter().rev()); |
| 653 |
if self.options.strength() == Strength::Identical && ret == Ordering::Equal { |
| 654 |
return Decomposition::new(left_tail.$left_to_iter(), self.decompositions, self.tables).map(|c| if c != MERGE_SEPARATOR { c as i32 } else { -1i32 }).cmp( |
| 655 |
Decomposition::new(right_tail.$right_to_iter(), self.decompositions, self.tables).map(|c| if c != MERGE_SEPARATOR { c as i32 } else { -1i32 }), |
| 656 |
); |
| 657 |
} |
| 658 |
ret |
| 659 |
} |
| 660 |
} |
| 661 |
} |
| 662 |
|
| 663 |
/// Compares strings according to culturally-relevant ordering, |
| 664 |
/// borrowed version. |
| 665 |
#[derive(Debug)] |
| 666 |
pub struct CollatorBorrowed<'a> { |
| 667 |
special_primaries: &'a CollationSpecialPrimaries<'a>, |
| 668 |
root: &'a CollationData<'a>, |
| 669 |
tailoring: Option<&'a CollationData<'a>>, |
| 670 |
jamo: &'a CollationJamo<'a>, |
| 671 |
diacritics: &'a CollationDiacritics<'a>, |
| 672 |
options: CollatorOptionsBitField, |
| 673 |
reordering: Option<&'a CollationReordering<'a>>, |
| 674 |
decompositions: &'a DecompositionData<'a>, |
| 675 |
tables: &'a DecompositionTables<'a>, |
| 676 |
} |
| 677 |
|
| 678 |
impl CollatorBorrowed<'static> { |
| 679 |
/// Creates a collator for the given locale and options from compiled data. |
| 680 |
#[cfg(feature = "compiled_data")] |
| 681 |
pub fn try_new( |
| 682 |
prefs: CollatorPreferences, |
| 683 |
options: CollatorOptions, |
| 684 |
) -> Result<Self, DataError> { |
| 685 |
let provider = &crate::provider::Baked; |
| 686 |
|
| 687 |
let decompositions = icu_normalizer::provider::Baked::SINGLETON_NORMALIZER_NFD_DATA_V1; |
| 688 |
let tables = icu_normalizer::provider::Baked::SINGLETON_NORMALIZER_NFD_TABLES_V1; |
| 689 |
let root = crate::provider::Baked::SINGLETON_COLLATION_ROOT_V1; |
| 690 |
let jamo = crate::provider::Baked::SINGLETON_COLLATION_JAMO_V1; |
| 691 |
let special_primaries = crate::provider::Baked::SINGLETON_COLLATION_SPECIAL_PRIMARIES_V1; |
| 692 |
|
| 693 |
let locale_dependent = LocaleSpecificDataHolder::try_new_unstable(provider, prefs)?; |
| 694 |
#[expect(clippy::unwrap_used)] // baked provider |
| 695 |
let tailoring = locale_dependent.tailoring.map(|s| s.get_static().unwrap()); |
| 696 |
#[expect(clippy::unwrap_used)] // baked provider |
| 697 |
let diacritics = locale_dependent.diacritics.get_static().unwrap(); |
| 698 |
#[expect(clippy::unwrap_used)] // baked provider |
| 699 |
let reordering = locale_dependent.reordering.map(|s| s.get_static().unwrap()); |
| 700 |
let metadata = locale_dependent.metadata; |
| 701 |
|
| 702 |
Ok(CollatorBorrowed { |
| 703 |
special_primaries, |
| 704 |
root, |
| 705 |
tailoring, |
| 706 |
jamo, |
| 707 |
diacritics, |
| 708 |
options: options.resolve(metadata, prefs.case_first, prefs.numeric_ordering), |
| 709 |
reordering, |
| 710 |
decompositions, |
| 711 |
tables, |
| 712 |
}) |
| 713 |
} |
| 714 |
|
| 715 |
/// This creates a root collator using baked data only. |
| 716 |
/// |
| 717 |
/// ✨ *Enabled with the `unstable` and `compiled_data` Cargo features.* |
| 718 |
#[cfg(feature = "compiled_data")] |
| 719 |
#[cfg(feature = "unstable")] |
| 720 |
pub const fn new_root(options: CollatorOptions) -> Self { |
| 721 |
let decompositions = icu_normalizer::provider::Baked::SINGLETON_NORMALIZER_NFD_DATA_V1; |
| 722 |
let tables = icu_normalizer::provider::Baked::SINGLETON_NORMALIZER_NFD_TABLES_V1; |
| 723 |
let root = crate::provider::Baked::SINGLETON_COLLATION_ROOT_V1; |
| 724 |
let jamo = crate::provider::Baked::SINGLETON_COLLATION_JAMO_V1; |
| 725 |
let special_primaries = crate::provider::Baked::SINGLETON_COLLATION_SPECIAL_PRIMARIES_V1; |
| 726 |
|
| 727 |
const METADATA: CollationMetadata = *crate::provider::Baked::COLLATION_METADATA_V1_UND; |
| 728 |
const _: () = assert!(!METADATA.tailored()); |
| 729 |
let tailoring = None; |
| 730 |
const _: () = assert!(!METADATA.tailored_diacritics()); |
| 731 |
const _: () = assert!( |
| 732 |
crate::provider::Baked::COLLATION_DIACRITICS_V1_UND |
| 733 |
.secondaries |
| 734 |
.as_slice() |
| 735 |
.len() |
| 736 |
== OPTIMIZED_DIACRITICS_MAX_COUNT |
| 737 |
); |
| 738 |
let diacritics = crate::provider::Baked::COLLATION_DIACRITICS_V1_UND; |
| 739 |
const _: () = assert!(!METADATA.reordering()); |
| 740 |
let reordering = None; |
| 741 |
|
| 742 |
Self { |
| 743 |
special_primaries, |
| 744 |
root, |
| 745 |
tailoring, |
| 746 |
jamo, |
| 747 |
diacritics, |
| 748 |
options: options.resolve(METADATA, None, None), |
| 749 |
reordering, |
| 750 |
decompositions, |
| 751 |
tables, |
| 752 |
} |
| 753 |
} |
| 754 |
|
| 755 |
/// Cheaply converts a [`CollatorBorrowed<'static>`] into a [`Collator`]. |
| 756 |
/// |
| 757 |
/// Note: Due to branching and indirection, using [`Collator`] might inhibit some |
| 758 |
/// compile-time optimizations that are possible with [`CollatorBorrowed`]. |
| 759 |
pub const fn static_to_owned(self) -> Collator { |
| 760 |
Collator { |
| 761 |
special_primaries: DataPayload::from_static_ref(self.special_primaries), |
| 762 |
root: DataPayload::from_static_ref(self.root), |
| 763 |
tailoring: if let Some(s) = self.tailoring { |
| 764 |
// `map` not available in const context |
| 765 |
Some(DataPayload::from_static_ref(s)) |
| 766 |
} else { |
| 767 |
None |
| 768 |
}, |
| 769 |
jamo: DataPayload::from_static_ref(self.jamo), |
| 770 |
diacritics: DataPayload::from_static_ref(self.diacritics), |
| 771 |
options: self.options, |
| 772 |
reordering: if let Some(s) = self.reordering { |
| 773 |
// `map` not available in const context |
| 774 |
Some(DataPayload::from_static_ref(s)) |
| 775 |
} else { |
| 776 |
None |
| 777 |
}, |
| 778 |
decompositions: DataPayload::from_static_ref(self.decompositions), |
| 779 |
tables: DataPayload::from_static_ref(self.tables), |
| 780 |
} |
| 781 |
} |
| 782 |
} |
| 783 |
|
| 784 |
impl<'a> CollatorBorrowed<'a> { |
| 785 |
/// The resolved options showing how the default options, the requested options, |
| 786 |
/// and the options from locale data were combined. |
| 787 |
pub fn resolved_options(&self) -> ResolvedCollatorOptions { |
| 788 |
self.options.into() |
| 789 |
} |
| 790 |
|
| 791 |
compare!( |
| 792 |
/// Compare guaranteed well-formed UTF-8 slices. |
| 793 |
, |
| 794 |
compare, |
| 795 |
str, |
| 796 |
str, |
| 797 |
split_prefix, |
| 798 |
chars, |
| 799 |
chars, |
| 800 |
); |
| 801 |
|
| 802 |
compare!( |
| 803 |
/// Compare potentially ill-formed UTF-8 slices. Ill-formed input is compared |
| 804 |
/// as if errors had been replaced with REPLACEMENT CHARACTERs according |
| 805 |
/// to the WHATWG Encoding Standard. |
| 806 |
, |
| 807 |
compare_utf8, |
| 808 |
[u8], |
| 809 |
[u8], |
| 810 |
split_prefix_u8, |
| 811 |
chars, |
| 812 |
chars, |
| 813 |
); |
| 814 |
|
| 815 |
compare!( |
| 816 |
/// Compare potentially ill-formed UTF-16 slices. Unpaired surrogates |
| 817 |
/// are compared as if each one was a REPLACEMENT CHARACTER. |
| 818 |
, |
| 819 |
compare_utf16, |
| 820 |
[u16], |
| 821 |
[u16], |
| 822 |
split_prefix_u16, |
| 823 |
chars, |
| 824 |
chars, |
| 825 |
); |
| 826 |
|
| 827 |
compare!( |
| 828 |
/// Compare Latin1 slices. |
| 829 |
/// |
| 830 |
/// ✨ *Enabled with the `latin1` Cargo feature.* |
| 831 |
#[cfg(feature = "latin1")] |
| 832 |
, |
| 833 |
compare_latin1, |
| 834 |
[u8], |
| 835 |
[u8], |
| 836 |
split_prefix_latin1, |
| 837 |
latin1_chars, |
| 838 |
latin1_chars, |
| 839 |
); |
| 840 |
|
| 841 |
compare!( |
| 842 |
/// Compare Latin1 slice with potentially ill-formed UTF-16 |
| 843 |
/// slice. |
| 844 |
/// |
| 845 |
/// If you need to compare a potentially ill-formed UTF-16 |
| 846 |
/// slice with a Latin1 slice, swap the arguments and |
| 847 |
/// call `reverse()` on the return value. |
| 848 |
/// |
| 849 |
/// ✨ *Enabled with the `latin1` Cargo feature.* |
| 850 |
#[cfg(feature = "latin1")] |
| 851 |
, |
| 852 |
compare_latin1_utf16, |
| 853 |
[u8], |
| 854 |
[u16], |
| 855 |
split_prefix_latin1_utf16, |
| 856 |
latin1_chars, |
| 857 |
chars, |
| 858 |
); |
| 859 |
|
| 860 |
#[inline(always)] |
| 861 |
fn tailoring_or_root(&self) -> &'a CollationData<'a> { |
| 862 |
if let Some(tailoring) = &self.tailoring { |
| 863 |
tailoring |
| 864 |
} else { |
| 865 |
// If the root collation is valid for the locale, |
| 866 |
// use the root as the tailoring so that reads from the |
| 867 |
// tailoring always succeed. |
| 868 |
// |
| 869 |
// TODO(#2011): Do we instead want to have an untailored |
| 870 |
// copypaste of the iterator that omits the tailoring |
| 871 |
// branches for performance at the expense of code size |
| 872 |
// and having to maintain both a tailoring-capable and |
| 873 |
// a tailoring-incapable version of the iterator? |
| 874 |
// Or, in order not to flip the branch prediction around, |
| 875 |
// should we have a no-op tailoring that contains a |
| 876 |
// specially-crafted CodePointTrie that always returns |
| 877 |
// a FALLBACK_CE32 after a single branch? |
| 878 |
self.root |
| 879 |
} |
| 880 |
} |
| 881 |
|
| 882 |
#[inline(always)] |
| 883 |
fn numeric_primary(&self) -> Option<u8> { |
| 884 |
if self.options.numeric() { |
| 885 |
Some(self.special_primaries.numeric_primary) |
| 886 |
} else { |
| 887 |
None |
| 888 |
} |
| 889 |
} |
| 890 |
|
| 891 |
#[inline(always)] |
| 892 |
fn variable_top(&self) -> u32 { |
| 893 |
if self.options.alternate_handling() == AlternateHandling::NonIgnorable { |
| 894 |
0 |
| 895 |
} else { |
| 896 |
// +1 so that we can use "<" and primary ignorables test out early. |
| 897 |
self.special_primaries |
| 898 |
.last_primary_for_group(self.options.max_variable()) |
| 899 |
+ 1 |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
/// The implementation of the comparison operation. |
| 904 |
/// |
| 905 |
/// `head_chars` is an iterator _backward_ over the identical |
| 906 |
/// prefix and `left_chars` and `right_chars` are iterators |
| 907 |
/// _forward_ over the parts after the identical prefix. |
| 908 |
fn compare_impl< |
| 909 |
L: Iterator<Item = char>, |
| 910 |
R: Iterator<Item = char>, |
| 911 |
H: Iterator<Item = char>, |
| 912 |
>( |
| 913 |
&self, |
| 914 |
left_chars: L, |
| 915 |
right_chars: R, |
| 916 |
mut head_chars: H, |
| 917 |
) -> Ordering { |
| 918 |
// Sadly, it looks like variable CEs and backward second level |
| 919 |
// require us to store the full 64-bit CEs instead of storing only |
| 920 |
// the NonPrimary part. |
| 921 |
// |
| 922 |
// TODO(#2008): Consider having two monomorphizations of this method: |
| 923 |
// one that can deal with variables shifted to quaternary and |
| 924 |
// backward second level and another that doesn't support that |
| 925 |
// and only stores `NonPrimary` in `left_ces` and `right_ces` |
| 926 |
// with double the number of stack allocated elements. |
| 927 |
|
| 928 |
// Note: These are used only after the identical prefix skipping, |
| 929 |
// but initializing these up here improves performance at the time |
| 930 |
// of writing. Presumably the source order affects the stack frame |
| 931 |
// layout. |
| 932 |
let mut left_ces: SmallVec<[CollationElement; CE_BUFFER_SIZE]> = SmallVec::new(); |
| 933 |
let mut right_ces: SmallVec<[CollationElement; CE_BUFFER_SIZE]> = SmallVec::new(); |
| 934 |
|
| 935 |
// The algorithm comes from CollationCompare::compareUpToQuaternary in ICU4C. |
| 936 |
|
| 937 |
let mut any_variable = false; |
| 938 |
let variable_top = self.variable_top(); |
| 939 |
|
| 940 |
let tailoring = self.tailoring_or_root(); |
| 941 |
let numeric_primary = self.numeric_primary(); |
| 942 |
let jamo = self.jamo.as_array(); |
| 943 |
let lithuanian_dot_above = self.options.lithuanian_dot_above(); |
| 944 |
let mut left = CollationElements::new( |
| 945 |
left_chars, |
| 946 |
self.root, |
| 947 |
tailoring, |
| 948 |
jamo, |
| 949 |
&self.diacritics.secondaries, |
| 950 |
self.decompositions, |
| 951 |
self.tables, |
| 952 |
numeric_primary, |
| 953 |
lithuanian_dot_above, |
| 954 |
); |
| 955 |
let mut right = CollationElements::new( |
| 956 |
right_chars, |
| 957 |
self.root, |
| 958 |
tailoring, |
| 959 |
jamo, |
| 960 |
&self.diacritics.secondaries, |
| 961 |
self.decompositions, |
| 962 |
self.tables, |
| 963 |
numeric_primary, |
| 964 |
lithuanian_dot_above, |
| 965 |
); |
| 966 |
|
| 967 |
// Start identical prefix |
| 968 |
|
| 969 |
// The logic here to check whether the boundary found by skipping |
| 970 |
// the identical prefix is safe is complicated compared to the ICU4C |
| 971 |
// approach of having a set of characters that are unsafe as the character |
| 972 |
// immediately following the identical prefix. However, the approach here |
| 973 |
// avoids extra data, and working on the main data avoids the bug |
| 974 |
// possibility of data structures not being mutually consistent. |
| 975 |
|
| 976 |
// This code intentionally does not keep around the `CollationElement32`s |
| 977 |
// that have been read from the collation data tries, because keeping |
| 978 |
// them around turned out to be a pessimization: There would be added |
| 979 |
// branches on the hot path of the algorithm that maps characters to |
| 980 |
// collation elements, and the element size of the upcoming buffer |
| 981 |
// would grow. |
| 982 |
// |
| 983 |
// However, the values read from the normalization trie _are_ kept around, |
| 984 |
// since there is already a place where to put them. |
| 985 |
|
| 986 |
// This loop is only broken out of as goto forward. |
| 987 |
#[expect(clippy::never_loop)] |
| 988 |
'prefix: loop { |
| 989 |
if let Some(mut head_last_c) = head_chars.next() { |
| 990 |
let norm_trie = &self.decompositions.trie; |
| 991 |
let mut head_last = CharacterAndClassAndTrieValue::new_with_trie_val( |
| 992 |
head_last_c, |
| 993 |
norm_trie.get(head_last_c), |
| 994 |
); |
| 995 |
let mut head_last_ce32 = CollationElement32::default(); |
| 996 |
let mut head_last_ok = false; |
| 997 |
if let Some(left_different) = left.iter_next_before_init() { |
| 998 |
left.prepend_upcoming_before_init(left_different.clone()); |
| 999 |
if let Some(right_different) = right.iter_next_before_init() { |
| 1000 |
// Note: left_different and right_different may both be U+FFFD. |
| 1001 |
right.prepend_upcoming_before_init(right_different.clone()); |
| 1002 |
|
| 1003 |
// The base logic is that a boundary between two starters |
| 1004 |
// that decompose to selves is safe iff the starter |
| 1005 |
// before the boundary can't contract a starter, the |
| 1006 |
// starter after the boundary doesn't have a prefix |
| 1007 |
// condition, and, with the numeric mode enabled, |
| 1008 |
// they aren't both numeric. |
| 1009 |
// |
| 1010 |
// This base logic is then extended with Hangul |
| 1011 |
// syllables and characters that decompose to a |
| 1012 |
// BMP starter followed by a BMP non-starter. |
| 1013 |
// The logic could be extended further, in |
| 1014 |
// particular to cover singleton decompositions |
| 1015 |
// to a BMP starter, but such characters can be |
| 1016 |
// expected to be rare enough in real-world input |
| 1017 |
// that it's not worthwhile to make this code more |
| 1018 |
// branchy. |
| 1019 |
// |
| 1020 |
// A Hangul syllable is safe on either side of the |
| 1021 |
// boundary, because Hangul syllables can't participate |
| 1022 |
// in contraction or have prefix conditions. They are |
| 1023 |
// also known not to be numeric. |
| 1024 |
// |
| 1025 |
// Hangul jamo is safe to look up from the main trie |
| 1026 |
// instead of the jamo table, because they aren't |
| 1027 |
// allowed to participate in contractions or prefix |
| 1028 |
// conditions, either, and are known not to be numeric. |
| 1029 |
// |
| 1030 |
// After a boundary, a decomposition to a BMP starter |
| 1031 |
// and a BMP non-starter can obviously be analyzed by |
| 1032 |
// considering the starter as if it was a starter |
| 1033 |
// that decomposes to self. |
| 1034 |
// |
| 1035 |
// Before a boundary the contraction condition considers |
| 1036 |
// whether the contraction can contract a starter. |
| 1037 |
// For the case of contracting a non-starter, it's |
| 1038 |
// fine for the BMP starter of the decomposition to |
| 1039 |
// contract the non-starter from the same decomposition: |
| 1040 |
// Since that would happen as part of the prefix that |
| 1041 |
// is identical, it wouldn't affect anything after. |
| 1042 |
// |
| 1043 |
// The case of contracting a non-starter other than |
| 1044 |
// the one that came from the decomposition itself |
| 1045 |
// is irrelevant, because we don't allow a non-starter |
| 1046 |
// right after the boundary regardless of the contraction |
| 1047 |
// status of what's before the boundary. |
| 1048 |
// |
| 1049 |
// Finally, decompositions to starter and non-starter |
| 1050 |
// are known not to be numeric. |
| 1051 |
|
| 1052 |
// The checks below are repetitive, but an attempt to factor |
| 1053 |
// repetitive code into an inlined function regressed, |
| 1054 |
// performance, so it seems that having the control flow |
| 1055 |
// right here without an intermediate enum from a |
| 1056 |
// function return to branch on is important. |
| 1057 |
|
| 1058 |
// This loop is only broken out of as goto forward. The control flow |
| 1059 |
// is much more readable this way. |
| 1060 |
#[expect(clippy::never_loop)] |
| 1061 |
loop { |
| 1062 |
// The two highest bits are about NFC, which we don't |
| 1063 |
// care about here. |
| 1064 |
let decomposition = head_last.trie_val; |
| 1065 |
if (decomposition |
| 1066 |
& !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER)) |
| 1067 |
== 0 |
| 1068 |
{ |
| 1069 |
// Intentionally empty block to keep |
| 1070 |
// the same structure as in the cases |
| 1071 |
// where something happens here. |
| 1072 |
} else if ((decomposition & HIGH_ZEROS_MASK) != 0) |
| 1073 |
&& ((decomposition & LOW_ZEROS_MASK) != 0) |
| 1074 |
{ |
| 1075 |
// Decomposition into two BMP characters: starter and non-starter |
| 1076 |
// Let's take the starter |
| 1077 |
head_last_c = char_from_u32(decomposition & 0x7FFF); |
| 1078 |
} else if decomposition == HANGUL_SYLLABLE_MARKER { |
| 1079 |
head_last_ce32 = FFFD_CE32; |
| 1080 |
} else { |
| 1081 |
break; |
| 1082 |
} |
| 1083 |
head_last_ok = true; |
| 1084 |
|
| 1085 |
let mut left_ce32 = CollationElement32::default(); |
| 1086 |
let mut right_ce32 = CollationElement32::default(); |
| 1087 |
let left_c; |
| 1088 |
let right_c; |
| 1089 |
|
| 1090 |
let decomposition = left_different.trie_val; |
| 1091 |
if (decomposition |
| 1092 |
& !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER)) |
| 1093 |
== 0 |
| 1094 |
{ |
| 1095 |
left_c = left_different.character(); |
| 1096 |
} else if ((decomposition & HIGH_ZEROS_MASK) != 0) |
| 1097 |
&& ((decomposition & LOW_ZEROS_MASK) != 0) |
| 1098 |
{ |
| 1099 |
// Decomposition into two BMP characters: starter and non-starter |
| 1100 |
// Let's take the starter |
| 1101 |
left_c = char_from_u32(decomposition & 0x7FFF); |
| 1102 |
} else if decomposition == HANGUL_SYLLABLE_MARKER { |
| 1103 |
left_c = '\u{0}'; |
| 1104 |
left_ce32 = FFFD_CE32; |
| 1105 |
} else { |
| 1106 |
break; |
| 1107 |
} |
| 1108 |
|
| 1109 |
let decomposition = right_different.trie_val; |
| 1110 |
if (decomposition |
| 1111 |
& !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER)) |
| 1112 |
== 0 |
| 1113 |
{ |
| 1114 |
right_c = right_different.character(); |
| 1115 |
} else if ((decomposition & HIGH_ZEROS_MASK) != 0) |
| 1116 |
&& ((decomposition & LOW_ZEROS_MASK) != 0) |
| 1117 |
{ |
| 1118 |
// Decomposition into two BMP characters: starter and non-starter |
| 1119 |
// Let's take the starter |
| 1120 |
right_c = char_from_u32(decomposition & 0x7FFF); |
| 1121 |
} else if decomposition == HANGUL_SYLLABLE_MARKER { |
| 1122 |
right_c = '\u{0}'; |
| 1123 |
right_ce32 = FFFD_CE32; |
| 1124 |
} else { |
| 1125 |
break; |
| 1126 |
} |
| 1127 |
|
| 1128 |
// The last character of the prefix is OK on the normalization |
| 1129 |
// level. Now let's check its ce32 unless it's a Hangul syllable, |
| 1130 |
// in which case `head_last_ce32` already is a non-default placeholder. |
| 1131 |
if head_last_ce32 == CollationElement32::default() { |
| 1132 |
head_last_ce32 = tailoring.ce32_for_char(head_last_c); |
| 1133 |
if head_last_ce32 == FALLBACK_CE32 { |
| 1134 |
head_last_ce32 = self.root.ce32_for_char(head_last_c); |
| 1135 |
} |
| 1136 |
if head_last_ce32.tag_checked() == Some(Tag::Contraction) |
| 1137 |
&& head_last_ce32.at_least_one_suffix_contains_starter() |
| 1138 |
{ |
| 1139 |
break; |
| 1140 |
} |
| 1141 |
} |
| 1142 |
// The first character of each suffix is OK on the normalization |
| 1143 |
// level. Now let's check their ce32s unless they are Hangul syllables. |
| 1144 |
if left_ce32 == CollationElement32::default() { |
| 1145 |
left_ce32 = tailoring.ce32_for_char(left_c); |
| 1146 |
if left_ce32 == FALLBACK_CE32 { |
| 1147 |
left_ce32 = self.root.ce32_for_char(left_c); |
| 1148 |
} |
| 1149 |
if left_ce32.tag_checked() == Some(Tag::Prefix) { |
| 1150 |
break; |
| 1151 |
} |
| 1152 |
} |
| 1153 |
if right_ce32 == CollationElement32::default() { |
| 1154 |
right_ce32 = tailoring.ce32_for_char(right_c); |
| 1155 |
if right_ce32 == FALLBACK_CE32 { |
| 1156 |
right_ce32 = self.root.ce32_for_char(right_c); |
| 1157 |
} |
| 1158 |
if right_ce32.tag_checked() == Some(Tag::Prefix) { |
| 1159 |
break; |
| 1160 |
} |
| 1161 |
} |
| 1162 |
if self.options.numeric() |
| 1163 |
&& head_last_ce32.tag_checked() == Some(Tag::Digit) |
| 1164 |
&& (left_ce32.tag_checked() == Some(Tag::Digit) |
| 1165 |
|| right_ce32.tag_checked() == Some(Tag::Digit)) |
| 1166 |
{ |
| 1167 |
break; |
| 1168 |
} |
| 1169 |
// We are at a good boundary! |
| 1170 |
break 'prefix; |
| 1171 |
} |
| 1172 |
} |
| 1173 |
} |
| 1174 |
let mut tail_first_c; |
| 1175 |
let mut tail_first_ce32; |
| 1176 |
let mut tail_first_ok; |
| 1177 |
loop { |
| 1178 |
// Take a step back. |
| 1179 |
left.prepend_upcoming_before_init(head_last.clone()); |
| 1180 |
right.prepend_upcoming_before_init(head_last.clone()); |
| 1181 |
|
| 1182 |
tail_first_c = head_last_c; |
| 1183 |
tail_first_ce32 = head_last_ce32; |
| 1184 |
tail_first_ok = head_last_ok; |
| 1185 |
|
| 1186 |
head_last_c = if let Some(head_last_c) = head_chars.next() { |
| 1187 |
head_last_c |
| 1188 |
} else { |
| 1189 |
// We need to step back beyond the start of the prefix. |
| 1190 |
// Treat as good boundary. |
| 1191 |
break 'prefix; |
| 1192 |
}; |
| 1193 |
let decomposition = norm_trie.get(head_last_c); |
| 1194 |
head_last = CharacterAndClassAndTrieValue::new_with_trie_val( |
| 1195 |
head_last_c, |
| 1196 |
decomposition, |
| 1197 |
); |
| 1198 |
head_last_ce32 = CollationElement32::default(); |
| 1199 |
head_last_ok = false; |
| 1200 |
|
| 1201 |
if (decomposition & !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER)) == 0 { |
| 1202 |
// Intentionally empty block to keep |
| 1203 |
// the same structure as in the cases |
| 1204 |
// where something happens here. |
| 1205 |
} else if ((decomposition & HIGH_ZEROS_MASK) != 0) |
| 1206 |
&& ((decomposition & LOW_ZEROS_MASK) != 0) |
| 1207 |
{ |
| 1208 |
// Decomposition into two BMP characters: starter and non-starter |
| 1209 |
// Let's take the starter |
| 1210 |
head_last_c = char_from_u32(decomposition & 0x7FFF); |
| 1211 |
} else if decomposition == HANGUL_SYLLABLE_MARKER { |
| 1212 |
head_last_ce32 = FFFD_CE32; |
| 1213 |
} else { |
| 1214 |
continue; |
| 1215 |
} |
| 1216 |
head_last_ok = true; |
| 1217 |
if !tail_first_ok { |
| 1218 |
continue; |
| 1219 |
} |
| 1220 |
// The last character of the prefix is OK on the normalization |
| 1221 |
// level. Now let's check its ce32 unless it's a Hangul syllable. |
| 1222 |
if head_last_ce32 == CollationElement32::default() { |
| 1223 |
head_last_ce32 = tailoring.ce32_for_char(head_last_c); |
| 1224 |
if head_last_ce32 == FALLBACK_CE32 { |
| 1225 |
head_last_ce32 = self.root.ce32_for_char(head_last_c); |
| 1226 |
} |
| 1227 |
if head_last_ce32.tag_checked() == Some(Tag::Contraction) |
| 1228 |
&& head_last_ce32.at_least_one_suffix_contains_starter() |
| 1229 |
{ |
| 1230 |
continue; |
| 1231 |
} |
| 1232 |
} |
| 1233 |
// Check this _after_ `head_last_ce32` to make sure |
| 1234 |
// `head_last_ce32` is initialized for the next loop round |
| 1235 |
// trip if applicable. |
| 1236 |
if tail_first_ce32 == CollationElement32::default() { |
| 1237 |
tail_first_ce32 = tailoring.ce32_for_char(tail_first_c); |
| 1238 |
if tail_first_ce32 == FALLBACK_CE32 { |
| 1239 |
tail_first_ce32 = self.root.ce32_for_char(tail_first_c); |
| 1240 |
} |
| 1241 |
} // else we already have a trie value from the previous loop iteration or we have Hangul syllable |
| 1242 |
if tail_first_ce32.tag_checked() == Some(Tag::Prefix) { |
| 1243 |
continue; |
| 1244 |
} |
| 1245 |
if self.options.numeric() |
| 1246 |
&& head_last_ce32.tag_checked() == Some(Tag::Digit) |
| 1247 |
&& tail_first_ce32.tag_checked() == Some(Tag::Digit) |
| 1248 |
{ |
| 1249 |
continue; |
| 1250 |
} |
| 1251 |
// We are at a good boundary! |
| 1252 |
break 'prefix; |
| 1253 |
} |
| 1254 |
} else { |
| 1255 |
// The prefix is empty |
| 1256 |
break 'prefix; |
| 1257 |
} |
| 1258 |
// Unreachable line |
| 1259 |
} |
| 1260 |
|
| 1261 |
// End identical prefix |
| 1262 |
|
| 1263 |
left.init(); |
| 1264 |
right.init(); |
| 1265 |
|
| 1266 |
loop { |
| 1267 |
let mut left_primary; |
| 1268 |
'left_primary_loop: loop { |
| 1269 |
let ce = left.next(); |
| 1270 |
left_primary = ce.primary(); |
| 1271 |
// TODO(#2008): Consider compiling out the variable handling when we know we aren't |
| 1272 |
// shifting variable CEs. |
| 1273 |
if !(left_primary < variable_top && left_primary > MERGE_SEPARATOR_PRIMARY) { |
| 1274 |
left_ces.push(ce); |
| 1275 |
} else { |
| 1276 |
// Variable CE, shift it to quaternary level. |
| 1277 |
// Ignore all following primary ignorables, and shift further variable CEs. |
| 1278 |
any_variable = true; |
| 1279 |
// Relative to ICU4C, the next line is hoisted out of the following loop |
| 1280 |
// in order to keep the variables called `ce` immutable to make it easier |
| 1281 |
// to reason about each assignment into `ce` resulting in exactly a single |
| 1282 |
// push into `left_ces`. |
| 1283 |
left_ces.push(ce.clone_with_non_primary_zeroed()); |
| 1284 |
loop { |
| 1285 |
// This loop is simpler than in ICU4C; unlike in C++, we get to break by label. |
| 1286 |
let ce = left.next(); |
| 1287 |
left_primary = ce.primary(); |
| 1288 |
if left_primary != 0 |
| 1289 |
&& !(left_primary < variable_top |
| 1290 |
&& left_primary > MERGE_SEPARATOR_PRIMARY) |
| 1291 |
{ |
| 1292 |
// Neither a primary ignorable nor a variable CE. |
| 1293 |
left_ces.push(ce); |
| 1294 |
break 'left_primary_loop; |
| 1295 |
} |
| 1296 |
// If `left_primary == 0`, the following line ignores a primary-ignorable. |
| 1297 |
// Otherwise, it shifts a variable CE. |
| 1298 |
left_ces.push(ce.clone_with_non_primary_zeroed()); |
| 1299 |
} |
| 1300 |
} |
| 1301 |
if left_primary != 0 { |
| 1302 |
break; |
| 1303 |
} |
| 1304 |
} |
| 1305 |
let mut right_primary; |
| 1306 |
'right_primary_loop: loop { |
| 1307 |
let ce = right.next(); |
| 1308 |
right_primary = ce.primary(); |
| 1309 |
// TODO(#2008): Consider compiling out the variable handling when we know we aren't |
| 1310 |
// shifting variable CEs. |
| 1311 |
if !(right_primary < variable_top && right_primary > MERGE_SEPARATOR_PRIMARY) { |
| 1312 |
right_ces.push(ce); |
| 1313 |
} else { |
| 1314 |
// Variable CE, shift it to quaternary level. |
| 1315 |
// Ignore all following primary ignorables, and shift further variable CEs. |
| 1316 |
any_variable = true; |
| 1317 |
// Relative to ICU4C, the next line is hoisted out of the following loop |
| 1318 |
// in order to keep the variables called `ce` immutable to make it easier |
| 1319 |
// to reason about each assignment into `ce` resulting in exactly a single |
| 1320 |
// push into `right_ces`. |
| 1321 |
right_ces.push(ce.clone_with_non_primary_zeroed()); |
| 1322 |
loop { |
| 1323 |
// This loop is simpler than in ICU4C; unlike in C++, we get to break by label. |
| 1324 |
let ce = right.next(); |
| 1325 |
right_primary = ce.primary(); |
| 1326 |
if right_primary != 0 |
| 1327 |
&& !(right_primary < variable_top |
| 1328 |
&& right_primary > MERGE_SEPARATOR_PRIMARY) |
| 1329 |
{ |
| 1330 |
// Neither a primary ignorable nor a variable CE. |
| 1331 |
right_ces.push(ce); |
| 1332 |
break 'right_primary_loop; |
| 1333 |
} |
| 1334 |
// If `right_primary == 0`, the following line ignores a primary-ignorable. |
| 1335 |
// Otherwise, it shifts a variable CE. |
| 1336 |
right_ces.push(ce.clone_with_non_primary_zeroed()); |
| 1337 |
} |
| 1338 |
} |
| 1339 |
if right_primary != 0 { |
| 1340 |
break; |
| 1341 |
} |
| 1342 |
} |
| 1343 |
if left_primary != right_primary { |
| 1344 |
if let Some(reordering) = &self.reordering { |
| 1345 |
left_primary = reordering.reorder(left_primary); |
| 1346 |
right_primary = reordering.reorder(right_primary); |
| 1347 |
} |
| 1348 |
if left_primary < right_primary { |
| 1349 |
return Ordering::Less; |
| 1350 |
} |
| 1351 |
return Ordering::Greater; |
| 1352 |
} |
| 1353 |
if left_primary == NO_CE_PRIMARY { |
| 1354 |
break; |
| 1355 |
} |
| 1356 |
} |
| 1357 |
|
| 1358 |
// Sadly, we end up pushing the sentinel value, which means these |
| 1359 |
// `SmallVec`s allocate more often than if we didn't actually |
| 1360 |
// store the sentinel. |
| 1361 |
debug_assert_eq!(left_ces.last(), Some(&NO_CE)); |
| 1362 |
debug_assert_eq!(right_ces.last(), Some(&NO_CE)); |
| 1363 |
|
| 1364 |
// Note: `unwrap_or_default` in the iterations below should never |
| 1365 |
// actually end up using the "_or_default" part, because the sentinel |
| 1366 |
// is in the `SmallVec`s. These could be changed to `unwrap()` if we |
| 1367 |
// preferred panic in case of a bug. |
| 1368 |
// TODO(#2009): Should we save one slot by not putting the sentinel in |
| 1369 |
// the `SmallVec`s? So far, the answer seems "no", as it would complicate |
| 1370 |
// the primary comparison above. |
| 1371 |
|
| 1372 |
// Compare the buffered secondary & tertiary weights. |
| 1373 |
// We might skip the secondary level but continue with the case level |
| 1374 |
// which is turned on separately. |
| 1375 |
if self.options.strength() >= Strength::Secondary { |
| 1376 |
if !self.options.backward_second_level() { |
| 1377 |
let mut left_iter = left_ces.iter(); |
| 1378 |
let mut right_iter = right_ces.iter(); |
| 1379 |
let mut left_secondary; |
| 1380 |
let mut right_secondary; |
| 1381 |
loop { |
| 1382 |
loop { |
| 1383 |
left_secondary = left_iter.next().unwrap_or_default().secondary(); |
| 1384 |
if left_secondary != 0 { |
| 1385 |
break; |
| 1386 |
} |
| 1387 |
} |
| 1388 |
loop { |
| 1389 |
right_secondary = right_iter.next().unwrap_or_default().secondary(); |
| 1390 |
if right_secondary != 0 { |
| 1391 |
break; |
| 1392 |
} |
| 1393 |
} |
| 1394 |
if left_secondary != right_secondary { |
| 1395 |
if left_secondary < right_secondary { |
| 1396 |
return Ordering::Less; |
| 1397 |
} |
| 1398 |
return Ordering::Greater; |
| 1399 |
} |
| 1400 |
if left_secondary == NO_CE_SECONDARY { |
| 1401 |
break; |
| 1402 |
} |
| 1403 |
} |
| 1404 |
} else { |
| 1405 |
let mut left_remaining = &left_ces[..]; |
| 1406 |
let mut right_remaining = &right_ces[..]; |
| 1407 |
loop { |
| 1408 |
if left_remaining.is_empty() { |
| 1409 |
debug_assert!(right_remaining.is_empty()); |
| 1410 |
break; |
| 1411 |
} |
| 1412 |
let (left_prefix, right_prefix) = { |
| 1413 |
let mut left_iter = left_remaining.iter(); |
| 1414 |
loop { |
| 1415 |
let left_primary = left_iter.next().unwrap_or_default().primary(); |
| 1416 |
if left_primary != 0 && left_primary <= MERGE_SEPARATOR_PRIMARY { |
| 1417 |
break; |
| 1418 |
} |
| 1419 |
debug_assert_ne!(left_primary, NO_CE_PRIMARY); |
| 1420 |
} |
| 1421 |
let left_new_remaining = left_iter.as_slice(); |
| 1422 |
// Index in range by construction |
| 1423 |
#[expect(clippy::indexing_slicing)] |
| 1424 |
let left_prefix = |
| 1425 |
&left_remaining[..left_remaining.len() - 1 - left_new_remaining.len()]; |
| 1426 |
left_remaining = left_new_remaining; |
| 1427 |
|
| 1428 |
let mut right_iter = right_remaining.iter(); |
| 1429 |
loop { |
| 1430 |
let right_primary = right_iter.next().unwrap_or_default().primary(); |
| 1431 |
if right_primary != 0 && right_primary <= MERGE_SEPARATOR_PRIMARY { |
| 1432 |
break; |
| 1433 |
} |
| 1434 |
debug_assert_ne!(right_primary, NO_CE_PRIMARY); |
| 1435 |
} |
| 1436 |
let right_new_remaining = right_iter.as_slice(); |
| 1437 |
// Index in range by construction |
| 1438 |
#[expect(clippy::indexing_slicing)] |
| 1439 |
let right_prefix = &right_remaining |
| 1440 |
[..right_remaining.len() - 1 - right_new_remaining.len()]; |
| 1441 |
right_remaining = right_new_remaining; |
| 1442 |
|
| 1443 |
(left_prefix, right_prefix) |
| 1444 |
}; |
| 1445 |
let mut left_iter = left_prefix.iter(); |
| 1446 |
let mut right_iter = right_prefix.iter(); |
| 1447 |
|
| 1448 |
let mut left_secondary; |
| 1449 |
let mut right_secondary; |
| 1450 |
loop { |
| 1451 |
loop { |
| 1452 |
left_secondary = left_iter.next_back().unwrap_or_default().secondary(); |
| 1453 |
if left_secondary != 0 { |
| 1454 |
break; |
| 1455 |
} |
| 1456 |
} |
| 1457 |
loop { |
| 1458 |
right_secondary = |
| 1459 |
right_iter.next_back().unwrap_or_default().secondary(); |
| 1460 |
if right_secondary != 0 { |
| 1461 |
break; |
| 1462 |
} |
| 1463 |
} |
| 1464 |
if left_secondary != right_secondary { |
| 1465 |
if left_secondary < right_secondary { |
| 1466 |
return Ordering::Less; |
| 1467 |
} |
| 1468 |
return Ordering::Greater; |
| 1469 |
} |
| 1470 |
if left_secondary == NO_CE_SECONDARY { |
| 1471 |
break; |
| 1472 |
} |
| 1473 |
} |
| 1474 |
} |
| 1475 |
} |
| 1476 |
} |
| 1477 |
|
| 1478 |
if self.options.case_level() { |
| 1479 |
let mut left_non_primary; |
| 1480 |
let mut right_non_primary; |
| 1481 |
let mut left_case; |
| 1482 |
let mut right_case; |
| 1483 |
let mut left_iter = left_ces.iter(); |
| 1484 |
let mut right_iter = right_ces.iter(); |
| 1485 |
if self.options.strength() == Strength::Primary { |
| 1486 |
// Primary+caseLevel: Ignore case level weights of primary ignorables. |
| 1487 |
// Otherwise we would get a-umlaut > a |
| 1488 |
// which is not desirable for accent-insensitive sorting. |
| 1489 |
// Check for (lower 32 bits) == 0 as well because variable CEs are stored |
| 1490 |
// with only primary weights. |
| 1491 |
loop { |
| 1492 |
loop { |
| 1493 |
let ce = left_iter.next().unwrap_or_default(); |
| 1494 |
left_non_primary = ce.non_primary(); |
| 1495 |
if !ce.either_half_zero() { |
| 1496 |
break; |
| 1497 |
} |
| 1498 |
} |
| 1499 |
left_case = left_non_primary.case(); |
| 1500 |
loop { |
| 1501 |
let ce = right_iter.next().unwrap_or_default(); |
| 1502 |
right_non_primary = ce.non_primary(); |
| 1503 |
if !ce.either_half_zero() { |
| 1504 |
break; |
| 1505 |
} |
| 1506 |
} |
| 1507 |
right_case = right_non_primary.case(); |
| 1508 |
// No need to handle NO_CE and MERGE_SEPARATOR specially: |
| 1509 |
// There is one case weight for each previous-level weight, |
| 1510 |
// so level length differences were handled there. |
| 1511 |
if left_case != right_case { |
| 1512 |
if !self.options.upper_first() { |
| 1513 |
if left_case < right_case { |
| 1514 |
return Ordering::Less; |
| 1515 |
} |
| 1516 |
return Ordering::Greater; |
| 1517 |
} |
| 1518 |
if left_case < right_case { |
| 1519 |
return Ordering::Greater; |
| 1520 |
} |
| 1521 |
return Ordering::Less; |
| 1522 |
} |
| 1523 |
if left_non_primary.secondary() == NO_CE_SECONDARY { |
| 1524 |
break; |
| 1525 |
} |
| 1526 |
} |
| 1527 |
} else { |
| 1528 |
// Secondary+caseLevel: By analogy with the above, |
| 1529 |
// ignore case level weights of secondary ignorables. |
| 1530 |
// |
| 1531 |
// Note: A tertiary CE has uppercase case bits (0.0.ut) |
| 1532 |
// to keep tertiary+caseFirst well-formed. |
| 1533 |
// |
| 1534 |
// Tertiary+caseLevel: Also ignore case level weights of secondary ignorables. |
| 1535 |
// Otherwise a tertiary CE's uppercase would be no greater than |
| 1536 |
// a primary/secondary CE's uppercase. |
| 1537 |
// (See UCA well-formedness condition 2.) |
| 1538 |
// We could construct a special case weight higher than uppercase, |
| 1539 |
// but it's simpler to always ignore case weights of secondary ignorables, |
| 1540 |
// turning 0.0.ut into 0.0.0.t. |
| 1541 |
// (See LDML Collation, Case Parameters.) |
| 1542 |
loop { |
| 1543 |
loop { |
| 1544 |
left_non_primary = left_iter.next().unwrap_or_default().non_primary(); |
| 1545 |
if left_non_primary.secondary() != 0 { |
| 1546 |
break; |
| 1547 |
} |
| 1548 |
} |
| 1549 |
left_case = left_non_primary.case(); |
| 1550 |
loop { |
| 1551 |
right_non_primary = right_iter.next().unwrap_or_default().non_primary(); |
| 1552 |
if right_non_primary.secondary() != 0 { |
| 1553 |
break; |
| 1554 |
} |
| 1555 |
} |
| 1556 |
right_case = right_non_primary.case(); |
| 1557 |
// No need to handle NO_CE and MERGE_SEPARATOR specially: |
| 1558 |
// There is one case weight for each previous-level weight, |
| 1559 |
// so level length differences were handled there. |
| 1560 |
if left_case != right_case { |
| 1561 |
if !self.options.upper_first() { |
| 1562 |
if left_case < right_case { |
| 1563 |
return Ordering::Less; |
| 1564 |
} |
| 1565 |
return Ordering::Greater; |
| 1566 |
} |
| 1567 |
if left_case < right_case { |
| 1568 |
return Ordering::Greater; |
| 1569 |
} |
| 1570 |
return Ordering::Less; |
| 1571 |
} |
| 1572 |
if left_non_primary.secondary() == NO_CE_SECONDARY { |
| 1573 |
break; |
| 1574 |
} |
| 1575 |
} |
| 1576 |
} |
| 1577 |
} |
| 1578 |
|
| 1579 |
if let Some(tertiary_mask) = self.options.tertiary_mask() { |
| 1580 |
let mut any_quaternaries = AnyQuaternaryAccumulator::new(); |
| 1581 |
let mut left_iter = left_ces.iter(); |
| 1582 |
let mut right_iter = right_ces.iter(); |
| 1583 |
loop { |
| 1584 |
let mut left_non_primary; |
| 1585 |
let mut left_tertiary; |
| 1586 |
loop { |
| 1587 |
left_non_primary = left_iter.next().unwrap_or_default().non_primary(); |
| 1588 |
any_quaternaries.accumulate(left_non_primary); |
| 1589 |
debug_assert!( |
| 1590 |
left_non_primary.tertiary() != 0 || left_non_primary.case_quaternary() == 0 |
| 1591 |
); |
| 1592 |
left_tertiary = left_non_primary.tertiary_case_quarternary(tertiary_mask); |
| 1593 |
if left_tertiary != 0 { |
| 1594 |
break; |
| 1595 |
} |
| 1596 |
} |
| 1597 |
|
| 1598 |
let mut right_non_primary; |
| 1599 |
let mut right_tertiary; |
| 1600 |
loop { |
| 1601 |
right_non_primary = right_iter.next().unwrap_or_default().non_primary(); |
| 1602 |
any_quaternaries.accumulate(right_non_primary); |
| 1603 |
debug_assert!( |
| 1604 |
right_non_primary.tertiary() != 0 |
| 1605 |
|| right_non_primary.case_quaternary() == 0 |
| 1606 |
); |
| 1607 |
right_tertiary = right_non_primary.tertiary_case_quarternary(tertiary_mask); |
| 1608 |
if right_tertiary != 0 { |
| 1609 |
break; |
| 1610 |
} |
| 1611 |
} |
| 1612 |
|
| 1613 |
if left_tertiary != right_tertiary { |
| 1614 |
if self.options.upper_first() { |
| 1615 |
// Pass through NO_CE and keep real tertiary weights larger than that. |
| 1616 |
// Do not change the artificial uppercase weight of a tertiary CE (0.0.ut), |
| 1617 |
// to keep tertiary CEs well-formed. |
| 1618 |
// Their case+tertiary weights must be greater than those of |
| 1619 |
// primary and secondary CEs. |
| 1620 |
// Magic numbers from ICU4C. |
| 1621 |
if left_tertiary > NO_CE_TERTIARY { |
| 1622 |
if left_non_primary.secondary() != 0 { |
| 1623 |
left_tertiary ^= 0xC000; |
| 1624 |
} else { |
| 1625 |
left_tertiary += 0x4000; |
| 1626 |
} |
| 1627 |
} |
| 1628 |
if right_tertiary > NO_CE_TERTIARY { |
| 1629 |
if right_non_primary.secondary() != 0 { |
| 1630 |
right_tertiary ^= 0xC000; |
| 1631 |
} else { |
| 1632 |
right_tertiary += 0x4000; |
| 1633 |
} |
| 1634 |
} |
| 1635 |
} |
| 1636 |
if left_tertiary < right_tertiary { |
| 1637 |
return Ordering::Less; |
| 1638 |
} |
| 1639 |
return Ordering::Greater; |
| 1640 |
} |
| 1641 |
|
| 1642 |
if left_tertiary == NO_CE_TERTIARY { |
| 1643 |
break; |
| 1644 |
} |
| 1645 |
} |
| 1646 |
if !any_variable && !any_quaternaries.has_quaternary() { |
| 1647 |
return Ordering::Equal; |
| 1648 |
} |
| 1649 |
} else { |
| 1650 |
return Ordering::Equal; |
| 1651 |
} |
| 1652 |
|
| 1653 |
if self.options.strength() <= Strength::Tertiary { |
| 1654 |
return Ordering::Equal; |
| 1655 |
} |
| 1656 |
|
| 1657 |
let mut left_iter = left_ces.iter(); |
| 1658 |
let mut right_iter = right_ces.iter(); |
| 1659 |
loop { |
| 1660 |
let mut left_quaternary; |
| 1661 |
loop { |
| 1662 |
let ce = left_iter.next().unwrap_or_default(); |
| 1663 |
if ce.tertiary_ignorable() { |
| 1664 |
left_quaternary = ce.primary(); |
| 1665 |
} else { |
| 1666 |
left_quaternary = ce.quaternary(); |
| 1667 |
} |
| 1668 |
if left_quaternary != 0 { |
| 1669 |
break; |
| 1670 |
} |
| 1671 |
} |
| 1672 |
let mut right_quaternary; |
| 1673 |
loop { |
| 1674 |
let ce = right_iter.next().unwrap_or_default(); |
| 1675 |
if ce.tertiary_ignorable() { |
| 1676 |
right_quaternary = ce.primary(); |
| 1677 |
} else { |
| 1678 |
right_quaternary = ce.quaternary(); |
| 1679 |
} |
| 1680 |
if right_quaternary != 0 { |
| 1681 |
break; |
| 1682 |
} |
| 1683 |
} |
| 1684 |
if left_quaternary != right_quaternary { |
| 1685 |
if let Some(reordering) = &self.reordering { |
| 1686 |
left_quaternary = reordering.reorder(left_quaternary); |
| 1687 |
right_quaternary = reordering.reorder(right_quaternary); |
| 1688 |
} |
| 1689 |
if left_quaternary < right_quaternary { |
| 1690 |
return Ordering::Less; |
| 1691 |
} |
| 1692 |
return Ordering::Greater; |
| 1693 |
} |
| 1694 |
if left_quaternary == NO_CE_PRIMARY { |
| 1695 |
break; |
| 1696 |
} |
| 1697 |
} |
| 1698 |
|
| 1699 |
Ordering::Equal |
| 1700 |
} |
| 1701 |
|
| 1702 |
fn sort_key_levels(&self) -> u8 { |
| 1703 |
#[expect(clippy::indexing_slicing)] |
| 1704 |
let mut levels = LEVEL_MASKS[self.options.strength() as usize]; |
| 1705 |
if self.options.case_level() { |
| 1706 |
levels |= CASE_LEVEL_FLAG; |
| 1707 |
} |
| 1708 |
levels |
| 1709 |
} |
| 1710 |
|
| 1711 |
/// Given valid UTF-8, write the sort key bytes up to the collator's strength. |
| 1712 |
/// |
| 1713 |
/// The bytes are written to an implementor of [`CollationKeySink`], a no-std version of `std::io::Write`. |
| 1714 |
/// This trait is currently unstable, but it is implemented by `Vec<u8>`, `VecDeque<u8>`, |
| 1715 |
/// `SmallVec<[u8; N]>`, and `&mut [u8]` (returning an error if the slice is too small). |
| 1716 |
/// |
| 1717 |
/// If two sort keys generated at the same strength are compared bytewise, the result is |
| 1718 |
/// the same as a collation comparison of the original strings at that strength. |
| 1719 |
/// |
| 1720 |
/// For identical strength, the UTF-8 NFD normalization is appended for breaking ties. |
| 1721 |
/// |
| 1722 |
/// No terminating zero byte is written to the output, so the output is not a valid C |
| 1723 |
/// string, but the caller may append a zero afterward if a C string is desired. |
| 1724 |
/// |
| 1725 |
/// ⚠️ Generating a sort key is expensive relative to comparison because to compare, the |
| 1726 |
/// collator skips identical prefixes before doing more complex comparison. Only use sort |
| 1727 |
/// keys if you expect to compare them many times so as to amortize the cost of generating |
| 1728 |
/// them. Measurement of this performance trade-off would be a good idea. |
| 1729 |
/// |
| 1730 |
/// ⚠️ Sort keys, if stored durably, should be presumed to be invalidated by a CLDR update, a |
| 1731 |
/// new version of Unicode, or an update to the ICU4X code. Applications using sort keys |
| 1732 |
/// *must* be prepared to recompute them if required and should take the performance of |
| 1733 |
/// such an operation into account when deciding to use sort keys. |
| 1734 |
/// |
| 1735 |
/// ⚠️ If you should store sort keys in a database that is or becomes so large that |
| 1736 |
/// regenerating sort keys becomes impractical, you should not expect ICU4X to support your |
| 1737 |
/// using an older, frozen copy of the sort key generation algorithm with a later version |
| 1738 |
/// of the library. |
| 1739 |
/// |
| 1740 |
/// # Example |
| 1741 |
/// |
| 1742 |
/// ``` |
| 1743 |
/// use icu::collator::{ |
| 1744 |
/// Collator, |
| 1745 |
/// options::{CollatorOptions, Strength}, |
| 1746 |
/// }; |
| 1747 |
/// use icu::locale::locale; |
| 1748 |
/// let locale = locale!("utf").into(); |
| 1749 |
/// let mut options = CollatorOptions::default(); |
| 1750 |
/// options.strength = Some(Strength::Primary); |
| 1751 |
/// let collator = Collator::try_new(locale, options).unwrap(); |
| 1752 |
/// |
| 1753 |
/// let mut k1 = Vec::new(); |
| 1754 |
/// let Ok(()) = collator.write_sort_key_to("hello", &mut k1); |
| 1755 |
/// let mut k2 = Vec::new(); |
| 1756 |
/// let Ok(()) = collator.write_sort_key_to("Héłłö", &mut k2); |
| 1757 |
/// assert_eq!(k1, k2); |
| 1758 |
/// ``` |
| 1759 |
pub fn write_sort_key_to<S>(&self, s: &str, sink: &mut S) -> Result<S::Output, S::Error> |
| 1760 |
where |
| 1761 |
S: CollationKeySink + ?Sized, |
| 1762 |
S::State: Default, |
| 1763 |
{ |
| 1764 |
self.write_sort_key_impl(s.chars(), sink) |
| 1765 |
} |
| 1766 |
|
| 1767 |
/// Given potentially invalid UTF-8, write the sort key bytes up to the collator's strength. |
| 1768 |
/// |
| 1769 |
/// For further details, see [`Self::write_sort_key_to`]. |
| 1770 |
pub fn write_sort_key_utf8_to<S>(&self, s: &[u8], sink: &mut S) -> Result<S::Output, S::Error> |
| 1771 |
where |
| 1772 |
S: CollationKeySink + ?Sized, |
| 1773 |
S::State: Default, |
| 1774 |
{ |
| 1775 |
self.write_sort_key_impl(s.chars(), sink) |
| 1776 |
} |
| 1777 |
|
| 1778 |
/// Given potentially invalid UTF-16, write the sort key bytes up to the collator's strength. |
| 1779 |
/// |
| 1780 |
/// For further details, see [`Self::write_sort_key_to`]. |
| 1781 |
pub fn write_sort_key_utf16_to<S>(&self, s: &[u16], sink: &mut S) -> Result<S::Output, S::Error> |
| 1782 |
where |
| 1783 |
S: CollationKeySink + ?Sized, |
| 1784 |
S::State: Default, |
| 1785 |
{ |
| 1786 |
self.write_sort_key_impl(s.chars(), sink) |
| 1787 |
} |
| 1788 |
|
| 1789 |
fn write_sort_key_impl<I, S>(&self, iter: I, sink: &mut S) -> Result<S::Output, S::Error> |
| 1790 |
where |
| 1791 |
I: Iterator<Item = char> + Clone, |
| 1792 |
S: CollationKeySink + ?Sized, |
| 1793 |
S::State: Default, |
| 1794 |
{ |
| 1795 |
let identical = if self.options.strength() == Strength::Identical { |
| 1796 |
Some(iter.clone()) |
| 1797 |
} else { |
| 1798 |
None |
| 1799 |
}; |
| 1800 |
|
| 1801 |
let mut state = S::State::default(); |
| 1802 |
match self.reordering { |
| 1803 |
Some(r) => self.write_sort_key_up_to_quaternary(iter, sink, &mut state, r)?, |
| 1804 |
None => self.write_sort_key_up_to_quaternary(iter, sink, &mut state, NoReorder)?, |
| 1805 |
} |
| 1806 |
|
| 1807 |
if let Some(iter) = identical { |
| 1808 |
let nfd = |
| 1809 |
DecomposingNormalizerBorrowed::new_with_data(self.decompositions, self.tables); |
| 1810 |
sink.write_byte(&mut state, LEVEL_SEPARATOR_BYTE)?; |
| 1811 |
|
| 1812 |
let iter = nfd.normalize_iter(iter); |
| 1813 |
write_identical_level(iter, sink, &mut state)?; |
| 1814 |
} |
| 1815 |
|
| 1816 |
sink.finish(state) |
| 1817 |
} |
| 1818 |
|
| 1819 |
/// Write the sort key bytes up to the collator's strength. |
| 1820 |
/// |
| 1821 |
/// Optionally write the case level. Separate levels with the `LEVEL_SEPARATOR_BYTE`, but |
| 1822 |
/// do not write a terminating zero as with a C string. |
| 1823 |
fn write_sort_key_up_to_quaternary<I, S, R>( |
| 1824 |
&self, |
| 1825 |
iter: I, |
| 1826 |
sink: &mut S, |
| 1827 |
state: &mut S::State, |
| 1828 |
reorder: R, |
| 1829 |
) -> Result<(), S::Error> |
| 1830 |
where |
| 1831 |
I: Iterator<Item = char>, |
| 1832 |
S: CollationKeySink + ?Sized, |
| 1833 |
R: Reorder, |
| 1834 |
{ |
| 1835 |
// This algorithm comes from `CollationKeys::writeSortKeyUpToQuaternary` in ICU4C. |
| 1836 |
let levels = self.sort_key_levels(); |
| 1837 |
|
| 1838 |
let mut iter = CollationElements::new( |
| 1839 |
iter, |
| 1840 |
self.root, |
| 1841 |
self.tailoring_or_root(), |
| 1842 |
self.jamo.as_array(), |
| 1843 |
&self.diacritics.secondaries, |
| 1844 |
self.decompositions, |
| 1845 |
self.tables, |
| 1846 |
self.numeric_primary(), |
| 1847 |
self.options.lithuanian_dot_above(), |
| 1848 |
); |
| 1849 |
iter.init(); |
| 1850 |
let variable_top = self.variable_top(); |
| 1851 |
|
| 1852 |
let tertiary_mask = self.options.tertiary_mask().unwrap_or_default(); |
| 1853 |
|
| 1854 |
let mut cases = SortKeyLevel::default(); |
| 1855 |
let mut secondaries = SortKeyLevel::default(); |
| 1856 |
let mut tertiaries = SortKeyLevel::default(); |
| 1857 |
let mut quaternaries = SortKeyLevel::default(); |
| 1858 |
|
| 1859 |
let mut prev_reordered_primary = 0; |
| 1860 |
let mut common_cases = 0usize; |
| 1861 |
let mut common_secondaries = 0usize; |
| 1862 |
let mut common_tertiaries = 0usize; |
| 1863 |
let mut common_quaternaries = 0usize; |
| 1864 |
let mut prev_secondary = 0; |
| 1865 |
let mut sec_segment_start = 0; |
| 1866 |
|
| 1867 |
loop { |
| 1868 |
let mut ce = iter.next(); |
| 1869 |
let mut p = ce.primary(); |
| 1870 |
if p < variable_top && p > MERGE_SEPARATOR_PRIMARY { |
| 1871 |
// Variable CE, shift it to quaternary level. Ignore all following primary |
| 1872 |
// ignorables, and shift further variable CEs. |
| 1873 |
if common_quaternaries != 0 { |
| 1874 |
common_quaternaries -= 1; |
| 1875 |
while common_quaternaries >= QUAT_COMMON[WEIGHT_MAX_COUNT] as _ { |
| 1876 |
quaternaries.append_byte(QUAT_COMMON[WEIGHT_MIDDLE]); |
| 1877 |
common_quaternaries -= QUAT_COMMON[WEIGHT_MAX_COUNT] as usize; |
| 1878 |
} |
| 1879 |
// Shifted primary weights are lower than the common weight. |
| 1880 |
quaternaries.append_byte(QUAT_COMMON[WEIGHT_LOW] + common_quaternaries as u8); |
| 1881 |
common_quaternaries = 0; |
| 1882 |
} |
| 1883 |
|
| 1884 |
loop { |
| 1885 |
if levels & QUATERNARY_LEVEL_FLAG != 0 { |
| 1886 |
p = reorder.reorder(p); |
| 1887 |
if (p >> 24) as u8 >= QUAT_SHIFTED_LIMIT_BYTE { |
| 1888 |
// Prevent shifted primary lead bytes from overlapping with the |
| 1889 |
// common compression range. |
| 1890 |
quaternaries.append_byte(QUAT_SHIFTED_LIMIT_BYTE); |
| 1891 |
} |
| 1892 |
quaternaries.append_weight_32(p); |
| 1893 |
} |
| 1894 |
loop { |
| 1895 |
ce = iter.next(); |
| 1896 |
p = ce.primary(); |
| 1897 |
if p != 0 { |
| 1898 |
break; |
| 1899 |
} |
| 1900 |
} |
| 1901 |
if !(p < variable_top && p > MERGE_SEPARATOR_PRIMARY) { |
| 1902 |
break; |
| 1903 |
} |
| 1904 |
} |
| 1905 |
} |
| 1906 |
|
| 1907 |
// ce could be primary ignorable, or NO_CE, or the merge separator, or a regular |
| 1908 |
// primary CE, but it is not variable. If ce == NO_CE, then write nothing for the |
| 1909 |
// primary level but terminate compression on all levels and then exit the loop. |
| 1910 |
if p > NO_CE_PRIMARY && levels & PRIMARY_LEVEL_FLAG != 0 { |
| 1911 |
// Test the un-reordered primary for compressibility. |
| 1912 |
let is_compressible = self.special_primaries.is_compressible((p >> 24) as _); |
| 1913 |
p = reorder.reorder(p); |
| 1914 |
let p1 = (p >> 24) as u8; |
| 1915 |
if !is_compressible || p1 != (prev_reordered_primary >> 24) as u8 { |
| 1916 |
if prev_reordered_primary != 0 { |
| 1917 |
if p < prev_reordered_primary { |
| 1918 |
// No primary compression terminator at the end of the level or |
| 1919 |
// merged segment. |
| 1920 |
if p1 > MERGE_SEPARATOR_BYTE { |
| 1921 |
sink.write(state, &[PRIMARY_COMPRESSION_LOW_BYTE])?; |
| 1922 |
} |
| 1923 |
} else { |
| 1924 |
sink.write(state, &[PRIMARY_COMPRESSION_HIGH_BYTE])?; |
| 1925 |
} |
| 1926 |
} |
| 1927 |
sink.write_byte(state, p1)?; |
| 1928 |
prev_reordered_primary = if is_compressible { p } else { 0 }; |
| 1929 |
} |
| 1930 |
|
| 1931 |
let p2 = (p >> 16) as u8; |
| 1932 |
if p2 != 0 { |
| 1933 |
let (b0, b1, b2) = (p2, (p >> 8) as _, p as _); |
| 1934 |
sink.write_byte(state, b0)?; |
| 1935 |
if b1 != 0 { |
| 1936 |
sink.write_byte(state, b1)?; |
| 1937 |
if b2 != 0 { |
| 1938 |
sink.write_byte(state, b2)?; |
| 1939 |
} |
| 1940 |
} |
| 1941 |
} |
| 1942 |
} |
| 1943 |
|
| 1944 |
let non_primary = ce.non_primary(); |
| 1945 |
if non_primary.ignorable() { |
| 1946 |
continue; // completely ignorable, no secondary/case/tertiary/quaternary |
| 1947 |
} |
| 1948 |
|
| 1949 |
macro_rules! handle_common { |
| 1950 |
($key:ident, $w:ident, $common:ident, $weights:ident, $lim:expr) => { |
| 1951 |
if $common != 0 { |
| 1952 |
$common -= 1; |
| 1953 |
while $common >= $weights[WEIGHT_MAX_COUNT] as _ { |
| 1954 |
$key.append_byte($weights[WEIGHT_MIDDLE]); |
| 1955 |
$common -= $weights[WEIGHT_MAX_COUNT] as usize; |
| 1956 |
} |
| 1957 |
let b = if $w < $lim { |
| 1958 |
$weights[WEIGHT_LOW] + ($common as u8) |
| 1959 |
} else { |
| 1960 |
$weights[WEIGHT_HIGH] - ($common as u8) |
| 1961 |
}; |
| 1962 |
$key.append_byte(b); |
| 1963 |
$common = 0; |
| 1964 |
} |
| 1965 |
}; |
| 1966 |
($key:ident, $w:ident, $common:ident, $weights:ident) => { |
| 1967 |
handle_common!($key, $w, $common, $weights, COMMON_WEIGHT16); |
| 1968 |
}; |
| 1969 |
} |
| 1970 |
|
| 1971 |
if levels & SECONDARY_LEVEL_FLAG != 0 { |
| 1972 |
let s = non_primary.secondary(); |
| 1973 |
if s == 0 { |
| 1974 |
// secondary ignorable |
| 1975 |
} else if s == COMMON_WEIGHT16 |
| 1976 |
&& (!self.options.backward_second_level() || p != MERGE_SEPARATOR_PRIMARY) |
| 1977 |
{ |
| 1978 |
// s is a common secondary weight, and backwards-secondary is off or the ce |
| 1979 |
// is not the merge separator. |
| 1980 |
common_secondaries += 1; |
| 1981 |
} else if !self.options.backward_second_level() { |
| 1982 |
handle_common!(secondaries, s, common_secondaries, SEC_COMMON); |
| 1983 |
secondaries.append_weight_16(s); |
| 1984 |
} else { |
| 1985 |
if common_secondaries != 0 { |
| 1986 |
common_secondaries -= 1; |
| 1987 |
// Append reverse weights. The level will be re-reversed later. |
| 1988 |
let remainder = common_secondaries % SEC_COMMON[WEIGHT_MAX_COUNT] as usize; |
| 1989 |
let b = if prev_secondary < COMMON_WEIGHT16 { |
| 1990 |
SEC_COMMON[WEIGHT_LOW] + remainder as u8 |
| 1991 |
} else { |
| 1992 |
SEC_COMMON[WEIGHT_HIGH] - remainder as u8 |
| 1993 |
}; |
| 1994 |
secondaries.append_byte(b); |
| 1995 |
common_secondaries -= remainder; |
| 1996 |
// common_secondaries is now a multiple of SEC_COMMON[WEIGHT_MAX_COUNT] |
| 1997 |
while common_secondaries > 0 { |
| 1998 |
// same as >= SEC_COMMON[WEIGHT_MAX_COUNT] |
| 1999 |
secondaries.append_byte(SEC_COMMON[WEIGHT_MIDDLE]); |
| 2000 |
common_secondaries -= SEC_COMMON[WEIGHT_MAX_COUNT] as usize; |
| 2001 |
} |
| 2002 |
// commonSecondaries == 0 |
| 2003 |
} |
| 2004 |
if 0 < p && p <= MERGE_SEPARATOR_PRIMARY { |
| 2005 |
// The backwards secondary level compares secondary weights backwards |
| 2006 |
// within segments separated by the merge separator (U+FFFE). |
| 2007 |
let secs = &mut secondaries.buf; |
| 2008 |
if let Some(last) = secs.len().checked_sub(1) |
| 2009 |
&& sec_segment_start < last |
| 2010 |
{ |
| 2011 |
let mut q = sec_segment_start; |
| 2012 |
let mut r = last; |
| 2013 |
|
| 2014 |
// these indices start at valid values and we stop when they cross |
| 2015 |
#[expect(clippy::indexing_slicing)] |
| 2016 |
while q < r { |
| 2017 |
let b = secs[q]; |
| 2018 |
secs[q] = secs[r]; |
| 2019 |
q += 1; |
| 2020 |
secs[r] = b; |
| 2021 |
r -= 1; |
| 2022 |
} |
| 2023 |
} |
| 2024 |
let b = if p == NO_CE_PRIMARY { |
| 2025 |
LEVEL_SEPARATOR_BYTE |
| 2026 |
} else { |
| 2027 |
MERGE_SEPARATOR_BYTE |
| 2028 |
}; |
| 2029 |
secondaries.append_byte(b); |
| 2030 |
prev_secondary = 0; |
| 2031 |
sec_segment_start = secondaries.len(); |
| 2032 |
} else { |
| 2033 |
secondaries.append_reverse_weight_16(s); |
| 2034 |
prev_secondary = s; |
| 2035 |
} |
| 2036 |
} |
| 2037 |
} |
| 2038 |
|
| 2039 |
if levels & CASE_LEVEL_FLAG != 0 { |
| 2040 |
if self.options.strength() == Strength::Primary && p == 0 |
| 2041 |
|| non_primary.bits() <= 0xffff |
| 2042 |
{ |
| 2043 |
// Primary+caseLevel: Ignore case level weights of primary ignorables. |
| 2044 |
// Otherwise: Ignore case level weights of secondary ignorables. For |
| 2045 |
// details see the comments in the CollationCompare class. |
| 2046 |
} else { |
| 2047 |
// case bits & tertiary lead byte |
| 2048 |
let mut c = ((non_primary.bits() >> 8) & 0xff) as u8; |
| 2049 |
debug_assert_ne!(c & 0xc0, 0xc0); |
| 2050 |
if c & 0xc0 == 0 && c > LEVEL_SEPARATOR_BYTE { |
| 2051 |
common_cases += 1; |
| 2052 |
} else { |
| 2053 |
if !self.options.upper_first() { |
| 2054 |
// lower first: Compress common weights to nibbles 1..7..13, |
| 2055 |
// mixed=14, upper=15. If there are only common (=lowest) weights |
| 2056 |
// in the whole level, then we need not write anything. Level |
| 2057 |
// length differences are handled already on the next-higher level. |
| 2058 |
if common_cases != 0 && (c > LEVEL_SEPARATOR_BYTE || !cases.is_empty()) |
| 2059 |
{ |
| 2060 |
common_cases -= 1; |
| 2061 |
while common_cases >= CASE_LOWER_FIRST_COMMON[WEIGHT_MAX_COUNT] as _ |
| 2062 |
{ |
| 2063 |
cases.append_byte(CASE_LOWER_FIRST_COMMON[WEIGHT_MIDDLE] << 4); |
| 2064 |
common_cases -= |
| 2065 |
CASE_LOWER_FIRST_COMMON[WEIGHT_MAX_COUNT] as usize; |
| 2066 |
} |
| 2067 |
let b = if c <= LEVEL_SEPARATOR_BYTE { |
| 2068 |
CASE_LOWER_FIRST_COMMON[WEIGHT_LOW] + common_cases as u8 |
| 2069 |
} else { |
| 2070 |
CASE_LOWER_FIRST_COMMON[WEIGHT_HIGH] - common_cases as u8 |
| 2071 |
}; |
| 2072 |
cases.append_byte(b << 4); |
| 2073 |
common_cases = 0; |
| 2074 |
} |
| 2075 |
if c > LEVEL_SEPARATOR_BYTE { |
| 2076 |
// 14 or 15 |
| 2077 |
c = (CASE_LOWER_FIRST_COMMON[WEIGHT_HIGH] + (c >> 6)) << 4; |
| 2078 |
} |
| 2079 |
} else { |
| 2080 |
// upper first: Compress common weights to nibbles 3..15, mixed=2, |
| 2081 |
// upper=1. The compressed common case weights only go up from the |
| 2082 |
// "low" value because with upperFirst the common weight is the |
| 2083 |
// highest one. |
| 2084 |
if common_cases != 0 { |
| 2085 |
common_cases -= 1; |
| 2086 |
while common_cases >= CASE_UPPER_FIRST_COMMON[WEIGHT_MAX_COUNT] as _ |
| 2087 |
{ |
| 2088 |
cases.append_byte(CASE_UPPER_FIRST_COMMON[WEIGHT_LOW] << 4); |
| 2089 |
common_cases -= |
| 2090 |
CASE_UPPER_FIRST_COMMON[WEIGHT_MAX_COUNT] as usize; |
| 2091 |
} |
| 2092 |
cases.append_byte( |
| 2093 |
(CASE_UPPER_FIRST_COMMON[WEIGHT_LOW] + common_cases as u8) << 4, |
| 2094 |
); |
| 2095 |
common_cases = 0; |
| 2096 |
} |
| 2097 |
if c > LEVEL_SEPARATOR_BYTE { |
| 2098 |
// 2 or 1 |
| 2099 |
c = (CASE_UPPER_FIRST_COMMON[WEIGHT_LOW] - (c >> 6)) << 4; |
| 2100 |
} |
| 2101 |
} |
| 2102 |
// c is a separator byte 01 or a left-shifted nibble 0x10, 0x20, ... |
| 2103 |
// 0xf0. |
| 2104 |
cases.append_byte(c); |
| 2105 |
} |
| 2106 |
} |
| 2107 |
} |
| 2108 |
|
| 2109 |
if levels & TERTIARY_LEVEL_FLAG != 0 { |
| 2110 |
let mut t = non_primary.tertiary_case_quarternary(tertiary_mask); |
| 2111 |
debug_assert_ne!(non_primary.bits() & 0xc000, 0xc000); |
| 2112 |
if t == COMMON_WEIGHT16 { |
| 2113 |
common_tertiaries += 1; |
| 2114 |
} else if tertiary_mask & 0x8000 == 0 { |
| 2115 |
// Tertiary weights without case bits. Move lead bytes 06..3F to C6..FF |
| 2116 |
// for a large common-weight range. |
| 2117 |
handle_common!(tertiaries, t, common_tertiaries, TER_ONLY_COMMON); |
| 2118 |
if t > COMMON_WEIGHT16 { |
| 2119 |
t += 0xc000; |
| 2120 |
} |
| 2121 |
tertiaries.append_weight_16(t); |
| 2122 |
} else if !self.options.upper_first() { |
| 2123 |
// Tertiary weights with caseFirst=lowerFirst. Move lead bytes 06..BF to |
| 2124 |
// 46..FF for the common-weight range. |
| 2125 |
handle_common!(tertiaries, t, common_tertiaries, TER_LOWER_FIRST_COMMON); |
| 2126 |
if t > COMMON_WEIGHT16 { |
| 2127 |
t += 0x4000; |
| 2128 |
} |
| 2129 |
tertiaries.append_weight_16(t); |
| 2130 |
} else { |
| 2131 |
// Tertiary weights with caseFirst=upperFirst. Do not change the |
| 2132 |
// artificial uppercase weight of a tertiary CE (0.0.ut), to keep tertiary |
| 2133 |
// CEs well-formed. Their case+tertiary weights must be greater than those |
| 2134 |
// of primary and secondary CEs. |
| 2135 |
// |
| 2136 |
// Separator 01 -> 01 (unchanged) |
| 2137 |
// Lowercase 02..04 -> 82..84 (includes uncased) |
| 2138 |
// Common weight 05 -> 85..C5 (common-weight compression range) |
| 2139 |
// Lowercase 06..3F -> C6..FF |
| 2140 |
// Mixed case 42..7F -> 42..7F |
| 2141 |
// Uppercase 82..BF -> 02..3F |
| 2142 |
// Tertiary CE 86..BF -> C6..FF |
| 2143 |
if t <= NO_CE_TERTIARY { |
| 2144 |
// Keep separators unchanged. |
| 2145 |
} else if non_primary.bits() > 0xffff { |
| 2146 |
// Invert case bits of primary & secondary CEs. |
| 2147 |
t ^= 0xc000; |
| 2148 |
if t < (TER_UPPER_FIRST_COMMON[WEIGHT_HIGH] as u16) << 8 { |
| 2149 |
t -= 0x4000; |
| 2150 |
} |
| 2151 |
} else { |
| 2152 |
// Keep uppercase bits of tertiary CEs. |
| 2153 |
debug_assert!((0x8600..=0xbfff).contains(&t)); |
| 2154 |
t += 0x4000; |
| 2155 |
} |
| 2156 |
handle_common!( |
| 2157 |
tertiaries, |
| 2158 |
t, |
| 2159 |
common_tertiaries, |
| 2160 |
TER_UPPER_FIRST_COMMON, |
| 2161 |
(TER_UPPER_FIRST_COMMON[WEIGHT_LOW] as u16) << 8 |
| 2162 |
); |
| 2163 |
tertiaries.append_weight_16(t); |
| 2164 |
} |
| 2165 |
} |
| 2166 |
|
| 2167 |
if levels & QUATERNARY_LEVEL_FLAG != 0 { |
| 2168 |
let q = (non_primary.bits() & 0xffff) as u16; |
| 2169 |
if q & 0xc0 == 0 && q > NO_CE_QUATERNARY { |
| 2170 |
common_quaternaries += 1; |
| 2171 |
} else if q == NO_CE_QUATERNARY |
| 2172 |
&& self.options.alternate_handling() == AlternateHandling::NonIgnorable |
| 2173 |
&& quaternaries.is_empty() |
| 2174 |
{ |
| 2175 |
// If alternate=non-ignorable and there are only common quaternary weights, |
| 2176 |
// then we need not write anything. The only weights greater than the |
| 2177 |
// merge separator and less than the common weight are shifted primary |
| 2178 |
// weights, which are not generated for alternate=non-ignorable. There are |
| 2179 |
// also exactly as many quaternary weights as tertiary weights, so level |
| 2180 |
// length differences are handled already on tertiary level. Any |
| 2181 |
// above-common quaternary weight will compare greater regardless. |
| 2182 |
quaternaries.append_byte(LEVEL_SEPARATOR_BYTE); |
| 2183 |
} else { |
| 2184 |
let q = if q == NO_CE_QUATERNARY { |
| 2185 |
LEVEL_SEPARATOR_BYTE |
| 2186 |
} else { |
| 2187 |
(0xfc + ((q >> 6) & 3)) as u8 |
| 2188 |
}; |
| 2189 |
handle_common!( |
| 2190 |
quaternaries, |
| 2191 |
q, |
| 2192 |
common_quaternaries, |
| 2193 |
QUAT_COMMON, |
| 2194 |
QUAT_COMMON[WEIGHT_LOW] |
| 2195 |
); |
| 2196 |
quaternaries.append_byte(q); |
| 2197 |
} |
| 2198 |
} |
| 2199 |
|
| 2200 |
if (non_primary.bits() >> 24) as u8 == LEVEL_SEPARATOR_BYTE { |
| 2201 |
break; // ce == NO_CE |
| 2202 |
} |
| 2203 |
} |
| 2204 |
|
| 2205 |
macro_rules! write_level { |
| 2206 |
($key:ident, $flag:ident) => { |
| 2207 |
if levels & $flag != 0 { |
| 2208 |
sink.write(state, &[LEVEL_SEPARATOR_BYTE])?; |
| 2209 |
sink.write(state, &$key.buf)?; |
| 2210 |
} |
| 2211 |
}; |
| 2212 |
} |
| 2213 |
|
| 2214 |
write_level!(secondaries, SECONDARY_LEVEL_FLAG); |
| 2215 |
|
| 2216 |
if levels & CASE_LEVEL_FLAG != 0 { |
| 2217 |
sink.write(state, &[LEVEL_SEPARATOR_BYTE])?; |
| 2218 |
|
| 2219 |
// Write pairs of nibbles as bytes, except separator bytes as themselves. |
| 2220 |
let mut b = 0; |
| 2221 |
if let Some((last, head)) = cases.buf.split_last() { |
| 2222 |
debug_assert_eq!(*last, 1); // The trailing NO_CE |
| 2223 |
for c in head { |
| 2224 |
debug_assert_eq!(*c & 0xf, 0); |
| 2225 |
debug_assert_ne!(*c, 0); |
| 2226 |
if b == 0 { |
| 2227 |
b = *c; |
| 2228 |
} else { |
| 2229 |
sink.write_byte(state, b | (*c >> 4))?; |
| 2230 |
b = 0; |
| 2231 |
} |
| 2232 |
} |
| 2233 |
} else { |
| 2234 |
debug_assert!(false); |
| 2235 |
} |
| 2236 |
if b != 0 { |
| 2237 |
sink.write_byte(state, b)?; |
| 2238 |
} |
| 2239 |
} |
| 2240 |
|
| 2241 |
write_level!(tertiaries, TERTIARY_LEVEL_FLAG); |
| 2242 |
write_level!(quaternaries, QUATERNARY_LEVEL_FLAG); |
| 2243 |
|
| 2244 |
Ok(()) |
| 2245 |
} |
| 2246 |
} |
| 2247 |
|
| 2248 |
/// Error indicating that a [`CollationKeySink`] with limited space ran out of space. |
| 2249 |
#[derive(Debug, PartialEq, Eq)] |
| 2250 |
pub struct TooSmall { |
| 2251 |
/// The total length, in bytes, of the sort key. |
| 2252 |
pub length: usize, |
| 2253 |
} |
| 2254 |
|
| 2255 |
impl TooSmall { |
| 2256 |
pub fn new(length: usize) -> Self { |
| 2257 |
Self { length } |
| 2258 |
} |
| 2259 |
} |
| 2260 |
|
| 2261 |
/// A [`std::io::Write`]-like trait for writing to a buffer-like object. |
| 2262 |
/// |
| 2263 |
/// (This crate does not have access to [`std`].) |
| 2264 |
/// |
| 2265 |
/// <div class="stab unstable"> |
| 2266 |
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways, |
| 2267 |
/// including in SemVer minor releases. Do not implement or call methods on this trait |
| 2268 |
/// unless you are prepared for things to occasionally break. |
| 2269 |
/// |
| 2270 |
/// Graduation tracking issue: [issue #7178](https://github.com/unicode-org/icu4x/issues/7178). |
| 2271 |
/// </div> |
| 2272 |
/// |
| 2273 |
/// ✨ *Enabled with the `unstable` Cargo feature.* |
| 2274 |
pub trait CollationKeySink { |
| 2275 |
/// The type of error the sink may return. |
| 2276 |
type Error; |
| 2277 |
|
| 2278 |
/// An intermediate state object used by the sink, which must implement [`Default`]. |
| 2279 |
type State; |
| 2280 |
|
| 2281 |
/// A result value indicating the final state of the sink (e.g. a number of bytes written). |
| 2282 |
type Output; |
| 2283 |
|
| 2284 |
/// Writes a buffer into the writer. |
| 2285 |
fn write(&mut self, state: &mut Self::State, buf: &[u8]) -> Result<(), Self::Error>; |
| 2286 |
|
| 2287 |
/// Write a single byte into the writer. |
| 2288 |
fn write_byte(&mut self, state: &mut Self::State, b: u8) -> Result<(), Self::Error> { |
| 2289 |
self.write(state, &[b]) |
| 2290 |
} |
| 2291 |
|
| 2292 |
/// Finalize any internal sink state (perhaps by flushing a buffer) and return the final |
| 2293 |
/// output value. |
| 2294 |
fn finish(&mut self, state: Self::State) -> Result<Self::Output, Self::Error>; |
| 2295 |
} |
| 2296 |
|
| 2297 |
impl CollationKeySink for Vec<u8> { |
| 2298 |
type Error = Infallible; |
| 2299 |
type State = (); |
| 2300 |
type Output = (); |
| 2301 |
|
| 2302 |
fn write(&mut self, _: &mut Self::State, buf: &[u8]) -> Result<(), Self::Error> { |
| 2303 |
self.extend_from_slice(buf); |
| 2304 |
Ok(()) |
| 2305 |
} |
| 2306 |
|
| 2307 |
fn finish(&mut self, _: Self::State) -> Result<Self::Output, Self::Error> { |
| 2308 |
Ok(()) |
| 2309 |
} |
| 2310 |
} |
| 2311 |
|
| 2312 |
impl CollationKeySink for VecDeque<u8> { |
| 2313 |
type Error = Infallible; |
| 2314 |
type State = (); |
| 2315 |
type Output = (); |
| 2316 |
|
| 2317 |
fn write(&mut self, _: &mut Self::State, buf: &[u8]) -> Result<(), Self::Error> { |
| 2318 |
self.extend(buf.iter()); |
| 2319 |
Ok(()) |
| 2320 |
} |
| 2321 |
|
| 2322 |
fn finish(&mut self, _: Self::State) -> Result<Self::Output, Self::Error> { |
| 2323 |
Ok(()) |
| 2324 |
} |
| 2325 |
} |
| 2326 |
|
| 2327 |
impl<const N: usize> CollationKeySink for SmallVec<[u8; N]> { |
| 2328 |
type Error = Infallible; |
| 2329 |
type State = (); |
| 2330 |
type Output = (); |
| 2331 |
|
| 2332 |
fn write(&mut self, _: &mut Self::State, buf: &[u8]) -> Result<(), Self::Error> { |
| 2333 |
self.extend_from_slice(buf); |
| 2334 |
Ok(()) |
| 2335 |
} |
| 2336 |
|
| 2337 |
fn finish(&mut self, _: Self::State) -> Result<Self::Output, Self::Error> { |
| 2338 |
Ok(()) |
| 2339 |
} |
| 2340 |
} |
| 2341 |
|
| 2342 |
impl CollationKeySink for [u8] { |
| 2343 |
type Error = TooSmall; |
| 2344 |
type State = usize; |
| 2345 |
type Output = usize; |
| 2346 |
|
| 2347 |
fn write(&mut self, offset: &mut Self::State, buf: &[u8]) -> Result<(), Self::Error> { |
| 2348 |
if *offset + buf.len() <= self.len() { |
| 2349 |
// just checked bounds |
| 2350 |
#[expect(clippy::indexing_slicing)] |
| 2351 |
self[*offset..*offset + buf.len()].copy_from_slice(buf); |
| 2352 |
} |
| 2353 |
*offset += buf.len(); |
| 2354 |
Ok(()) |
| 2355 |
} |
| 2356 |
|
| 2357 |
fn finish(&mut self, offset: Self::State) -> Result<Self::Output, Self::Error> { |
| 2358 |
if offset <= self.len() { |
| 2359 |
Ok(offset) |
| 2360 |
} else { |
| 2361 |
Err(TooSmall::new(offset)) |
| 2362 |
} |
| 2363 |
} |
| 2364 |
} |
| 2365 |
|
| 2366 |
#[derive(Default)] |
| 2367 |
struct SortKeyLevel { |
| 2368 |
buf: SmallVec<[u8; 40]>, |
| 2369 |
} |
| 2370 |
|
| 2371 |
impl SortKeyLevel { |
| 2372 |
fn len(&self) -> usize { |
| 2373 |
self.buf.len() |
| 2374 |
} |
| 2375 |
|
| 2376 |
fn is_empty(&self) -> bool { |
| 2377 |
self.buf.is_empty() |
| 2378 |
} |
| 2379 |
|
| 2380 |
fn append_byte(&mut self, x: u8) { |
| 2381 |
self.buf.push(x); |
| 2382 |
} |
| 2383 |
|
| 2384 |
fn append_weight_16(&mut self, w: u16) { |
| 2385 |
debug_assert_ne!(w, 0); |
| 2386 |
let b0 = (w >> 8) as u8; |
| 2387 |
let b1 = w as u8; |
| 2388 |
self.append_byte(b0); |
| 2389 |
if b1 != 0 { |
| 2390 |
self.append_byte(b1); |
| 2391 |
} |
| 2392 |
} |
| 2393 |
|
| 2394 |
fn append_reverse_weight_16(&mut self, w: u16) { |
| 2395 |
debug_assert_ne!(w, 0); |
| 2396 |
let b0 = (w >> 8) as u8; |
| 2397 |
let b1 = w as u8; |
| 2398 |
if b1 != 0 { |
| 2399 |
self.append_byte(b1); |
| 2400 |
} |
| 2401 |
self.append_byte(b0); |
| 2402 |
} |
| 2403 |
|
| 2404 |
fn append_weight_32(&mut self, w: u32) { |
| 2405 |
debug_assert_ne!(w, 0); |
| 2406 |
let b0 = (w >> 24) as u8; |
| 2407 |
let b1 = (w >> 16) as u8; |
| 2408 |
let b2 = (w >> 8) as u8; |
| 2409 |
let b3 = w as u8; |
| 2410 |
self.append_byte(b0); |
| 2411 |
if b1 != 0 { |
| 2412 |
self.append_byte(b1); |
| 2413 |
if b2 != 0 { |
| 2414 |
self.append_byte(b2); |
| 2415 |
if b3 != 0 { |
| 2416 |
self.append_byte(b3); |
| 2417 |
} |
| 2418 |
} |
| 2419 |
} |
| 2420 |
} |
| 2421 |
} |
| 2422 |
|
| 2423 |
// The algorithm below (BOCSU or Binary Ordered Compression Scheme for Unicode) is translated |
| 2424 |
// from the C++ code in ICU4C at icu4c/source/i18n/bocsu.{cpp,h}. The algorithm works by |
| 2425 |
// converting a sequence of codepoints into a sequence of presumably small differences. See |
| 2426 |
// the C++ code for a more detailed explanation. |
| 2427 |
|
| 2428 |
macro_rules! negdivmod { |
| 2429 |
($n:ident, $d:ident, $m:ident) => { |
| 2430 |
$m = $n % $d; |
| 2431 |
$n /= $d; |
| 2432 |
if $m < 0 { |
| 2433 |
$n -= 1; |
| 2434 |
$m += $d; |
| 2435 |
} |
| 2436 |
}; |
| 2437 |
} |
| 2438 |
|
| 2439 |
fn write_diff<S>(mut diff: i32, sink: &mut S, state: &mut S::State) -> Result<(), S::Error> |
| 2440 |
where |
| 2441 |
S: CollationKeySink + ?Sized, |
| 2442 |
{ |
| 2443 |
let mut out = |b| sink.write_byte(state, b); |
| 2444 |
|
| 2445 |
if diff >= SLOPE_REACH_NEG_1 { |
| 2446 |
if diff <= SLOPE_REACH_POS_1 { |
| 2447 |
out((SLOPE_MIDDLE + diff) as _)?; |
| 2448 |
} else if diff <= SLOPE_REACH_POS_2 { |
| 2449 |
out((SLOPE_START_POS_2 + (diff / SLOPE_TAIL_COUNT)) as _)?; |
| 2450 |
out((SLOPE_MIN + diff % SLOPE_TAIL_COUNT) as _)?; |
| 2451 |
} else if diff <= SLOPE_REACH_POS_3 { |
| 2452 |
let p2 = SLOPE_MIN + diff % SLOPE_TAIL_COUNT; |
| 2453 |
diff /= SLOPE_TAIL_COUNT; |
| 2454 |
let p1 = SLOPE_MIN + diff % SLOPE_TAIL_COUNT; |
| 2455 |
let p0 = SLOPE_START_POS_3 + (diff / SLOPE_TAIL_COUNT); |
| 2456 |
out(p0 as _)?; |
| 2457 |
out(p1 as _)?; |
| 2458 |
out(p2 as _)?; |
| 2459 |
} else { |
| 2460 |
let p3 = SLOPE_MIN + diff % SLOPE_TAIL_COUNT; |
| 2461 |
diff /= SLOPE_TAIL_COUNT; |
| 2462 |
let p2 = SLOPE_MIN + diff % SLOPE_TAIL_COUNT; |
| 2463 |
diff /= SLOPE_TAIL_COUNT; |
| 2464 |
let p1 = SLOPE_MIN + diff % SLOPE_TAIL_COUNT; |
| 2465 |
out(SLOPE_MAX as _)?; |
| 2466 |
out(p1 as _)?; |
| 2467 |
out(p2 as _)?; |
| 2468 |
out(p3 as _)?; |
| 2469 |
} |
| 2470 |
} else { |
| 2471 |
let mut m; |
| 2472 |
|
| 2473 |
if diff >= SLOPE_REACH_NEG_2 { |
| 2474 |
negdivmod!(diff, SLOPE_TAIL_COUNT, m); |
| 2475 |
out((SLOPE_START_NEG_2 + diff) as _)?; |
| 2476 |
out((SLOPE_MIN + m) as _)?; |
| 2477 |
} else if diff >= SLOPE_REACH_NEG_3 { |
| 2478 |
negdivmod!(diff, SLOPE_TAIL_COUNT, m); |
| 2479 |
let p2 = SLOPE_MIN + m; |
| 2480 |
negdivmod!(diff, SLOPE_TAIL_COUNT, m); |
| 2481 |
let p1 = SLOPE_MIN + m; |
| 2482 |
let p0 = SLOPE_START_NEG_3 + diff; |
| 2483 |
out(p0 as _)?; |
| 2484 |
out(p1 as _)?; |
| 2485 |
out(p2 as _)?; |
| 2486 |
} else { |
| 2487 |
negdivmod!(diff, SLOPE_TAIL_COUNT, m); |
| 2488 |
let p3 = SLOPE_MIN + m; |
| 2489 |
negdivmod!(diff, SLOPE_TAIL_COUNT, m); |
| 2490 |
let p2 = SLOPE_MIN + m; |
| 2491 |
negdivmod!(diff, SLOPE_TAIL_COUNT, m); |
| 2492 |
let p1 = SLOPE_MIN + m; |
| 2493 |
let _ = diff; |
| 2494 |
out(SLOPE_MIN as _)?; |
| 2495 |
out(p1 as _)?; |
| 2496 |
out(p2 as _)?; |
| 2497 |
out(p3 as _)?; |
| 2498 |
} |
| 2499 |
} |
| 2500 |
|
| 2501 |
Ok(()) |
| 2502 |
} |
| 2503 |
|
| 2504 |
fn write_identical_level<I, S>(iter: I, sink: &mut S, state: &mut S::State) -> Result<(), S::Error> |
| 2505 |
where |
| 2506 |
I: Iterator<Item = char>, |
| 2507 |
S: CollationKeySink + ?Sized, |
| 2508 |
{ |
| 2509 |
let mut prev = 0i32; |
| 2510 |
|
| 2511 |
for c in iter { |
| 2512 |
if !(0x4e00..0xa000).contains(&prev) { |
| 2513 |
prev = (prev & !0x7f) - SLOPE_REACH_NEG_1; |
| 2514 |
} else { |
| 2515 |
// Unihan U+4e00..U+9fa5: double-bytes down from the upper end |
| 2516 |
prev = 0x9fff - SLOPE_REACH_POS_2; |
| 2517 |
} |
| 2518 |
|
| 2519 |
if c == MERGE_SEPARATOR { |
| 2520 |
sink.write_byte(state, MERGE_SEPARATOR_BYTE)?; |
| 2521 |
prev = 0; |
| 2522 |
} else { |
| 2523 |
let c = c as i32; |
| 2524 |
write_diff(c - prev, sink, state)?; |
| 2525 |
prev = c; |
| 2526 |
} |
| 2527 |
} |
| 2528 |
Ok(()) |
| 2529 |
} |
| 2530 |
|
| 2531 |
#[cfg(test)] |
| 2532 |
mod test { |
| 2533 |
use super::*; |
| 2534 |
use icu_locale_core::locale; |
| 2535 |
|
| 2536 |
type Key = Vec<u8>; |
| 2537 |
|
| 2538 |
fn collator_en(strength: Strength) -> CollatorBorrowed<'static> { |
| 2539 |
let locale = locale!("en").into(); |
| 2540 |
let mut options = CollatorOptions::default(); |
| 2541 |
options.strength = Some(strength); |
| 2542 |
Collator::try_new(locale, options).unwrap() |
| 2543 |
} |
| 2544 |
|
| 2545 |
fn collator_en_case_level(strength: Strength) -> CollatorBorrowed<'static> { |
| 2546 |
let locale = locale!("en").into(); |
| 2547 |
let mut options = CollatorOptions::default(); |
| 2548 |
options.strength = Some(strength); |
| 2549 |
options.case_level = Some(crate::options::CaseLevel::On); |
| 2550 |
Collator::try_new(locale, options).unwrap() |
| 2551 |
} |
| 2552 |
|
| 2553 |
fn keys(strength: Strength) -> (Key, Key, Key) { |
| 2554 |
let collator = collator_en(strength); |
| 2555 |
|
| 2556 |
let mut k0 = Vec::new(); |
| 2557 |
let Ok(()) = collator.write_sort_key_to("aabc", &mut k0); |
| 2558 |
let mut k1 = Vec::new(); |
| 2559 |
let Ok(()) = collator.write_sort_key_to("aAbc", &mut k1); |
| 2560 |
let mut k2 = Vec::new(); |
| 2561 |
let Ok(()) = collator.write_sort_key_to("áAbc", &mut k2); |
| 2562 |
|
| 2563 |
(k0, k1, k2) |
| 2564 |
} |
| 2565 |
|
| 2566 |
#[test] |
| 2567 |
fn sort_key_primary() { |
| 2568 |
let (k0, k1, k2) = keys(Strength::Primary); |
| 2569 |
assert_eq!(k0, k1); |
| 2570 |
assert_eq!(k1, k2); |
| 2571 |
} |
| 2572 |
|
| 2573 |
#[test] |
| 2574 |
fn sort_key_secondary() { |
| 2575 |
let (k0, k1, k2) = keys(Strength::Secondary); |
| 2576 |
assert_eq!(k0, k1); |
| 2577 |
assert!(k1 < k2); |
| 2578 |
} |
| 2579 |
|
| 2580 |
#[test] |
| 2581 |
fn sort_key_tertiary() { |
| 2582 |
let (k0, k1, k2) = keys(Strength::Tertiary); |
| 2583 |
assert!(k0 < k1); |
| 2584 |
assert!(k1 < k2); |
| 2585 |
} |
| 2586 |
|
| 2587 |
fn collator_ja(strength: Strength) -> CollatorBorrowed<'static> { |
| 2588 |
let locale = locale!("ja").into(); |
| 2589 |
let mut options = CollatorOptions::default(); |
| 2590 |
options.strength = Some(strength); |
| 2591 |
Collator::try_new(locale, options).unwrap() |
| 2592 |
} |
| 2593 |
|
| 2594 |
fn keys_ja_strs(strength: Strength, s0: &str, s1: &str) -> (Key, Key) { |
| 2595 |
let collator = collator_ja(strength); |
| 2596 |
|
| 2597 |
let mut k0 = Vec::new(); |
| 2598 |
let Ok(()) = collator.write_sort_key_to(s0, &mut k0); |
| 2599 |
let mut k1 = Vec::new(); |
| 2600 |
let Ok(()) = collator.write_sort_key_to(s1, &mut k1); |
| 2601 |
|
| 2602 |
(k0, k1) |
| 2603 |
} |
| 2604 |
|
| 2605 |
fn keys_ja(strength: Strength) -> (Key, Key) { |
| 2606 |
keys_ja_strs(strength, "あ", "ア") |
| 2607 |
} |
| 2608 |
|
| 2609 |
#[test] |
| 2610 |
fn sort_keys_ja_to_quaternary() { |
| 2611 |
let (k0, k1) = keys_ja(Strength::Primary); |
| 2612 |
assert_eq!(k0, k1); |
| 2613 |
let (k0, k1) = keys_ja(Strength::Secondary); |
| 2614 |
assert_eq!(k0, k1); |
| 2615 |
let (k0, k1) = keys_ja(Strength::Tertiary); |
| 2616 |
assert_eq!(k0, k1); |
| 2617 |
let (k0, k1) = keys_ja(Strength::Quaternary); |
| 2618 |
assert!(k0 < k1); |
| 2619 |
} |
| 2620 |
|
| 2621 |
#[test] |
| 2622 |
fn sort_keys_ja_identical() { |
| 2623 |
let (k0, k1) = keys_ja_strs(Strength::Quaternary, "ア", "ア"); |
| 2624 |
assert_eq!(k0, k1); |
| 2625 |
let (k0, k1) = keys_ja_strs(Strength::Identical, "ア", "ア"); |
| 2626 |
assert!(k0 < k1); |
| 2627 |
} |
| 2628 |
|
| 2629 |
#[test] |
| 2630 |
fn sort_keys_utf16() { |
| 2631 |
let collator = collator_en(Strength::Identical); |
| 2632 |
|
| 2633 |
const STR8: &[u8] = b"hello world!"; |
| 2634 |
let mut k8 = Vec::new(); |
| 2635 |
let Ok(()) = collator.write_sort_key_utf8_to(STR8, &mut k8); |
| 2636 |
|
| 2637 |
const STR16: &[u16] = &[ |
| 2638 |
0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21, |
| 2639 |
]; |
| 2640 |
let mut k16 = Vec::new(); |
| 2641 |
let Ok(()) = collator.write_sort_key_utf16_to(STR16, &mut k16); |
| 2642 |
assert_eq!(k8, k16); |
| 2643 |
} |
| 2644 |
|
| 2645 |
#[test] |
| 2646 |
fn sort_keys_invalid() { |
| 2647 |
let collator = collator_en(Strength::Identical); |
| 2648 |
|
| 2649 |
// some invalid strings |
| 2650 |
let mut k = Vec::new(); |
| 2651 |
let Ok(()) = collator.write_sort_key_utf8_to(b"\xf0\x90", &mut k); |
| 2652 |
let mut k = Vec::new(); |
| 2653 |
let Ok(()) = collator.write_sort_key_utf16_to(&[0xdd1e], &mut k); |
| 2654 |
} |
| 2655 |
|
| 2656 |
#[test] |
| 2657 |
fn sort_key_to_vecdeque() { |
| 2658 |
let collator = collator_en(Strength::Identical); |
| 2659 |
|
| 2660 |
let mut k0 = Vec::new(); |
| 2661 |
let Ok(()) = collator.write_sort_key_to("áAbc", &mut k0); |
| 2662 |
let mut k1 = VecDeque::new(); |
| 2663 |
let Ok(()) = collator.write_sort_key_to("áAbc", &mut k1); |
| 2664 |
assert!(k0.iter().eq(k1.iter())); |
| 2665 |
} |
| 2666 |
|
| 2667 |
#[test] |
| 2668 |
fn sort_key_to_slice() { |
| 2669 |
let collator = collator_en(Strength::Identical); |
| 2670 |
|
| 2671 |
let mut k0 = Vec::new(); |
| 2672 |
let Ok(()) = collator.write_sort_key_to("áAbc", &mut k0); |
| 2673 |
let mut k1 = [0u8; 100]; |
| 2674 |
let len = collator.write_sort_key_to("áAbc", &mut k1[..]).unwrap(); |
| 2675 |
assert_eq!(len, k0.len()); |
| 2676 |
assert!(k0.iter().eq(k1[..len].iter())); |
| 2677 |
} |
| 2678 |
|
| 2679 |
#[test] |
| 2680 |
fn sort_key_to_slice_no_space() { |
| 2681 |
let collator = collator_en(Strength::Identical); |
| 2682 |
let mut k = [0u8; 0]; |
| 2683 |
let res = collator.write_sort_key_to("áAbc", &mut k[..]); |
| 2684 |
assert!(matches!(res, Err(TooSmall { .. }))); |
| 2685 |
} |
| 2686 |
|
| 2687 |
#[test] |
| 2688 |
fn sort_key_to_slice_too_long() { |
| 2689 |
// This runs out of space in write_sort_key_up_to_quaternary. |
| 2690 |
let collator = collator_en(Strength::Identical); |
| 2691 |
let mut k = [0u8; 5]; |
| 2692 |
let res = collator.write_sort_key_to("áAbc", &mut k[..]); |
| 2693 |
assert!(matches!(res, Err(TooSmall { .. }))); |
| 2694 |
} |
| 2695 |
|
| 2696 |
#[test] |
| 2697 |
fn sort_key_to_slice_identical_too_long() { |
| 2698 |
// This runs out of space while appending UTF-8 in the SinkAdapter. |
| 2699 |
let collator = collator_en(Strength::Identical); |
| 2700 |
let mut k = [0u8; 22]; |
| 2701 |
let res = collator.write_sort_key_to("áAbc", &mut k[..]); |
| 2702 |
assert!(matches!(res, Err(TooSmall { .. }))); |
| 2703 |
} |
| 2704 |
|
| 2705 |
#[test] |
| 2706 |
fn sort_key_just_right() { |
| 2707 |
// get the length needed |
| 2708 |
let collator = collator_en(Strength::Identical); |
| 2709 |
let mut k = [0u8; 0]; |
| 2710 |
let res = collator.write_sort_key_to("áAbc", &mut k[..]); |
| 2711 |
let len = res.unwrap_err().length; |
| 2712 |
|
| 2713 |
// almost enough |
| 2714 |
let mut k = vec![0u8; len - 1]; |
| 2715 |
let res = collator.write_sort_key_to("áAbc", &mut k[..]); |
| 2716 |
let len = res.unwrap_err().length; |
| 2717 |
|
| 2718 |
// just right |
| 2719 |
let mut k = vec![0u8; len]; |
| 2720 |
let res = collator.write_sort_key_to("áAbc", &mut k[..]); |
| 2721 |
assert_eq!(res, Ok(len)); |
| 2722 |
} |
| 2723 |
|
| 2724 |
#[test] |
| 2725 |
fn sort_key_utf16_slice_too_small() { |
| 2726 |
let collator = collator_en(Strength::Identical); |
| 2727 |
const STR16: &[u16] = &[0x68, 0x65, 0x6c, 0x6c, 0x6f]; |
| 2728 |
let mut k = [0u8; 4]; |
| 2729 |
let res = collator.write_sort_key_utf16_to(STR16, &mut k[..]); |
| 2730 |
assert!(matches!(res, Err(TooSmall { .. }))); |
| 2731 |
} |
| 2732 |
|
| 2733 |
#[test] |
| 2734 |
fn sort_key_very_long() { |
| 2735 |
let collator = collator_en(Strength::Secondary); |
| 2736 |
let mut k = Vec::new(); |
| 2737 |
let Ok(()) = collator.write_sort_key_to(&"a".repeat(300), &mut k); |
| 2738 |
} |
| 2739 |
|
| 2740 |
#[test] |
| 2741 |
fn sort_key_case_level() { |
| 2742 |
let collator = collator_en_case_level(Strength::Tertiary); |
| 2743 |
let mut k = Vec::new(); |
| 2744 |
let Ok(()) = collator.write_sort_key_to("aBc", &mut k); |
| 2745 |
} |
| 2746 |
|
| 2747 |
#[test] |
| 2748 |
fn sort_key_case_level_empty() { |
| 2749 |
let collator = collator_en_case_level(Strength::Tertiary); |
| 2750 |
let mut k = Vec::new(); |
| 2751 |
let Ok(()) = collator.write_sort_key_to("", &mut k); |
| 2752 |
} |
| 2753 |
|
| 2754 |
fn check_sort_key_less(a: &[u16], b: &[u16]) { |
| 2755 |
let collator = collator_en(Strength::Identical); |
| 2756 |
let mut ak = Vec::new(); |
| 2757 |
let Ok(()) = collator.write_sort_key_utf16_to(a, &mut ak); |
| 2758 |
let mut bk = Vec::new(); |
| 2759 |
let Ok(()) = collator.write_sort_key_utf16_to(b, &mut bk); |
| 2760 |
assert!(ak < bk, "failed: {a:04x?} - {b:04x?}"); |
| 2761 |
} |
| 2762 |
|
| 2763 |
#[test] |
| 2764 |
fn sort_key_backward_second_level_empty() { |
| 2765 |
let locale = locale!("fr-CA").into(); |
| 2766 |
let mut options = CollatorOptions::default(); |
| 2767 |
options.strength = Some(Strength::Tertiary); |
| 2768 |
let collator = Collator::try_new(locale, options).unwrap(); |
| 2769 |
let mut k = Vec::new(); |
| 2770 |
let Ok(()) = collator.write_sort_key_to("", &mut k); |
| 2771 |
} |
| 2772 |
|
| 2773 |
#[test] |
| 2774 |
fn sort_key_fffe_bug_6811() { |
| 2775 |
check_sort_key_less( |
| 2776 |
&[0xfffe, 0x0001, 0x0002, 0x0003], |
| 2777 |
&[0x0001, 0xfffe, 0x0002, 0x0003], |
| 2778 |
); |
| 2779 |
check_sort_key_less( |
| 2780 |
&[0x0001, 0xfffe, 0x0002, 0x0003], |
| 2781 |
&[0x0001, 0x0002, 0xfffe, 0x0003], |
| 2782 |
); |
| 2783 |
check_sort_key_less( |
| 2784 |
&[0x0001, 0x0002, 0xfffe, 0x0003], |
| 2785 |
&[0x0001, 0x0002, 0x0003, 0xfffe], |
| 2786 |
); |
| 2787 |
check_sort_key_less(&[0xfffe, 0x0000, 0x0000], &[0x0000, 0xfffe, 0x0000]); |
| 2788 |
check_sort_key_less(&[0x0000, 0xfffe, 0x0000], &[0x0000, 0x0000, 0xfffe]); |
| 2789 |
} |
| 2790 |
} |