icu_provider_source 2.2.0

A data provider based on CLDR and ICU data.
Documentation
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
// 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 ).

// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations
// #![cfg_attr(not(any(test, doc)), no_std)]
// #![cfg_attr(
//     not(test),
//     deny(
//         clippy::indexing_slicing,
//         clippy::unwrap_used,
//         clippy::expect_used,
//         clippy::panic,
//     )
// )]
#![warn(missing_docs)]

//! `icu_provider_source` defines [`SourceDataProvider`], the authorative ICU4X [`DataProvider`] that produces data from
//! CLDR and ICU sources.
//!
//! [`SourceDataProvider`] is mainly intended as a source for the `icu_provider_export` crate,
//! which can be used to transform the data into a more efficient format.
//!
//! # Cargo features
//!
//! * `networking`
//!   * enables networking support to download CLDR and ICU source data from GitHub
//! * `use_wasm` / `use_icu4c`
//!   * see the documentation on [`icu_codepointtrie_builder`](icu_codepointtrie_builder#build-configuration)
//! * `unstable`
//!   * enables unstable data markers

use cldr_cache::CldrCache;
use elsa::sync::FrozenMap;
use icu::calendar::{Date, Iso};
use icu::time::zone::UtcOffset;
use icu::time::Time;
use icu_provider::prelude::*;
use source::{AbstractFs, SerdeCache, TzdbCache, UnihanCache};
use std::collections::{BTreeSet, HashSet};
use std::fmt::Debug;
use std::path::Path;
use std::sync::{Arc, OnceLock};

mod calendar;
mod characters;
mod cldr_serde;
mod collator;
#[cfg(feature = "unstable")]
mod currency;
mod datetime;
mod debug_provider;
mod decimal;
#[cfg(feature = "unstable")]
mod displaynames;
mod duration;
mod list;
mod locale;
mod normalizer;
#[cfg(feature = "unstable")]
mod percent;
#[cfg(feature = "unstable")]
mod personnames;
mod plurals;
mod properties;
#[cfg(feature = "unstable")]
mod relativetime;
mod segmenter;
mod time_zones;
#[cfg(feature = "unstable")]
mod transforms;
mod ucase;
#[cfg(feature = "unstable")]
mod units;

mod cldr_cache;
mod source;

#[cfg(test)]
mod tests;

/// An [`ExportableProvider`](icu_provider::export::ExportableProvider) backed by raw CLDR and ICU data.
///
/// This provider covers all markers that are used by ICU4X. It is intended as the canonical
/// provider for `ExportDriver::export`.
///
/// If a required data source has not been set, `DataProvider::load` will
/// fail with the appropriate error:
/// * [`is_missing_cldr_error`](Self::is_missing_cldr_error)
/// * [`is_missing_icuexport_error`](Self::is_missing_icuexport_error)
/// * [`is_missing_segmenter_lstm_error`](Self::is_missing_segmenter_lstm_error)
/// * [`is_missing_unihan_error`](Self::is_missing_unihan_error)
/// * [`is_missing_ucd_error`](Self::is_missing_ucd_error)
/// * [`is_missing_tzdb_error`](Self::is_missing_tzdb_error)
#[allow(clippy::exhaustive_structs)] // any information will be added to SourceData
#[derive(Debug, Clone)]
pub struct SourceDataProvider {
    cldr_paths: Option<Arc<CldrCache>>,
    icuexport_paths: Option<Arc<SerdeCache>>,
    segmenter_lstm_paths: Option<Arc<SerdeCache>>,
    tzdb_paths: Option<Arc<TzdbCache>>,
    unihan_paths: Option<Arc<UnihanCache>>,
    ucd_paths: Option<Arc<AbstractFs>>,
    trie_type: TrieType,
    collation_root_han: CollationRootHan,
    pub(crate) timezone_horizon: time_zones::Timestamp,
    #[expect(clippy::type_complexity)] // not as complex as it appears
    requests_cache: Arc<
        FrozenMap<
            DataMarkerInfo,
            Box<OnceLock<Result<HashSet<DataIdentifierCow<'static>>, DataError>>>,
        >,
    >,
}

macro_rules! cb {
    ($($marker_ty:ty:$marker:ident,)+ #[unstable] $($emarker_ty:ty:$emarker:ident,)+) => {
        icu_provider::export::make_exportable_provider!(SourceDataProvider, [
            $($marker_ty,)+
            $(#[cfg(feature = "unstable")] $emarker_ty,)+
        ]);
    }
}
extern crate alloc;
icu_provider_registry::registry!(cb);

icu_provider::marker::impl_data_provider_never_marker!(SourceDataProvider);

impl SourceDataProvider {
    /// The CLDR JSON tag that has been verified to work with this version of `SourceDataProvider`.
    pub const TESTED_CLDR_TAG: &'static str = "48.2.0";

    /// The ICU export tag that has been verified to work with this version of `SourceDataProvider`.
    pub const TESTED_ICUEXPORT_TAG: &'static str = "release-78.1rc";

    /// The segmentation LSTM model tag that has been verified to work with this version of `SourceDataProvider`.
    pub const TESTED_SEGMENTER_LSTM_TAG: &'static str = "v0.1.0";

    /// The UCD version tag that has been verified to work with this version of `SourceDataProvider`.
    pub const TESTED_UCD_TAG: &'static str = "17.0.0";

    /// The TZDB tag that has been verified to work with this version of `SourceDataProvider`.
    pub const TESTED_TZDB_TAG: &'static str = "2026a";

    /// A provider using the data that has been verified to work with this version of `SourceDataProvider`.
    ///
    /// See [`TESTED_CLDR_TAG`](Self::TESTED_CLDR_TAG),
    /// [`TESTED_ICUEXPORT_TAG`](Self::TESTED_ICUEXPORT_TAG),
    /// [`TESTED_SEGMENTER_LSTM_TAG`](Self::TESTED_SEGMENTER_LSTM_TAG),
    /// [`TESTED_UCD_TAG`](Self::TESTED_UCD_TAG),
    /// [`TESTED_TZDB_TAG`](Self::TESTED_TZDB_TAG).
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    #[expect(clippy::new_without_default)]
    pub fn new() -> Self {
        // Singleton so that all instantiations share the same cache.
        static SINGLETON: OnceLock<SourceDataProvider> = OnceLock::new();
        SINGLETON
            .get_or_init(|| {
                Self::new_custom()
                    .with_cldr_for_tag(Self::TESTED_CLDR_TAG)
                    .with_icuexport_for_tag(Self::TESTED_ICUEXPORT_TAG)
                    .with_segmenter_lstm_for_tag(Self::TESTED_SEGMENTER_LSTM_TAG)
                    .with_tzdb_for_tag(Self::TESTED_TZDB_TAG)
                    .with_unihan_for_tag(Self::TESTED_UCD_TAG)
            })
            .clone()
    }

    /// A provider with no source data. Without adding more sources, most `load` methods
    /// will return errors.
    ///
    /// Use [`with_cldr`](Self::with_cldr), [`with_icuexport`](Self::with_icuexport),
    /// [`with_segmenter_lstm`](Self::with_segmenter_lstm) to set data sources.
    pub fn new_custom() -> Self {
        Self {
            cldr_paths: None,
            icuexport_paths: None,
            segmenter_lstm_paths: None,
            tzdb_paths: None,
            unihan_paths: None,
            ucd_paths: None,
            trie_type: Default::default(),
            timezone_horizon: time_zones::Timestamp::try_offset_only_from_str(
                "2015-01-01T00:00:00Z",
                Default::default(),
            )
            .unwrap(),
            collation_root_han: Default::default(),
            requests_cache: Default::default(),
        }
    }

    /// Adds CLDR source data to the provider. The root should point to a local
    /// `cldr-{tag}-json-full` directory or ZIP file (see
    /// [GitHub releases](https://github.com/unicode-org/cldr-json/releases)).
    pub fn with_cldr(self, root: &Path) -> Result<Self, DataError> {
        Ok(Self {
            cldr_paths: Some(Arc::new(CldrCache::from_serde_cache(SerdeCache::new(
                AbstractFs::new(root)?,
            )))),
            ..self
        })
    }

    /// Adds ICU export source data to the provider. The path should point to a local
    /// `icuexportdata_{tag}` directory or ZIP file (see [GitHub releases](
    /// https://github.com/unicode-org/icu/releases)).
    pub fn with_icuexport(self, root: &Path) -> Result<Self, DataError> {
        Ok(Self {
            icuexport_paths: Some(Arc::new(SerdeCache::new(AbstractFs::new(root)?))),
            ..self
        })
    }

    /// Adds segmenter LSTM source data to the provider. The path should point to a local
    /// `models` directory or ZIP file (see [GitHub releases](
    /// https://github.com/unicode-org/lstm_word_segmentation/releases)).
    pub fn with_segmenter_lstm(self, root: &Path) -> Result<Self, DataError> {
        Ok(Self {
            segmenter_lstm_paths: Some(Arc::new(SerdeCache::new(AbstractFs::new(root)?))),
            ..self
        })
    }

    /// Adds Unihan source data to the provider. The path should point to the Unihan ZIP file
    /// (see [Unicode Character Database](https://www.unicode.org/ucd/)).
    pub fn with_unihan(self, root: &Path) -> Result<Self, DataError> {
        Ok(Self {
            unihan_paths: Some(Arc::new(UnihanCache {
                root: AbstractFs::new(root)?,
                irg_cache: Default::default(),
            })),
            ..self
        })
    }

    /// Adds UCD source data to the provider. The path should point to a
    /// directory containing `security/IdentifierStatus.txt`.
    pub fn with_ucd(self, root: &Path) -> Result<Self, DataError> {
        Ok(Self {
            ucd_paths: Some(Arc::new(AbstractFs::new(root)?)),
            ..self
        })
    }

    /// Adds timezone database source data to the provider. The path should point to a local
    /// `tz` directory or ZIP file (see [GitHub](https://github.com/eggert/tz)).
    pub fn with_tzdb(self, root: &Path) -> Result<Self, DataError> {
        Ok(Self {
            tzdb_paths: Some(Arc::new(TzdbCache {
                root: AbstractFs::new(root)?,
                transitions: Default::default(),
            })),
            ..self
        })
    }

    /// Adds CLDR source data to the provider. The data will be downloaded from GitHub
    /// using the given tag (see [GitHub releases](https://github.com/unicode-org/cldr-json/releases)).
    ///
    /// Also see: [`TESTED_CLDR_TAG`](Self::TESTED_CLDR_TAG)
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    pub fn with_cldr_for_tag(self, tag: &str) -> Self {
        Self {
                cldr_paths: Some(Arc::new(CldrCache::from_serde_cache(SerdeCache::new(AbstractFs::new_from_url(format!(
                    "https://github.com/unicode-org/cldr-json/releases/download/{tag}/cldr-{tag}-json-full.zip",
                )))))),
                ..self
        }
    }

    /// Adds ICU export source data to the provider. The data will be downloaded from GitHub
    /// using the given tag (see [GitHub releases](https://github.com/unicode-org/icu/releases)).
    ///
    /// Also see: [`TESTED_ICUEXPORT_TAG`](Self::TESTED_ICUEXPORT_TAG)
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    pub fn with_icuexport_for_tag(self, tag: &str) -> Self {
        let url = if tag >= "release-78.1" || tag.starts_with("icu4x-") {
            format!(
                "https://github.com/unicode-org/icu/releases/download/{tag}/icu4x-icuexportdata-{}.zip",
                tag.replace("release-", "").replace("icu4x-", "")
            )
        } else {
            format!(
                "https://github.com/unicode-org/icu/releases/download/{tag}/icuexportdata_{}.zip",
                tag.replace('/', "-")
            )
        };
        Self {
            icuexport_paths: Some(Arc::new(SerdeCache::new(AbstractFs::new_from_url(url)))),
            ..self
        }
    }

    /// Adds segmenter LSTM source data to the provider. The data will be downloaded from GitHub
    /// using the given tag (see [GitHub releases](https://github.com/unicode-org/lstm_word_segmentation/releases)).
    ///
    /// Also see: [`TESTED_SEGMENTER_LSTM_TAG`](Self::TESTED_SEGMENTER_LSTM_TAG)
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    pub fn with_segmenter_lstm_for_tag(self, tag: &str) -> Self {
        Self {
            segmenter_lstm_paths: Some(Arc::new(SerdeCache::new(AbstractFs::new_from_url(format!(
                "https://github.com/unicode-org/lstm_word_segmentation/releases/download/{tag}/models.zip"
            ))))),
            ..self
        }
    }

    /// Adds UCD Unihan source data to the provider. The data will be downloaded from unicode.org
    /// using the given version tag (see [Unicode Character Database](https://www.unicode.org/ucd/)).
    ///
    /// Also see: [`TESTED_UCD_TAG`](Self::TESTED_UCD_TAG)
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    pub fn with_unihan_for_tag(self, tag: &str) -> Self {
        Self {
            unihan_paths: Some(Arc::new(UnihanCache {
                root: AbstractFs::new_from_url(format!(
                    "https://www.unicode.org/Public/{tag}/ucd/Unihan.zip"
                )),
                irg_cache: Default::default(),
            })),
            ..self
        }
    }

    /// Adds UCD source data to the provider. The data will be downloaded from unicode.org
    /// using the given version tag (see [Unicode Character Database](https://www.unicode.org/ucd/)).
    ///
    /// Also see: [`TESTED_UCD_TAG`](Self::TESTED_UCD_TAG)
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    pub fn with_ucd_for_tag(self, tag: &str) -> Self {
        Self {
            ucd_paths: Some(Arc::new(AbstractFs::new_from_url(format!(
                "https://www.unicode.org/Public/{tag}/"
            )))),
            ..self
        }
    }

    /// Adds timezone database source data to the provider. The data will be downloaded from GitHub
    /// using the given tag (see [GitHub](https://github.com/eggert/tz)).
    ///
    /// Also see: [`TESTED_SEGMENTER_LSTM_TAG`](Self::TESTED_SEGMENTER_LSTM_TAG)
    ///
    /// ✨ *Enabled with the `networking` Cargo feature.*
    #[cfg(feature = "networking")]
    pub fn with_tzdb_for_tag(self, tag: &str) -> Self {
        Self {
            tzdb_paths: Some(Arc::new(TzdbCache {
                root: AbstractFs::new_from_url(format!(
                    "https://www.iana.org/time-zones/repository/releases/tzdata{tag}.tar.gz",
                )),
                transitions: Default::default(),
            })),
            ..self
        }
    }

    const MISSING_CLDR_ERROR: DataError =
        DataError::custom("Missing CLDR data. Use `.with_cldr[_for_tag]` to set CLDR data.");

    const MISSING_ICUEXPORT_ERROR: DataError =
        DataError::custom("Missing ICU data. Use `.with_icuexport[_for_tag]` to set ICU data.");

    const MISSING_SEGMENTER_LSTM_ERROR: DataError = DataError::custom(
        "Missing segmenter data. Use `.with_segmenter_lstm[_for_tag]` to set segmenter data.",
    );

    const MISSING_UNIHAN_ERROR: DataError =
        DataError::custom("Missing Unihan data. Use `.with_unihan[_for_tag]` to set Unihan data.");

    const MISSING_UCD_ERROR: DataError =
        DataError::custom("Missing UCD data. Use `.with_ucd` to set UCD data.");

    const MISSING_TZDB_ERROR: DataError =
        DataError::custom("Missing tzdb data. Use `.with_tzdb[_for_tag]` to set tzdb data.");

    /// Identifies errors that are due to missing CLDR data.
    pub fn is_missing_cldr_error(mut e: DataError) -> bool {
        e.marker = None;
        e == Self::MISSING_CLDR_ERROR
    }

    /// Identifies errors that are due to missing ICU export data.
    pub fn is_missing_icuexport_error(mut e: DataError) -> bool {
        e.marker = None;
        e == Self::MISSING_ICUEXPORT_ERROR
    }

    /// Identifies errors that are due to missing segmenter LSTM data.
    pub fn is_missing_segmenter_lstm_error(mut e: DataError) -> bool {
        e.marker = None;
        e == Self::MISSING_SEGMENTER_LSTM_ERROR
    }

    /// Identifies errors that are due to missing TZDB data.
    pub fn is_missing_tzdb_error(mut e: DataError) -> bool {
        e.marker = None;
        e == Self::MISSING_TZDB_ERROR
    }

    /// Identifies errors that are due to missing UCD data.
    pub fn is_missing_unihan_error(mut e: DataError) -> bool {
        e.marker = None;
        e == Self::MISSING_UNIHAN_ERROR
    }

    /// Identifies errors that are due to missing UCD data.
    pub fn is_missing_ucd_error(mut e: DataError) -> bool {
        e.marker = None;
        e == Self::MISSING_UCD_ERROR
    }

    fn cldr(&self) -> Result<&CldrCache, DataError> {
        self.cldr_paths.as_deref().ok_or(Self::MISSING_CLDR_ERROR)
    }

    fn icuexport(&self) -> Result<&SerdeCache, DataError> {
        self.icuexport_paths
            .as_deref()
            .ok_or(Self::MISSING_ICUEXPORT_ERROR)
    }

    fn segmenter_lstm(&self) -> Result<&SerdeCache, DataError> {
        self.segmenter_lstm_paths
            .as_deref()
            .ok_or(Self::MISSING_SEGMENTER_LSTM_ERROR)
    }

    #[allow(dead_code)]
    fn unihan(&self) -> Result<&UnihanCache, DataError> {
        self.unihan_paths
            .as_deref()
            .ok_or(Self::MISSING_UNIHAN_ERROR)
    }

    #[allow(dead_code)]
    fn ucd(&self) -> Result<&AbstractFs, DataError> {
        self.ucd_paths.as_deref().ok_or(Self::MISSING_UCD_ERROR)
    }

    fn tzdb(&self) -> Result<&TzdbCache, DataError> {
        self.tzdb_paths.as_deref().ok_or(Self::MISSING_TZDB_ERROR)
    }

    /// Set this to use tries optimized for speed instead of data size.
    ///
    /// The tries for the core (UAX #15 but not UAX #46) normalization
    /// forms use the fast trie type regardless of this setting.
    pub fn with_fast_tries(self) -> Self {
        Self {
            trie_type: TrieType::Fast,
            ..self
        }
    }

    /// Set the [`CollationRootHan`] version.
    pub fn with_collation_root_han(self, collation_root_han: CollationRootHan) -> Self {
        Self {
            collation_root_han,
            ..self
        }
    }

    /// Set the timezone horizon from a UTC date.
    ///
    /// Timezone names that have not been in use since before this date are not included,
    /// formatting will fall back to formats like "Germany Time" or "GMT+1".
    ///
    /// Defaults to 2015-01-01, which is a reasonable time frame where people remember
    /// time zone changes.
    pub fn with_timezone_horizon(self, date: Date<Iso>) -> Self {
        Self {
            timezone_horizon: time_zones::Timestamp {
                date,
                time: Time::start_of_day(),
                zone: UtcOffset::zero(),
            },
            ..self
        }
    }

    fn trie_type(&self) -> TrieType {
        self.trie_type
    }

    fn collation_root_han(&self) -> CollationRootHan {
        self.collation_root_han
    }

    /// List the locales for the given CLDR coverage levels
    pub fn locales_for_coverage_levels(
        &self,
        levels: impl IntoIterator<Item = CoverageLevel>,
    ) -> Result<impl IntoIterator<Item = DataLocale>, DataError> {
        self.cldr()?.locales(levels)
    }
}

impl SourceDataProvider {
    fn check_req<M: DataMarker>(&self, req: DataRequest) -> Result<(), DataError>
    where
        SourceDataProvider: IterableDataProviderCached<M>,
    {
        if <M as DataMarker>::INFO.is_singleton {
            if !req.id.locale.is_unknown() {
                Err(DataErrorKind::InvalidRequest)
            } else {
                Ok(())
            }
        } else if !self.populate_requests_cache()?.contains(&req.id.as_cow()) {
            Err(DataErrorKind::IdentifierNotFound)
        } else {
            Ok(())
        }
        .map_err(|e| e.with_req(<M as DataMarker>::INFO, req))
    }
}

#[test]
fn test_check_req() {
    use icu::locale::langid;
    use icu_provider::hello_world::*;

    #[allow(non_local_definitions)] // test-scoped, only place that uses it
    impl DataProvider<HelloWorldV1> for SourceDataProvider {
        fn load(&self, req: DataRequest) -> Result<DataResponse<HelloWorldV1>, DataError> {
            HelloWorldProvider.load(req)
        }
    }

    #[allow(non_local_definitions)] // test-scoped, only place that uses it
    impl IterableDataProviderCached<HelloWorldV1> for SourceDataProvider {
        fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError> {
            Ok(HelloWorldProvider.iter_ids()?.into_iter().collect())
        }
    }

    let provider = SourceDataProvider::new_testing();
    assert!(provider
        .check_req::<HelloWorldV1>(DataRequest {
            id: DataIdentifierBorrowed::for_locale(&langid!("fi").into()),
            ..Default::default()
        })
        .is_ok());
    assert!(provider
        .check_req::<HelloWorldV1>(DataRequest {
            id: DataIdentifierBorrowed::for_locale(&langid!("arc").into()),
            ..Default::default()
        })
        .is_err());
}

trait IterableDataProviderCached<M: DataMarker>: DataProvider<M> {
    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError>;
}

impl SourceDataProvider {
    fn populate_requests_cache<M: DataMarker>(
        &self,
    ) -> Result<&HashSet<DataIdentifierCow<'_>>, DataError>
    where
        SourceDataProvider: IterableDataProviderCached<M>,
    {
        self.requests_cache
            .insert_with(M::INFO, || Box::new(OnceLock::new()))
            // write lock gets dropped here, `iter_ids_cached` might be expensive
            .get_or_init(|| self.iter_ids_cached())
            .as_ref()
            .map_err(|&e| e)
    }
}

impl<M: DataMarker> IterableDataProvider<M> for SourceDataProvider
where
    SourceDataProvider: IterableDataProviderCached<M>,
{
    fn iter_ids(&self) -> Result<BTreeSet<DataIdentifierCow<'_>>, DataError> {
        Ok(if <M as DataMarker>::INFO.is_singleton {
            [Default::default()].into_iter().collect()
        } else {
            self.populate_requests_cache()?
                .iter()
                .map(|id| id.as_borrowed().as_cow())
                .collect()
        })
    }
}

/// Specifies the collation Han database to use.
///
/// Unihan is more precise but significantly increases data size. See
/// <https://github.com/unicode-org/icu/blob/main/docs/userguide/icu::data/buildtool.md#collation-ucadata>
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum CollationRootHan {
    /// Implicit
    #[serde(rename = "implicit")]
    #[default]
    Implicit,
    /// Unihan
    #[serde(rename = "unihan")]
    Unihan,
}

impl std::fmt::Display for CollationRootHan {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            CollationRootHan::Implicit => write!(f, "implicithan"),
            CollationRootHan::Unihan => write!(f, "unihan"),
        }
    }
}

/// A language's CLDR coverage level.
///
/// In ICU4X, these are disjoint sets: a language belongs to a single coverage level. This
/// contrasts with CLDR usage, where these levels are understood to be additive (i.e., "basic"
/// includes all language with "basic", or better coverage). The ICU4X semantics allow
/// generating different data files for different coverage levels without duplicating data.
/// However, the data itself is still additive (e.g. for fallback to work correctly), so data
/// for moderate (basic) languages should only be loaded if modern (modern and moderate) data
/// is already present.
#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, Hash)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub enum CoverageLevel {
    /// Locales listed as modern coverage targets by the CLDR subcomittee.
    ///
    /// This is the highest level of coverage.
    Modern,
    /// Locales listed as moderate, but not modern, coverage targets by the CLDR subcomittee.
    ///
    /// This is a medium level of coverage.
    Moderate,
    /// Locales listed as basic, but not moderate or modern, coverage targets by the CLDR subcomittee.
    ///
    /// This is the lowest level of coverage.
    Basic,
}

/// Specifies the trie type to use.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
enum TrieType {
    /// Fast tries are optimized for speed
    #[serde(rename = "fast")]
    Fast,
    /// Small tries are optimized for size
    #[serde(rename = "small")]
    #[default]
    Small,
}

impl std::fmt::Display for TrieType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            TrieType::Fast => write!(f, "fast"),
            TrieType::Small => write!(f, "small"),
        }
    }
}