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
// 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 ).

//! Resource paths and related types.

use crate::error::Error;
use alloc::borrow::Cow;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;

use core::borrow::Borrow;
use core::default::Default;
use core::fmt;
use core::fmt::Write;
use icu_locid::LanguageIdentifier;
use tinystr::{TinyStr16, TinyStr4};

/// A top-level collection of related resource keys.
#[non_exhaustive]
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)]
pub enum ResourceCategory {
    Core,
    DateTime,
    Decimal,
    LocaleCanonicalizer,
    Plurals,
    TimeZone,
    UnicodeSet,
    PrivateUse(TinyStr4),
}

impl ResourceCategory {
    /// Gets or builds a string form of this [`ResourceCategory`].
    pub fn as_str(&self) -> Cow<'static, str> {
        match self {
            Self::Core => Cow::Borrowed("core"),
            Self::DateTime => Cow::Borrowed("datetime"),
            Self::Decimal => Cow::Borrowed("decimal"),
            Self::LocaleCanonicalizer => Cow::Borrowed("locale_canonicalizer"),
            Self::Plurals => Cow::Borrowed("plurals"),
            Self::TimeZone => Cow::Borrowed("time_zone"),
            Self::UnicodeSet => Cow::Borrowed("uniset"),
            Self::PrivateUse(id) => {
                let mut result = String::from("x-");
                result.push_str(id.as_str());
                Cow::Owned(result)
            }
        }
    }
}

impl fmt::Display for ResourceCategory {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.as_str())
    }
}

impl writeable::Writeable for ResourceCategory {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        sink.write_str(&self.as_str())
    }

    fn write_len(&self) -> writeable::LengthHint {
        writeable::LengthHint::Exact(self.as_str().len())
    }
}

/// A category, subcategory, and version, used for requesting data from a
/// [`DataProvider`](crate::DataProvider).
///
/// The fields in a [`ResourceKey`] should generally be known at compile time.
///
/// Use [`resource_key!`] as a shortcut to create resource keys in code.
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub struct ResourceKey {
    pub category: ResourceCategory,
    pub sub_category: TinyStr16,
    pub version: u16,
}

/// Shortcut to construct a const resource identifier.
///
/// # Examples
///
/// Create a private-use ResourceKey:
///
/// ```
/// use icu_provider::prelude::*;
///
/// const MY_PRIVATE_USE_KEY: ResourceKey = icu_provider::resource_key!(x, "foo", "bar", 1);
/// assert_eq!("x-foo/bar@1", format!("{}", MY_PRIVATE_USE_KEY));
/// ```
///
/// Create a ResourceKey for a specific [`ResourceCategory`] (for ICU4X library code only):
///
/// ```
/// use icu_provider::prelude::*;
///
/// const MY_PRIVATE_USE_KEY: ResourceKey = icu_provider::resource_key!(Plurals, "ordinal", 1);
/// assert_eq!("plurals/ordinal@1", format!("{}", MY_PRIVATE_USE_KEY));
/// ```
#[macro_export]
macro_rules! resource_key {
    ($category:ident, $sub_category:literal, $version:tt) => {
        $crate::resource_key!($crate::ResourceCategory::$category, $sub_category, $version)
    };
    (x, $pu:literal, $sub_category:literal, $version:tt) => {
        $crate::resource_key!(
            $crate::ResourceCategory::PrivateUse($crate::internal::tinystr4!($pu)),
            $sub_category,
            $version
        )
    };
    ($category:expr, $sub_category:literal, $version:tt) => {
        $crate::ResourceKey {
            category: $category,
            sub_category: $crate::internal::tinystr16!($sub_category),
            version: $version,
        }
    };
}

impl fmt::Debug for ResourceKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("ResourceKey{")?;
        fmt::Display::fmt(self, f)?;
        f.write_char('}')?;
        Ok(())
    }
}

impl fmt::Display for ResourceKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeable::Writeable::write_to(self, f)
    }
}

impl writeable::Writeable for ResourceKey {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        sink.write_str(&self.category.as_str())?;
        sink.write_char('/')?;
        sink.write_str(self.sub_category.as_str())?;
        sink.write_char('@')?;
        write!(sink, "{}", self.version)?;
        Ok(())
    }

    fn write_len(&self) -> writeable::LengthHint {
        writeable::LengthHint::Exact(2)
            + self.category.as_str().len()
            + self.sub_category.len()
            + if self.version < 10 {
                1
            } else if self.version < 100 {
                2
            } else if self.version < 1000 {
                3
            } else if self.version < 10000 {
                4
            } else {
                5
            }
    }
}

impl ResourceKey {
    /// Gets the standard path components of this [`ResourceKey`]. These components should be used when
    /// persisting the [`ResourceKey`] on the filesystem or in structured data.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    ///
    /// let resc_key = icu_provider::hello_world::key::HELLO_WORLD_V1;
    /// let components = resc_key.get_components();
    ///
    /// assert_eq!(
    ///     ["core", "helloworld@1"],
    ///     components.iter().collect::<Vec<&str>>()[..]
    /// );
    /// ```
    pub fn get_components(&self) -> ResourceKeyComponents {
        self.into()
    }

    /// Returns [`Ok`] if this data key matches the argument, or the appropriate error.
    ///
    /// Convenience method for data providers that support a single [`ResourceKey`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    ///
    /// const FOO_BAR: ResourceKey = icu_provider::resource_key!(x, "foo", "bar", 1);
    /// const FOO_BAZ: ResourceKey = icu_provider::resource_key!(x, "foo", "baz", 1);
    /// const BAR_BAZ: ResourceKey = icu_provider::resource_key!(x, "bar", "baz", 1);
    ///
    /// assert!(matches!(FOO_BAR.match_key(FOO_BAR), Ok(())));
    /// assert!(matches!(FOO_BAR.match_key(FOO_BAZ), Err(DataError::MissingResourceKey(_))));
    /// assert!(matches!(FOO_BAR.match_key(BAR_BAZ), Err(DataError::MissingResourceKey(_))));
    /// ```
    pub fn match_key(&self, key: Self) -> Result<(), Error> {
        if *self == key {
            Ok(())
        } else {
            Err(Error::MissingResourceKey(*self))
        }
    }
}

/// The standard components of a [`ResourceKey`] path.
pub struct ResourceKeyComponents {
    components: [Cow<'static, str>; 2],
}

impl ResourceKeyComponents {
    pub fn iter(&self) -> impl Iterator<Item = &str> {
        self.components.iter().map(|cow| cow.borrow())
    }
}

impl From<&ResourceKey> for ResourceKeyComponents {
    fn from(resc_key: &ResourceKey) -> Self {
        Self {
            components: [
                resc_key.category.as_str(),
                // TODO: Evalute the size penalty of this format!
                Cow::Owned(format!(
                    "{}@{}",
                    resc_key.sub_category.as_str(),
                    resc_key.version
                )),
            ],
        }
    }
}

/// A variant and language identifier, used for requesting data from a
/// [`DataProvider`](crate::DataProvider).
///
/// The fields in a [`ResourceOptions`] are not generally known until runtime.
#[derive(PartialEq, Clone)]
pub struct ResourceOptions {
    // TODO: Consider making multiple variant fields.
    pub variant: Option<Cow<'static, str>>,
    pub langid: Option<LanguageIdentifier>,
}

impl fmt::Debug for ResourceOptions {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ResourceOptions{{{}}}", self)
    }
}

impl fmt::Display for ResourceOptions {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeable::Writeable::write_to(self, f)
    }
}

impl writeable::Writeable for ResourceOptions {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        let mut initial = true;
        for component in self.get_components().iter() {
            if initial {
                initial = false;
            } else {
                sink.write_char('/')?;
            }
            sink.write_str(component)?;
        }
        Ok(())
    }

    fn write_len(&self) -> writeable::LengthHint {
        let mut result = 0;
        let mut initial = true;
        for component in self.get_components().iter() {
            if initial {
                initial = false;
            } else {
                result += 1;
            }
            result += component.len();
        }
        writeable::LengthHint::Exact(result)
    }
}

impl Default for ResourceOptions {
    fn default() -> Self {
        Self {
            variant: None,
            langid: None,
        }
    }
}

impl From<LanguageIdentifier> for ResourceOptions {
    /// Create a ResourceOptions with the given language identifier and an empty variant field.
    fn from(langid: LanguageIdentifier) -> Self {
        Self {
            langid: Some(langid),
            variant: None,
        }
    }
}

impl ResourceOptions {
    /// Gets the standard path components of this [`ResourceOptions`]. These components should be used when
    /// persisting the [`ResourceOptions`] on the filesystem or in structured data.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::borrow::Cow;
    /// use icu_provider::prelude::*;
    /// use icu_locid_macros::langid;
    ///
    /// let resc_options = ResourceOptions {
    ///     variant: Some(Cow::Borrowed("GBP")),
    ///     langid: Some(langid!("pt_BR")),
    /// };
    /// let components = resc_options.get_components();
    ///
    /// assert_eq!(
    ///     ["GBP", "pt-BR"],
    ///     components.iter().collect::<Vec<&str>>()[..]
    /// );
    /// ```
    pub fn get_components(&self) -> ResourceOptionsComponents {
        self.into()
    }

    /// Returns whether this [`ResourceOptions`] has all empty fields (no components).
    pub fn is_empty(&self) -> bool {
        self == &Self::default()
    }
}

/// The standard components of a [`ResourceOptions`] path.
pub struct ResourceOptionsComponents {
    components: [Option<Cow<'static, str>>; 2],
}

impl ResourceOptionsComponents {
    pub fn iter(&self) -> impl Iterator<Item = &str> {
        self.components
            .iter()
            .filter_map(|option| option.as_ref().map(|cow| cow.borrow()))
    }
}

impl From<&ResourceOptions> for ResourceOptionsComponents {
    fn from(resc_options: &ResourceOptions) -> Self {
        Self {
            components: [
                resc_options.variant.as_ref().cloned(),
                resc_options
                    .langid
                    .as_ref()
                    .map(|s| Cow::Owned(s.to_string())),
            ],
        }
    }
}

#[derive(Clone, PartialEq)]
pub struct ResourcePath {
    pub key: ResourceKey,
    pub options: ResourceOptions,
}

impl fmt::Debug for ResourcePath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ResourcePath{{{}}}", self)
    }
}

impl fmt::Display for ResourcePath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeable::Writeable::write_to(self, f)
    }
}

impl writeable::Writeable for ResourcePath {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        writeable::Writeable::write_to(&self.key, sink)?;
        if !self.options.is_empty() {
            sink.write_char('/')?;
            writeable::Writeable::write_to(&self.options, sink)?;
        }
        Ok(())
    }

    fn write_len(&self) -> writeable::LengthHint {
        let mut result = writeable::Writeable::write_len(&self.key);
        if !self.options.is_empty() {
            result += writeable::Writeable::write_len(&self.options) + 1;
        }
        result
    }
}

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

    struct KeyTestCase {
        pub resc_key: ResourceKey,
        pub expected: &'static str,
    }

    fn get_key_test_cases() -> [KeyTestCase; 4] {
        [
            KeyTestCase {
                resc_key: resource_key!(Core, "cardinal", 1),
                expected: "core/cardinal@1",
            },
            KeyTestCase {
                resc_key: ResourceKey {
                    category: ResourceCategory::PrivateUse(tinystr4!("priv")),
                    sub_category: tinystr::tinystr16!("cardinal"),
                    version: 1,
                },
                expected: "x-priv/cardinal@1",
            },
            KeyTestCase {
                resc_key: resource_key!(Core, "maxlengthsubcatg", 1),
                expected: "core/maxlengthsubcatg@1",
            },
            KeyTestCase {
                resc_key: resource_key!(Core, "cardinal", 65535),
                expected: "core/cardinal@65535",
            },
        ]
    }

    #[test]
    fn test_options_to_string() {
        for cas in get_key_test_cases().iter() {
            assert_eq!(cas.expected, cas.resc_key.to_string());
            writeable::assert_writeable_eq!(cas.expected, &cas.resc_key);
            assert_eq!(
                cas.expected,
                cas.resc_key
                    .get_components()
                    .iter()
                    .collect::<Vec<&str>>()
                    .join("/")
            );
        }
    }

    struct OptionsTestCase {
        pub resc_options: ResourceOptions,
        pub expected: &'static str,
    }

    fn get_options_test_cases() -> [OptionsTestCase; 3] {
        use icu_locid_macros::langid;
        [
            OptionsTestCase {
                resc_options: ResourceOptions {
                    variant: None,
                    langid: Some(LanguageIdentifier::und()),
                },
                expected: "und",
            },
            OptionsTestCase {
                resc_options: ResourceOptions {
                    variant: Some(Cow::Borrowed("GBP")),
                    langid: Some(LanguageIdentifier::und()),
                },
                expected: "GBP/und",
            },
            OptionsTestCase {
                resc_options: ResourceOptions {
                    variant: Some(Cow::Borrowed("GBP")),
                    langid: Some(langid!("en-ZA")),
                },
                expected: "GBP/en-ZA",
            },
        ]
    }

    #[test]
    fn test_key_to_string() {
        for cas in get_options_test_cases().iter() {
            assert_eq!(cas.expected, cas.resc_options.to_string());
            writeable::assert_writeable_eq!(cas.expected, &cas.resc_options);
            assert_eq!(
                cas.expected,
                cas.resc_options
                    .get_components()
                    .iter()
                    .collect::<Vec<&str>>()
                    .join("/")
            );
        }
    }

    #[test]
    fn test_resource_path_to_string() {
        for key_cas in get_key_test_cases().iter() {
            for options_cas in get_options_test_cases().iter() {
                let expected = if options_cas.resc_options.is_empty() {
                    key_cas.expected.to_string()
                } else {
                    format!("{}/{}", key_cas.expected, options_cas.expected)
                };
                let resource_path = ResourcePath {
                    key: key_cas.resc_key,
                    // Note: once https://github.com/rust-lang/rust/pull/80470 is accepted,
                    // we won't have to clone here.
                    options: options_cas.resc_options.clone(),
                };
                assert_eq!(expected, resource_path.to_string());
                writeable::assert_writeable_eq!(expected, &resource_path);
            }
        }
    }
}