1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

//! Access to the Unicode properties or property-based operations that
//! are required for NFC and NFD.
//!
//! Applications should generally use the full normalizers that are
//! provided at the top level of this crate. However, the APIs in this
//! module are provided for callers such as HarfBuzz that specifically
//! want access to the raw canonical composition operation e.g. for use in a
//! glyph-availability-guided custom normalizer.

use crate::char_from_u16;
use crate::in_inclusive_range;
use crate::provider::CanonicalCompositionsV1;
use crate::provider::CanonicalCompositionsV1Marker;
use crate::provider::CanonicalDecompositionDataV1Marker;
use crate::provider::CanonicalDecompositionTablesV1Marker;
use crate::provider::DecompositionDataV1;
use crate::provider::DecompositionTablesV1;
use crate::provider::NonRecursiveDecompositionSupplementV1;
use crate::provider::NonRecursiveDecompositionSupplementV1Marker;
use crate::trie_value_has_ccc;
use crate::trie_value_indicates_special_non_starter_decomposition;
use crate::CanonicalCombiningClass;
use crate::BACKWARD_COMBINING_STARTER_MARKER;
use crate::FDFA_MARKER;
use crate::HANGUL_L_BASE;
use crate::HANGUL_N_COUNT;
use crate::HANGUL_S_BASE;
use crate::HANGUL_S_COUNT;
use crate::HANGUL_T_BASE;
use crate::HANGUL_T_COUNT;
use crate::HANGUL_V_BASE;
use crate::NON_ROUND_TRIP_MARKER;
use crate::SPECIAL_NON_STARTER_DECOMPOSITION_MARKER_U16;
use icu_provider::prelude::*;

/// Borrowed version of the raw canonical composition operation.
///
/// Callers should generally use `ComposingNormalizer` instead of this API.
/// However, this API is provided for callers such as HarfBuzz that specifically
/// want access to the raw canonical composition operation e.g. for use in a
/// glyph-availability-guided custom normalizer.
#[derive(Debug)]
pub struct CanonicalCompositionBorrowed<'a> {
    canonical_compositions: &'a CanonicalCompositionsV1<'a>,
}

#[cfg(feature = "compiled_data")]
impl Default for CanonicalCompositionBorrowed<'static> {
    fn default() -> Self {
        Self::new()
    }
}

impl CanonicalCompositionBorrowed<'static> {
    /// Cheaply converts a [`CanonicalCompositionBorrowed<'static>`] into a [`CanonicalComposition`].
    ///
    /// Note: Due to branching and indirection, using [`CanonicalComposition`] might inhibit some
    /// compile-time optimizations that are possible with [`CanonicalCompositionBorrowed`].
    pub const fn static_to_owned(self) -> CanonicalComposition {
        CanonicalComposition {
            canonical_compositions: DataPayload::from_static_ref(self.canonical_compositions),
        }
    }

    /// Constructs a new `CanonicalComposition` using compiled data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [πŸ“š Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    pub const fn new() -> Self {
        Self {
            canonical_compositions:
                crate::provider::Baked::SINGLETON_CANONICAL_COMPOSITIONS_V1_MARKER,
        }
    }
}

impl CanonicalCompositionBorrowed<'_> {
    /// Performs canonical composition (including Hangul) on a pair of
    /// characters or returns `None` if these characters don't compose.
    /// Composition exclusions are taken into account.
    ///
    /// # Examples
    ///
    /// ```
    /// let comp = icu::normalizer::properties::CanonicalCompositionBorrowed::new();
    ///
    /// assert_eq!(comp.compose('a', 'b'), None); // Just two non-composing starters
    /// assert_eq!(comp.compose('a', '\u{0308}'), Some('Γ€'));
    /// assert_eq!(comp.compose('αΊΉ', '\u{0302}'), Some('ệ'));
    /// assert_eq!(comp.compose('𝅗', 'π…₯'), None); // Composition exclusion
    /// assert_eq!(comp.compose('ে', 'ΰ¦Ύ'), Some('ো')); // Second is starter
    /// assert_eq!(comp.compose('α„€', 'α…‘'), Some('κ°€')); // Hangul LV
    /// assert_eq!(comp.compose('κ°€', 'ᆨ'), Some('각')); // Hangul LVT
    /// ```
    #[inline(always)]
    pub fn compose(&self, starter: char, second: char) -> Option<char> {
        crate::compose(
            self.canonical_compositions.canonical_compositions.iter(),
            starter,
            second,
        )
    }
}

/// The raw canonical composition operation.
///
/// Callers should generally use `ComposingNormalizer` instead of this API.
/// However, this API is provided for callers such as HarfBuzz that specifically
/// want access to the raw canonical composition operation e.g. for use in a
/// glyph-availability-guided custom normalizer.
#[derive(Debug)]
pub struct CanonicalComposition {
    canonical_compositions: DataPayload<CanonicalCompositionsV1Marker>,
}

#[cfg(feature = "compiled_data")]
impl Default for CanonicalComposition {
    fn default() -> Self {
        Self::new().static_to_owned()
    }
}

impl CanonicalComposition {
    /// Constructs a borrowed version of this type for more efficient querying.
    pub fn as_borrowed(&self) -> CanonicalCompositionBorrowed<'_> {
        CanonicalCompositionBorrowed {
            canonical_compositions: self.canonical_compositions.get(),
        }
    }

    /// Constructs a new `CanonicalCompositionBorrowed` using compiled data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [πŸ“š Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    #[allow(clippy::new_ret_no_self)]
    pub const fn new() -> CanonicalCompositionBorrowed<'static> {
        CanonicalCompositionBorrowed::new()
    }

    icu_provider::gen_any_buffer_data_constructors!(() -> error: DataError,
        functions: [
            new: skip,
            try_new_with_any_provider,
            try_new_with_buffer_provider,
            try_new_unstable,
            Self,
        ]
    );

    #[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::new)]
    pub fn try_new_unstable<D>(provider: &D) -> Result<Self, DataError>
    where
        D: DataProvider<CanonicalCompositionsV1Marker> + ?Sized,
    {
        let canonical_compositions: DataPayload<CanonicalCompositionsV1Marker> =
            provider.load(Default::default())?.payload;
        Ok(CanonicalComposition {
            canonical_compositions,
        })
    }
}

/// The outcome of non-recursive canonical decomposition of a character.
#[allow(clippy::exhaustive_enums)]
#[derive(Debug, PartialEq, Eq)]
pub enum Decomposed {
    /// The character is its own canonical decomposition.
    Default,
    /// The character decomposes to a single different character.
    Singleton(char),
    /// The character decomposes to two characters.
    Expansion(char, char),
}

/// Borrowed version of the raw (non-recursive) canonical decomposition operation.
///
/// Callers should generally use `DecomposingNormalizer` instead of this API.
/// However, this API is provided for callers such as HarfBuzz that specifically
/// want access to non-recursive canonical decomposition e.g. for use in a
/// glyph-availability-guided custom normalizer.
#[derive(Debug)]
pub struct CanonicalDecompositionBorrowed<'a> {
    decompositions: &'a DecompositionDataV1<'a>,
    tables: &'a DecompositionTablesV1<'a>,
    non_recursive: &'a NonRecursiveDecompositionSupplementV1<'a>,
}

#[cfg(feature = "compiled_data")]
impl Default for CanonicalDecompositionBorrowed<'static> {
    fn default() -> Self {
        Self::new()
    }
}

impl CanonicalDecompositionBorrowed<'static> {
    /// Cheaply converts a [`CanonicalDecompositionBorrowed<'static>`] into a [`CanonicalDecomposition`].
    ///
    /// Note: Due to branching and indirection, using [`CanonicalDecomposition`] might inhibit some
    /// compile-time optimizations that are possible with [`CanonicalDecompositionBorrowed`].
    pub const fn static_to_owned(self) -> CanonicalDecomposition {
        CanonicalDecomposition {
            decompositions: DataPayload::from_static_ref(self.decompositions),
            tables: DataPayload::from_static_ref(self.tables),
            non_recursive: DataPayload::from_static_ref(self.non_recursive),
        }
    }

    /// Construct from compiled data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [πŸ“š Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    pub const fn new() -> Self {
        const _: () = assert!(
            crate::provider::Baked::SINGLETON_CANONICAL_DECOMPOSITION_TABLES_V1_MARKER
                .scalars16
                .const_len()
                + crate::provider::Baked::SINGLETON_CANONICAL_DECOMPOSITION_TABLES_V1_MARKER
                    .scalars24
                    .const_len()
                <= 0xFFF,
            "future extension"
        );

        Self {
            decompositions:
                crate::provider::Baked::SINGLETON_CANONICAL_DECOMPOSITION_DATA_V1_MARKER,
            tables: crate::provider::Baked::SINGLETON_CANONICAL_DECOMPOSITION_TABLES_V1_MARKER,
            non_recursive:
                crate::provider::Baked::SINGLETON_NON_RECURSIVE_DECOMPOSITION_SUPPLEMENT_V1_MARKER,
        }
    }
}

impl CanonicalDecompositionBorrowed<'_> {
    /// Performs non-recursive canonical decomposition (including for Hangul).
    ///
    /// ```
    ///     use icu::normalizer::properties::Decomposed;
    ///     let decomp = icu::normalizer::properties::CanonicalDecompositionBorrowed::new();
    ///
    ///     assert_eq!(decomp.decompose('e'), Decomposed::Default);
    ///     assert_eq!(
    ///         decomp.decompose('ệ'),
    ///         Decomposed::Expansion('αΊΉ', '\u{0302}')
    ///     );
    ///     assert_eq!(decomp.decompose('각'), Decomposed::Expansion('κ°€', 'ᆨ'));
    ///     assert_eq!(decomp.decompose('\u{212B}'), Decomposed::Singleton('Γ…')); // ANGSTROM SIGN
    ///     assert_eq!(decomp.decompose('\u{2126}'), Decomposed::Singleton('Ξ©')); // OHM SIGN
    ///     assert_eq!(decomp.decompose('\u{1F71}'), Decomposed::Singleton('Ξ¬')); // oxia
    /// ```
    #[inline]
    pub fn decompose(&self, c: char) -> Decomposed {
        let lvt = u32::from(c).wrapping_sub(HANGUL_S_BASE);
        if lvt >= HANGUL_S_COUNT {
            return self.decompose_non_hangul(c);
        }
        let t = lvt % HANGUL_T_COUNT;
        if t == 0 {
            let l = lvt / HANGUL_N_COUNT;
            let v = (lvt % HANGUL_N_COUNT) / HANGUL_T_COUNT;
            // Safe because values known to be in range
            return Decomposed::Expansion(
                unsafe { char::from_u32_unchecked(HANGUL_L_BASE + l) },
                unsafe { char::from_u32_unchecked(HANGUL_V_BASE + v) },
            );
        }
        let lv = lvt - t;
        // Safe because values known to be in range
        Decomposed::Expansion(
            unsafe { char::from_u32_unchecked(HANGUL_S_BASE + lv) },
            unsafe { char::from_u32_unchecked(HANGUL_T_BASE + t) },
        )
    }

    /// Performs non-recursive canonical decomposition except Hangul syllables
    /// are reported as `Decomposed::Default`.
    #[inline(always)]
    fn decompose_non_hangul(&self, c: char) -> Decomposed {
        let decomposition = self.decompositions.trie.get(c);
        if decomposition <= BACKWARD_COMBINING_STARTER_MARKER {
            return Decomposed::Default;
        }
        // The loop is only broken out of as goto forward
        #[allow(clippy::never_loop)]
        loop {
            let trail_or_complex = (decomposition >> 16) as u16;
            let lead = decomposition as u16;
            if lead > NON_ROUND_TRIP_MARKER && trail_or_complex != 0 {
                // Decomposition into two BMP characters: starter and non-starter
                if in_inclusive_range(c, '\u{1F71}', '\u{1FFB}') {
                    // Look in the other trie due to oxia singleton
                    // mappings to corresponding character with tonos.
                    break;
                }
                return Decomposed::Expansion(char_from_u16(lead), char_from_u16(trail_or_complex));
            }
            if lead > NON_ROUND_TRIP_MARKER {
                // Decomposition into one BMP character or non-starter
                debug_assert_ne!(
                    lead, FDFA_MARKER,
                    "How come we got the U+FDFA NFKD marker here?"
                );
                if lead == SPECIAL_NON_STARTER_DECOMPOSITION_MARKER_U16 {
                    // Non-starter
                    if !in_inclusive_range(c, '\u{0340}', '\u{0F81}') {
                        return Decomposed::Default;
                    }
                    return match c {
                        '\u{0340}' => {
                            // COMBINING GRAVE TONE MARK
                            Decomposed::Singleton('\u{0300}')
                        }
                        '\u{0341}' => {
                            // COMBINING ACUTE TONE MARK
                            Decomposed::Singleton('\u{0301}')
                        }
                        '\u{0343}' => {
                            // COMBINING GREEK KORONIS
                            Decomposed::Singleton('\u{0313}')
                        }
                        '\u{0344}' => {
                            // COMBINING GREEK DIALYTIKA TONOS
                            Decomposed::Expansion('\u{0308}', '\u{0301}')
                        }
                        '\u{0F73}' => {
                            // TIBETAN VOWEL SIGN II
                            Decomposed::Expansion('\u{0F71}', '\u{0F72}')
                        }
                        '\u{0F75}' => {
                            // TIBETAN VOWEL SIGN UU
                            Decomposed::Expansion('\u{0F71}', '\u{0F74}')
                        }
                        '\u{0F81}' => {
                            // TIBETAN VOWEL SIGN REVERSED II
                            Decomposed::Expansion('\u{0F71}', '\u{0F80}')
                        }
                        _ => Decomposed::Default,
                    };
                }
                return Decomposed::Singleton(char_from_u16(lead));
            }
            // The recursive decomposition of ANGSTROM SIGN is in the complex
            // decomposition structure to avoid a branch in `potential_passthrough`
            // for the BMP case.
            if c == '\u{212B}' {
                // ANGSTROM SIGN
                return Decomposed::Singleton('\u{00C5}');
            }
            // Complex decomposition
            // Format for 16-bit value:
            // 15..13: length minus two for 16-bit case and length minus one for
            //         the 32-bit case. Length 8 needs to fit in three bits in
            //         the 16-bit case, and this way the value is future-proofed
            //         up to 9 in the 16-bit case. Zero is unused and length one
            //         in the 16-bit case goes directly into the trie.
            //     12: 1 if all trailing characters are guaranteed non-starters,
            //         0 if no guarantees about non-starterness.
            //         Note: The bit choice is this way around to allow for
            //         dynamically falling back to not having this but instead
            //         having one more bit for length by merely choosing
            //         different masks.
            //  11..0: Start offset in storage. The offset is to the logical
            //         sequence of scalars16, scalars32, supplementary_scalars16,
            //         supplementary_scalars32.
            let offset = usize::from(trail_or_complex & 0xFFF);
            let tables = self.tables;
            if offset < tables.scalars16.len() {
                if usize::from(trail_or_complex >> 13) != 0 {
                    // i.e. logical len isn't 2
                    break;
                }
                if let Some(first) = tables.scalars16.get(offset) {
                    if let Some(second) = tables.scalars16.get(offset + 1) {
                        // Two BMP starters
                        return Decomposed::Expansion(char_from_u16(first), char_from_u16(second));
                    }
                }
                // GIGO case
                debug_assert!(false);
                return Decomposed::Default;
            }
            let len = usize::from(trail_or_complex >> 13) + 1;
            if len > 2 {
                break;
            }
            let offset24 = offset - tables.scalars16.len();
            if let Some(first_c) = tables.scalars24.get(offset24) {
                if len == 1 {
                    return Decomposed::Singleton(first_c);
                }
                if let Some(second_c) = tables.scalars24.get(offset24 + 1) {
                    return Decomposed::Expansion(first_c, second_c);
                }
            }
            // GIGO case
            debug_assert!(false);
            return Decomposed::Default;
        }
        let non_recursive = self.non_recursive;
        let non_recursive_decomposition = non_recursive.trie.get(c);
        if non_recursive_decomposition == 0 {
            // GIGO case
            debug_assert!(false);
            return Decomposed::Default;
        }
        let trail_or_complex = (non_recursive_decomposition >> 16) as u16;
        let lead = non_recursive_decomposition as u16;
        if lead != 0 && trail_or_complex != 0 {
            // Decomposition into two BMP characters
            return Decomposed::Expansion(char_from_u16(lead), char_from_u16(trail_or_complex));
        }
        if lead != 0 {
            // Decomposition into one BMP character
            return Decomposed::Singleton(char_from_u16(lead));
        }
        // Decomposition into two non-BMP characters
        // Low is offset into a table plus one to keep it non-zero.
        let offset = usize::from(trail_or_complex - 1);
        if let Some(first) = non_recursive.scalars24.get(offset) {
            if let Some(second) = non_recursive.scalars24.get(offset + 1) {
                return Decomposed::Expansion(first, second);
            }
        }
        // GIGO case
        debug_assert!(false);
        Decomposed::Default
    }
}

/// The raw (non-recursive) canonical decomposition operation.
///
/// Callers should generally use `DecomposingNormalizer` instead of this API.
/// However, this API is provided for callers such as HarfBuzz that specifically
/// want access to non-recursive canonical decomposition e.g. for use in a
/// glyph-availability-guided custom normalizer.
#[derive(Debug)]
pub struct CanonicalDecomposition {
    decompositions: DataPayload<CanonicalDecompositionDataV1Marker>,
    tables: DataPayload<CanonicalDecompositionTablesV1Marker>,
    non_recursive: DataPayload<NonRecursiveDecompositionSupplementV1Marker>,
}

#[cfg(feature = "compiled_data")]
impl Default for CanonicalDecomposition {
    fn default() -> Self {
        Self::new().static_to_owned()
    }
}

impl CanonicalDecomposition {
    /// Constructs a borrowed version of this type for more efficient querying.
    pub fn as_borrowed(&self) -> CanonicalDecompositionBorrowed<'_> {
        CanonicalDecompositionBorrowed {
            decompositions: self.decompositions.get(),
            tables: self.tables.get(),
            non_recursive: self.non_recursive.get(),
        }
    }

    /// Construct from compiled data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [πŸ“š Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    #[allow(clippy::new_ret_no_self)]
    pub const fn new() -> CanonicalDecompositionBorrowed<'static> {
        CanonicalDecompositionBorrowed::new()
    }

    icu_provider::gen_any_buffer_data_constructors!(() -> error: DataError,
        functions: [
            new: skip,
            try_new_with_any_provider,
            try_new_with_buffer_provider,
            try_new_unstable,
            Self,
        ]
    );

    #[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::new)]
    pub fn try_new_unstable<D>(provider: &D) -> Result<Self, DataError>
    where
        D: DataProvider<CanonicalDecompositionDataV1Marker>
            + DataProvider<CanonicalDecompositionTablesV1Marker>
            + DataProvider<NonRecursiveDecompositionSupplementV1Marker>
            + ?Sized,
    {
        let decompositions: DataPayload<CanonicalDecompositionDataV1Marker> =
            provider.load(Default::default())?.payload;
        let tables: DataPayload<CanonicalDecompositionTablesV1Marker> =
            provider.load(Default::default())?.payload;

        if tables.get().scalars16.len() + tables.get().scalars24.len() > 0xFFF {
            // The data is from a future where there exists a normalization flavor whose
            // complex decompositions take more than 0xFFF but fewer than 0x1FFF code points
            // of space. If a good use case from such a decomposition flavor arises, we can
            // dynamically change the bit masks so that the length mask becomes 0x1FFF instead
            // of 0xFFF and the all-non-starters mask becomes 0 instead of 0x1000. However,
            // since for now the masks are hard-coded, error out.
            return Err(DataError::custom("future extension"));
        }

        let non_recursive: DataPayload<NonRecursiveDecompositionSupplementV1Marker> =
            provider.load(Default::default())?.payload;

        Ok(CanonicalDecomposition {
            decompositions,
            tables,
            non_recursive,
        })
    }
}

/// Borrowed version of lookup of the Canonical_Combining_Class Unicode property.
///
/// # Example
///
/// ```
/// use icu::properties::props::CanonicalCombiningClass;
/// use icu::normalizer::properties::CanonicalCombiningClassMapBorrowed;
///
/// let map = CanonicalCombiningClassMapBorrowed::new();
/// assert_eq!(map.get('a'), CanonicalCombiningClass::NotReordered); // U+0061: LATIN SMALL LETTER A
/// assert_eq!(map.get32(0x0301), CanonicalCombiningClass::Above); // U+0301: COMBINING ACUTE ACCENT
/// ```
#[derive(Debug)]
pub struct CanonicalCombiningClassMapBorrowed<'a> {
    /// The data trie
    decompositions: &'a DecompositionDataV1<'a>,
}

#[cfg(feature = "compiled_data")]
impl Default for CanonicalCombiningClassMapBorrowed<'static> {
    fn default() -> Self {
        Self::new()
    }
}

impl CanonicalCombiningClassMapBorrowed<'static> {
    /// Cheaply converts a [`CanonicalCombiningClassMapBorrowed<'static>`] into a [`CanonicalCombiningClassMap`].
    ///
    /// Note: Due to branching and indirection, using [`CanonicalCombiningClassMap`] might inhibit some
    /// compile-time optimizations that are possible with [`CanonicalCombiningClassMapBorrowed`].
    pub const fn static_to_owned(self) -> CanonicalCombiningClassMap {
        CanonicalCombiningClassMap {
            decompositions: DataPayload::from_static_ref(self.decompositions),
        }
    }

    /// Construct from compiled data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [πŸ“š Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    pub const fn new() -> Self {
        CanonicalCombiningClassMapBorrowed {
            decompositions:
                crate::provider::Baked::SINGLETON_CANONICAL_DECOMPOSITION_DATA_V1_MARKER,
        }
    }
}

impl CanonicalCombiningClassMapBorrowed<'_> {
    /// Look up the canonical combining class for a scalar value.
    ///
    /// The return value is a u8 representing the canonical combining class,
    /// you may enable the `"icu_properties"` feature if you would like to use a typed
    /// `CanonicalCombiningClass`.
    #[inline(always)]
    pub fn get_u8(&self, c: char) -> u8 {
        self.get32_u8(u32::from(c))
    }

    /// Look up the canonical combining class for a scalar value
    /// represented as `u32`. If the argument is outside the scalar
    /// value range, `Not_Reordered` is returned.
    ///
    /// The return value is a u8 representing the canonical combining class,
    /// you may enable the `"icu_properties"` feature if you would like to use a typed
    /// `CanonicalCombiningClass`.
    pub fn get32_u8(&self, c: u32) -> u8 {
        let trie_value = self.decompositions.trie.get32(c);
        if trie_value_has_ccc(trie_value) {
            trie_value as u8
        } else if trie_value_indicates_special_non_starter_decomposition(trie_value) {
            match c {
                0x0340 | 0x0341 | 0x0343 | 0x0344 => ccc!(Above, 230).0,
                _ => ccc!(NotReordered, 0).0,
            }
        } else {
            ccc!(NotReordered, 0).0
        }
    }

    /// Look up the canonical combining class for a scalar value
    ///
    /// ✨ *Enabled with the `icu_properties` Cargo feature.*
    #[inline(always)]
    #[cfg(feature = "icu_properties")]
    pub fn get(&self, c: char) -> CanonicalCombiningClass {
        CanonicalCombiningClass(self.get_u8(c))
    }

    /// Look up the canonical combining class for a scalar value
    /// represented as `u32`. If the argument is outside the scalar
    /// value range, `CanonicalCombiningClass::NotReordered` is returned.
    ///
    /// ✨ *Enabled with the `icu_properties` Cargo feature.*
    #[cfg(feature = "icu_properties")]
    pub fn get32(&self, c: u32) -> CanonicalCombiningClass {
        CanonicalCombiningClass(self.get32_u8(c))
    }
}

/// Lookup of the Canonical_Combining_Class Unicode property.
#[derive(Debug)]
pub struct CanonicalCombiningClassMap {
    /// The data trie
    decompositions: DataPayload<CanonicalDecompositionDataV1Marker>,
}

#[cfg(feature = "compiled_data")]
impl Default for CanonicalCombiningClassMap {
    fn default() -> Self {
        Self::new().static_to_owned()
    }
}

impl CanonicalCombiningClassMap {
    /// Constructs a borrowed version of this type for more efficient querying.
    pub fn as_borrowed(&self) -> CanonicalCombiningClassMapBorrowed<'_> {
        CanonicalCombiningClassMapBorrowed {
            decompositions: self.decompositions.get(),
        }
    }

    /// Construct from compiled data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [πŸ“š Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    #[allow(clippy::new_ret_no_self)]
    pub const fn new() -> CanonicalCombiningClassMapBorrowed<'static> {
        CanonicalCombiningClassMapBorrowed::new()
    }

    icu_provider::gen_any_buffer_data_constructors!(() -> error: DataError,
        functions: [
            new: skip,
            try_new_with_any_provider,
            try_new_with_buffer_provider,
            try_new_unstable,
            Self,
    ]);

    #[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::new)]
    pub fn try_new_unstable<D>(provider: &D) -> Result<Self, DataError>
    where
        D: DataProvider<CanonicalDecompositionDataV1Marker> + ?Sized,
    {
        let decompositions: DataPayload<CanonicalDecompositionDataV1Marker> =
            provider.load(Default::default())?.payload;
        Ok(CanonicalCombiningClassMap { decompositions })
    }
}