icu_provider_source/properties/
enum_codepointtrie.rs

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

use crate::SourceDataProvider;
use icu::collections::codepointtrie::CodePointTrie;
use icu::properties::provider::{names::*, *};
use icu_provider::prelude::*;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::convert::TryFrom;
use zerotrie::ZeroTrieSimpleAscii;
use zerovec::ule::NichedOption;

impl SourceDataProvider {
    pub(super) fn get_enumerated_prop<'a>(
        &'a self,
        key: &str,
    ) -> Result<&'a super::uprops_serde::enumerated::EnumeratedPropertyMap, DataError> {
        self.icuexport()?
            .read_and_parse_toml::<super::uprops_serde::enumerated::Main>(&format!(
                "uprops/{}/{}.toml",
                self.trie_type(),
                key
            ))?
            .enum_property
            .first()
            .ok_or_else(|| DataErrorKind::MarkerNotFound.into_error())
    }
    fn get_mask_prop<'a>(
        &'a self,
        key: &str,
    ) -> Result<&'a super::uprops_serde::mask::MaskPropertyMap, DataError> {
        self.icuexport()?
            .read_and_parse_toml::<super::uprops_serde::mask::Main>(&format!(
                "uprops/{}/{}.toml",
                self.trie_type(),
                key
            ))?
            .mask_property
            .first()
            .ok_or(DataError::custom(
                "Loading icuexport property data failed: \
                 Are you using a sufficiently recent icuexport? (Must be ⪈ 72.1)",
            ))
    }
}

fn get_prop_values_map<F>(
    values: &[super::uprops_serde::PropertyValue],
    transform_u32: F,
) -> Result<PropertyValueNameToEnumMapV1<'static>, DataError>
where
    F: Fn(u32) -> Result<u16, DataError>,
{
    let mut map = BTreeMap::new();
    for value in values {
        let discr = transform_u32(value.discr)? as usize;
        map.insert(value.long.as_bytes(), discr);
        if let Some(ref short) = value.short {
            map.insert(short.as_bytes(), discr);
        }
        for alias in &value.aliases {
            map.insert(alias.as_bytes(), discr);
        }
    }
    Ok(PropertyValueNameToEnumMapV1 {
        map: ZeroTrieSimpleAscii::from_iter(map).convert_store(),
    })
}

/// Convert a map from property values to their names into
/// a linear map where each index represents a property value
fn map_to_vec<'a>(
    map: &'a BTreeMap<u16, &'a str>,
    prop_name: &str,
) -> Result<Vec<&'a str>, DataError> {
    // Use .first_key_value() and .last_key_value() after bumping MSRV
    let first = if let Some((&first, _)) = map.iter().next() {
        if first > 0 {
            return Err(DataError::custom(
                "Property has nonzero starting discriminant, perhaps consider \
                 storing its names as a sparse map or by specializing this error",
            )
            .with_display_context(&format!("Property: {prop_name}, discr: {first}")));
        }

        first
    } else {
        return Err(DataError::custom("Property has no values!").with_display_context(prop_name));
    };
    let last = if let Some((&last, _)) = map.iter().next_back() {
        let range = usize::from(1 + last - first);
        let count = map.len();
        let gaps = range - count;
        if gaps > 0 {
            return Err(DataError::custom("Property has more than 0 gaps, \
                perhaps consider storing its names in a sparse map or by specializing this error")
                .with_display_context(&format!("Property: {prop_name}, discriminant range: {first}..{last}, discriminant count: {count}")));
        }

        last
    } else {
        return Err(DataError::custom("Property has no values!").with_display_context(prop_name));
    };

    let mut v = Vec::new();
    for i in 0..=last {
        if let Some(&val) = map.get(&i) {
            v.push(val)
        } else {
            v.push("")
        }
    }
    Ok(v)
}

/// Load the mapping from property values to their names
fn load_values_to_names(
    data: &super::uprops_serde::enumerated::EnumeratedPropertyMap,
    is_short: bool,
) -> Result<BTreeMap<u16, &str>, DataError> {
    let mut map: BTreeMap<_, &str> = BTreeMap::new();

    for value in &data.values {
        let discr = u16::try_from(value.discr)
            .map_err(|_| DataError::custom("Found value larger than u16 for property"))?;
        if is_short {
            if let Some(ref short) = value.short {
                map.insert(discr, short);
            }
        } else {
            map.insert(discr, &value.long);
        }
    }

    Ok(map)
}

/// Load the mapping from property values to their names as a sparse map
fn load_values_to_names_sparse<M>(
    p: &SourceDataProvider,
    prop_name: &str,
    is_short: bool,
) -> Result<DataResponse<M>, DataError>
where
    M: DynamicDataMarker<DataStruct = PropertyEnumToValueNameSparseMapV1<'static>>,
{
    let data = p.get_enumerated_prop(prop_name)
        .map_err(|_| DataError::custom("Loading icuexport property data failed: \
                                        Are you using a sufficiently recent icuexport? (Must be ⪈ 72.1)"))?;
    let map = load_values_to_names(data, is_short)?;
    let map = map.into_iter().collect();
    let data_struct = PropertyEnumToValueNameSparseMapV1 { map };
    Ok(DataResponse {
        metadata: Default::default(),
        payload: DataPayload::from_owned(data_struct),
    })
}

/// Load the mapping from property values to their names as a linear map
fn load_values_to_names_linear<M>(
    p: &SourceDataProvider,
    prop_name: &str,
    is_short: bool,
) -> Result<DataResponse<M>, DataError>
where
    M: DynamicDataMarker<DataStruct = PropertyEnumToValueNameLinearMapV1<'static>>,
{
    let data = p.get_enumerated_prop(prop_name)
        .map_err(|_| DataError::custom("Loading icuexport property data failed: \
                                        Are you using a sufficiently recent icuexport? (Must be ⪈ 72.1)"))?;
    let map = load_values_to_names(data, is_short)?;
    let vec = map_to_vec(&map, prop_name)?;
    let varzerovec = (&vec).into();
    let data_struct = PropertyEnumToValueNameLinearMapV1 { map: varzerovec };
    Ok(DataResponse {
        metadata: Default::default(),
        payload: DataPayload::from_owned(data_struct),
    })
}

/// Load the mapping from property values to their names as a linear map of TinyStr4s
fn load_values_to_names_linear4<M>(
    p: &SourceDataProvider,
    prop_name: &str,
    is_short: bool,
) -> Result<DataResponse<M>, DataError>
where
    M: DynamicDataMarker<DataStruct = PropertyScriptToIcuScriptMapV1<'static>>,
{
    let data = p.get_enumerated_prop(prop_name)
        .map_err(|_| DataError::custom("Loading icuexport property data failed: \
                                        Are you using a sufficiently recent icuexport? (Must be ⪈ 72.1)"))?;
    let map = load_values_to_names(data, is_short)?;
    let vec = map_to_vec(&map, prop_name)?;
    let vec: Result<Vec<_>, _> = vec
        .into_iter()
        .map(|s| {
            if s.is_empty() {
                Ok(None)
            } else {
                icu::locale::subtags::Script::try_from_str(s).map(Some)
            }
        })
        .collect();

    let vec = vec.map_err(|_| DataError::custom("Found invalid script tag"))?;
    let zerovec = vec.into_iter().map(NichedOption).collect();
    let data_struct = PropertyScriptToIcuScriptMapV1 { map: zerovec };
    Ok(DataResponse {
        metadata: Default::default(),
        payload: DataPayload::from_owned(data_struct),
    })
}
macro_rules! expand {
    ($(($marker:ident, $marker_n2e:ident,
        // marker_e2sns is short for marker_enum_to_short_name_sparse, etc
        // We only support selecting one of these at a time right now, but we need
        // different variable names for the macro matcher to work
        $((sparse: $marker_e2sns:ident, $marker_e2lns:ident),)?
        $((linear: $marker_e2snl:ident, $marker_e2lnl:ident),)?
        $((linear4: $marker_e2snl4:ident, $marker_e2lnl4:ident),)?


        $prop_name:literal)),+,) => {
        $(
            impl DataProvider<$marker> for SourceDataProvider
            {
                fn load(&self, req: DataRequest) -> Result<DataResponse<$marker>, DataError> {
                    self.check_req::<$marker>(req)?;
                    let source_cpt_data = &self.get_enumerated_prop($prop_name)?.code_point_trie;

                    let code_point_trie = CodePointTrie::try_from(source_cpt_data).map_err(|e| {
                        DataError::custom("Could not parse CodePointTrie TOML").with_display_context(&e)
                    })?;
                    let data_struct = PropertyCodePointMapV1::CodePointTrie(code_point_trie);
                    Ok(DataResponse {
                        metadata: Default::default(),
                        payload: DataPayload::from_owned(data_struct),
                    })
                }
            }

            impl crate::IterableDataProviderCached<$marker> for SourceDataProvider {
                fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                    self.get_enumerated_prop($prop_name)?;
                    Ok(HashSet::from_iter([Default::default()]))
                }
            }

            impl DataProvider<$marker_n2e> for SourceDataProvider
            {
                fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_n2e>, DataError> {
                    self.check_req::<$marker_n2e>(req)?;
                    let data = self.get_enumerated_prop($prop_name)
                        .map_err(|_| DataError::custom("Loading icuexport property data failed: \
                                                        Are you using a sufficiently recent icuexport? (Must be ⪈ 72.1)"))?;

                    let data_struct = get_prop_values_map(&data.values, |v| u16::try_from(v).map_err(|_| DataError::custom(concat!("Found value larger than u16 for property ", $prop_name))))?;
                    Ok(DataResponse {
                        metadata: Default::default(),
                        payload: DataPayload::from_owned(data_struct),
                    })
                }
            }

            impl crate::IterableDataProviderCached<$marker_n2e> for SourceDataProvider {
                                fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                    self.get_enumerated_prop($prop_name)?;
                    Ok(HashSet::from_iter([Default::default()]))
                }
            }

            $(
                impl DataProvider<$marker_e2sns> for SourceDataProvider
                {
                    fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_e2sns>, DataError> {
                        self.check_req::<$marker_e2sns>(req)?;
                        load_values_to_names_sparse(self, $prop_name, true)
                    }
                }

                impl crate::IterableDataProviderCached<$marker_e2sns> for SourceDataProvider {
                    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                        self.get_enumerated_prop($prop_name)?;
                        Ok(HashSet::from_iter([Default::default()]))
                    }
                }

                impl DataProvider<$marker_e2lns> for SourceDataProvider
                {
                    fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_e2lns>, DataError> {
                        self.check_req::<$marker_e2lns>(req)?;
                        load_values_to_names_sparse(self, $prop_name, false)
                    }
                }

                impl crate::IterableDataProviderCached<$marker_e2lns> for SourceDataProvider {
                    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                        self.get_enumerated_prop($prop_name)?;
                        Ok(HashSet::from_iter([Default::default()]))
                    }
                }
            )?

            $(
                impl DataProvider<$marker_e2snl> for SourceDataProvider
                {
                    fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_e2snl>, DataError> {
                        self.check_req::<$marker_e2snl>(req)?;
                        load_values_to_names_linear(self, $prop_name, true)
                    }
                }

                impl crate::IterableDataProviderCached<$marker_e2snl> for SourceDataProvider {
                    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                        self.get_enumerated_prop($prop_name)?;
                        Ok(HashSet::from_iter([Default::default()]))
                    }
                }

                impl DataProvider<$marker_e2lnl> for SourceDataProvider
                {
                    fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_e2lnl>, DataError> {
                        self.check_req::<$marker_e2lnl>(req)?;
                        load_values_to_names_linear(self, $prop_name, false)
                    }
                }

                impl crate::IterableDataProviderCached<$marker_e2lnl> for SourceDataProvider {
                    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                        self.get_enumerated_prop($prop_name)?;
                        Ok(HashSet::from_iter([Default::default()]))
                    }
                }
            )?

            $(
                impl DataProvider<$marker_e2snl4> for SourceDataProvider
                {
                    fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_e2snl4>, DataError> {
                        self.check_req::<$marker_e2snl4>(req)?;
                        load_values_to_names_linear4(self, $prop_name, true)
                    }
                }

                impl crate::IterableDataProviderCached<$marker_e2snl4> for SourceDataProvider {
                    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                        self.get_enumerated_prop($prop_name)?;
                        Ok(HashSet::from_iter([Default::default()]))
                    }
                }

                impl DataProvider<$marker_e2lnl4> for SourceDataProvider
                {
                    fn load(&self, req: DataRequest) -> Result<DataResponse<$marker_e2lnl4>, DataError> {
                        self.check_req::<$marker_e2lnl4>(req)?;
                        // Tiny4 is only for short names
                        load_values_to_names_linear(self, $prop_name, false)
                    }
                }

                impl crate::IterableDataProviderCached<$marker_e2lnl4> for SourceDataProvider {
                    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>  {
                        self.get_enumerated_prop($prop_name)?;
                        Ok(HashSet::from_iter([Default::default()]))
                    }
                }
            )?
        )+
    };
}

// Special handling for GeneralCategoryMask
impl DataProvider<GeneralCategoryMaskNameToValueV2Marker> for SourceDataProvider {
    fn load(
        &self,
        req: DataRequest,
    ) -> Result<DataResponse<GeneralCategoryMaskNameToValueV2Marker>, DataError> {
        use icu::properties::props::GeneralCategoryGroup;
        use zerovec::ule::AsULE;

        self.check_req::<GeneralCategoryMaskNameToValueV2Marker>(req)?;

        let data = self.get_mask_prop("gcm")?;
        let data_struct = get_prop_values_map(&data.values, |v| {
            let value: GeneralCategoryGroup = v.into();
            let ule = value.to_unaligned();
            let packed = u16::from_unaligned(ule);

            // sentinel value
            if packed == 0xFF00 {
                return Err(DataError::custom("Found unknown general category mask value, properties code may need to be updated."));
            }
            Ok(packed)
        })?;
        Ok(DataResponse {
            metadata: Default::default(),
            payload: DataPayload::from_owned(data_struct),
        })
    }
}

impl crate::IterableDataProviderCached<GeneralCategoryMaskNameToValueV2Marker>
    for SourceDataProvider
{
    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError> {
        self.get_mask_prop("gcm")?;
        Ok(HashSet::from_iter([Default::default()]))
    }
}

expand!(
    (
        CanonicalCombiningClassV1Marker,
        CanonicalCombiningClassNameToValueV2Marker,
        (
            sparse: CanonicalCombiningClassValueToShortNameV1Marker,
            CanonicalCombiningClassValueToLongNameV1Marker
        ),
        "ccc"
    ),
    (
        GeneralCategoryV1Marker,
        GeneralCategoryNameToValueV2Marker,
        (
            linear: GeneralCategoryValueToShortNameV1Marker,
            GeneralCategoryValueToLongNameV1Marker
        ),
        "gc"
    ),
    (
        BidiClassV1Marker,
        BidiClassNameToValueV2Marker,
        (
            linear: BidiClassValueToShortNameV1Marker,
            BidiClassValueToLongNameV1Marker
        ),
        "bc"
    ),
    (
        ScriptV1Marker,
        ScriptNameToValueV2Marker,
        (
            linear4: ScriptValueToShortNameV1Marker,
            ScriptValueToLongNameV1Marker
        ),
        "sc"
    ),
    (
        HangulSyllableTypeV1Marker,
        HangulSyllableTypeNameToValueV2Marker,
        (
            linear: HangulSyllableTypeValueToShortNameV1Marker,
            HangulSyllableTypeValueToLongNameV1Marker
        ),
        "hst"
    ),
    (
        EastAsianWidthV1Marker,
        EastAsianWidthNameToValueV2Marker,
        (
            linear: EastAsianWidthValueToShortNameV1Marker,
            EastAsianWidthValueToLongNameV1Marker
        ),
        "ea"
    ),
    (
        IndicSyllabicCategoryV1Marker,
        IndicSyllabicCategoryNameToValueV2Marker,
        (
            linear: IndicSyllabicCategoryValueToShortNameV1Marker,
            IndicSyllabicCategoryValueToLongNameV1Marker
        ),
        "InSC"
    ),
    (
        LineBreakV1Marker,
        LineBreakNameToValueV2Marker,
        (
            linear: LineBreakValueToShortNameV1Marker,
            LineBreakValueToLongNameV1Marker
        ),
        "lb"
    ),
    (
        GraphemeClusterBreakV1Marker,
        GraphemeClusterBreakNameToValueV2Marker,
        (
            linear: GraphemeClusterBreakValueToShortNameV1Marker,
            GraphemeClusterBreakValueToLongNameV1Marker
        ),
        "GCB"
    ),
    (
        WordBreakV1Marker,
        WordBreakNameToValueV2Marker,
        (
            linear: WordBreakValueToShortNameV1Marker,
            WordBreakValueToLongNameV1Marker
        ),
        "WB"
    ),
    (
        SentenceBreakV1Marker,
        SentenceBreakNameToValueV2Marker,
        (
            linear: SentenceBreakValueToShortNameV1Marker,
            SentenceBreakValueToLongNameV1Marker
        ),
        "SB"
    ),
    (
        JoiningTypeV1Marker,
        JoiningTypeNameToValueV2Marker,
        (
            linear: JoiningTypeValueToShortNameV1Marker,
            JoiningTypeValueToLongNameV1Marker
        ),
        "jt"
    ),
);

#[cfg(test)]
mod tests {
    use super::*;

    // A test of the UnicodeProperty General_Category is truly a test of the
    // `GeneralCategory` Rust enum, not the `GeneralCategoryGroup` Rust enum,
    // since we must match the representation and value width of the data from
    // the ICU CodePointTrie that ICU4X is reading from.
    #[test]
    fn test_general_category() {
        use icu::properties::{props::GeneralCategory, CodePointMapData};
        let provider = SourceDataProvider::new_testing();

        let trie = CodePointMapData::<GeneralCategory>::try_new_unstable(&provider).unwrap();
        let trie = trie.as_code_point_trie().unwrap();

        assert_eq!(trie.get32('꣓' as u32), GeneralCategory::DecimalNumber);
        assert_eq!(trie.get32('≈' as u32), GeneralCategory::MathSymbol);
    }

    #[test]
    fn test_script() {
        use icu::properties::{props::Script, CodePointMapData};
        let provider = SourceDataProvider::new_testing();

        let trie = CodePointMapData::<Script>::try_new_unstable(&provider).unwrap();
        let trie = trie.as_code_point_trie().unwrap();

        assert_eq!(trie.get32('꣓' as u32), Script::Saurashtra);
        assert_eq!(trie.get32('≈' as u32), Script::Common);
    }
}