icu_datetime 2.2.0

Human-readable formatting of dates, times, and time zones in hundreds of locales
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
// 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 ).

//! Data provider structs for time zones.

use alloc::borrow::Cow;
use icu_pattern::{DoublePlaceholderPattern, SinglePlaceholderPattern};
use icu_provider::prelude::*;
use icu_time::{zone::TimeZoneVariant, TimeZone};
use zerovec::{ZeroMap, ZeroVec};

pub use icu_time::provider::MetazoneId;

/// Time zone type aliases for cleaner code
pub(crate) mod tz {
    pub(crate) use super::ExemplarCities;
    pub(crate) use super::Locations;
    pub(crate) use super::MetazoneGenericNames as MzGeneric;
    pub(crate) use super::MetazoneSpecificNames as MzSpecific;
    pub(crate) use super::TimeZoneEssentials as Essentials;
    pub(crate) use super::TimezoneNamesCitiesOverrideV1 as CitiesOverrideV1;
    pub(crate) use super::TimezoneNamesCitiesRootV1 as CitiesRootV1;
    pub(crate) use super::TimezoneNamesEssentialsV1 as EssentialsV1;
    pub(crate) use super::TimezoneNamesGenericLongV1 as MzGenericLongV1;
    pub(crate) use super::TimezoneNamesGenericShortV1 as MzGenericShortV1;
    pub(crate) use super::TimezoneNamesLocationsOverrideV1 as LocationsOverrideV1;
    pub(crate) use super::TimezoneNamesLocationsRootV1 as LocationsRootV1;
    pub(crate) use super::TimezoneNamesSpecificLongV1 as MzSpecificLongV1;
    pub(crate) use super::TimezoneNamesSpecificShortV1 as MzSpecificShortV1;
    pub(crate) use super::TimezoneNamesStandardLongV1 as MzStandardLongV1;
    pub(crate) use icu_time::provider::TimezonePeriods as MzPeriod;
    pub(crate) use icu_time::provider::TimezonePeriodsV1 as MzPeriodV1;
}

icu_provider::data_marker!(
    /// `TimezoneNamesEssentialsV1`
    TimezoneNamesEssentialsV1,
    TimeZoneEssentials<'static>
);
icu_provider::data_marker!(
    /// `TimezoneNamesLocationsOverrideV1`
    TimezoneNamesLocationsOverrideV1,
    Locations<'static>
);
icu_provider::data_marker!(
    /// `TimezoneNamesLocationsRootV1`
    TimezoneNamesLocationsRootV1,
    Locations<'static>
);
icu_provider::data_marker!(
    /// `TimezoneNamesCitiesOverrideV1`
    TimezoneNamesCitiesOverrideV1,
    ExemplarCities<'static>
);
icu_provider::data_marker!(
    /// `TimezoneNamesCitiesRootV1`
    TimezoneNamesCitiesRootV1,
    ExemplarCities<'static>
);

icu_provider::data_marker!(
    /// `TimezoneNamesGenericLongV1`
    ///
    /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
    TimezoneNamesGenericLongV1,
    MetazoneGenericNames<'static>,
    has_checksum = true
);
icu_provider::data_marker!(
    /// `TimezoneNamesGenericShortV1`
    ///
    /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
    TimezoneNamesGenericShortV1,
    MetazoneGenericNames<'static>,
    has_checksum = true
);
icu_provider::data_marker!(
    /// `TimezoneNamesStandardLongV1`
    ///
    /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
    TimezoneNamesStandardLongV1,
    MetazoneGenericNames<'static>,
    has_checksum = true
);
icu_provider::data_marker!(
    /// `TimezoneNamesSpecificLongV1`
    ///
    /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
    TimezoneNamesSpecificLongV1,
    MetazoneSpecificNames<'static>,
    has_checksum = true
);
icu_provider::data_marker!(
    /// `TimezoneNamesSpecificShortV1`
    ///
    /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
    TimezoneNamesSpecificShortV1,
    MetazoneSpecificNames<'static>,
    has_checksum = true,
);

/// An ICU4X mapping to the CLDR timeZoneNames format strings.
/// See CLDR-JSON timeZoneNames.json and <https://cldr.unicode.org/translation/time-zones-and-city-names>
/// for more context.
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[yoke(prove_covariance_manually)]
pub struct TimeZoneEssentials<'data> {
    /// The separator sign
    #[cfg_attr(feature = "serde", serde(borrow,))]
    pub offset_separator: Cow<'data, str>,
    /// The localized offset format.
    #[cfg_attr(
        feature = "serde",
        serde(
            borrow,
            deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
        )
    )]
    pub offset_pattern: Cow<'data, SinglePlaceholderPattern>,
    /// The localized zero-offset format.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub offset_zero: Cow<'data, str>,
    /// The localized unknown-offset format.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub offset_unknown: Cow<'data, str>,
}

icu_provider::data_struct!(
    TimeZoneEssentials<'_>,
    #[cfg(feature = "datagen")]
);

/// An ICU4X mapping to the CLDR timeZoneNames exemplar cities.
/// See CLDR-JSON timeZoneNames.json for more context.
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[yoke(prove_covariance_manually)]
pub struct Locations<'data> {
    /// Per-zone location display name
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub locations: ZeroMap<'data, TimeZone, str>,
    /// The format string for a region's generic time.
    #[cfg_attr(
        feature = "serde",
        serde(
            borrow,
            deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
        )
    )]
    pub pattern_generic: Cow<'data, SinglePlaceholderPattern>,
    /// The format string for a region's standard time.
    #[cfg_attr(
        feature = "serde",
        serde(
            borrow,
            deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
        )
    )]
    pub pattern_standard: Cow<'data, SinglePlaceholderPattern>,
    /// The format string for a region's daylight time.
    #[cfg_attr(
        feature = "serde",
        serde(
            borrow,
            deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
        )
    )]
    pub pattern_daylight: Cow<'data, SinglePlaceholderPattern>,
    /// Metazone Name with Location Pattern.
    #[cfg_attr(
        feature = "serde",
        serde(
            borrow,
            deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::DoublePlaceholder, _>"
        )
    )]
    pub pattern_partial_location: Cow<'data, DoublePlaceholderPattern>,
}

icu_provider::data_struct!(
    Locations<'_>,
    #[cfg(feature = "datagen")]
);

/// An ICU4X mapping to the CLDR timeZoneNames exemplar cities.
/// See CLDR-JSON timeZoneNames.json for more context.
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[yoke(prove_covariance_manually)]
pub struct ExemplarCities<'data> {
    /// Per-zone exemplar city name. This is deduplicated against `Locations.locations`, so it
    /// only contains time zones that don't use the exemplar city in the location format.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub exemplars: ZeroMap<'data, TimeZone, str>,
}

icu_provider::data_struct!(
    ExemplarCities<'_>,
    #[cfg(feature = "datagen")]
);

/// An ICU4X mapping to generic metazone names.
/// See CLDR-JSON timeZoneNames.json for more context.
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[yoke(prove_covariance_manually)]
pub struct MetazoneGenericNames<'data> {
    /// The default mapping between metazone id and localized metazone name.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub defaults: ZeroMap<'data, MetazoneId, str>,
    /// The override mapping between timezone id and localized metazone name.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub overrides: ZeroMap<'data, TimeZone, str>,
}

icu_provider::data_struct!(
    MetazoneGenericNames<'_>,
    #[cfg(feature = "datagen")]
);

/// An ICU4X mapping to specific metazone names.
/// Specific names include time variants such as "daylight."
/// See CLDR-JSON timeZoneNames.json for more context.
///
/// These markers use a checksum to ensure consistency with [`icu_time::provider::TimezonePeriodsV1`].
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[yoke(prove_covariance_manually)]
pub struct MetazoneSpecificNames<'data> {
    /// The default mapping between metazone id and localized metazone name.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub defaults: ZeroMap<'data, (MetazoneId, TimeZoneVariant), str>,
    /// The override mapping between timezone id and localized metazone name.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub overrides: ZeroMap<'data, (TimeZone, TimeZoneVariant), str>,
    /// The metazones for which the standard name is in `MetazoneGenericStandardNames*V1`
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub use_standard: ZeroVec<'data, MetazoneId>,
}

icu_provider::data_struct!(
    MetazoneSpecificNames<'_>,
    #[cfg(feature = "datagen")]
);

#[cfg(feature = "serde")]
pub(crate) mod legacy {
    use super::*;
    use icu_time::zone::ZoneNameTimestamp;
    use zerovec::ule::NichedOption;
    use zerovec::ZeroMap2d;

    icu_provider::data_marker!(
        /// `TimezoneMetazonePeriodsV1`
        TimezoneMetazonePeriodsV1,
        MetazonePeriod<'static>,
        is_singleton = true,
        has_checksum = true
    );

    /// An ICU4X mapping to the metazones at a given period.
    /// See CLDR-JSON metaZones.json for more context.
    ///
    /// <div class="stab unstable">
    /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
    /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
    /// to be stable, their Rust representation might not be. Use with caution.
    /// </div>
    #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
    #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
    #[yoke(prove_covariance_manually)]
    #[allow(dead_code, reason = "We construct this struct through serde impls")]
    pub struct MetazonePeriod<'data> {
        /// The default mapping between period and offsets. The second level key is a wall-clock time encoded as
        /// [`ZoneNameTimestamp`]. It represents when the metazone started to be used.
        #[cfg_attr(feature = "serde", serde(borrow))]
        pub list: ZeroMap2d<'data, TimeZone, ZoneNameTimestamp, NichedOption<MetazoneId, 1>>,
    }

    icu_provider::data_struct!(
        MetazonePeriod<'_>,
        #[cfg(feature = "datagen")]
    );

    #[inline(never)] // keep this compat code self-contained and not duplicated
    pub(crate) fn metazone_timezone_compat(
        provider: &impl BufferProvider,
        req: DataRequest<'_>,
    ) -> Result<DataResponse<icu_time::provider::TimezonePeriodsV1>, DataError> {
        use alloc::vec::Vec;
        use icu_time::provider::Timestamp24;
        use icu_time::provider::TimezonePeriods;
        use zerotrie::ZeroTrieSimpleAscii;
        use zerovec::ule::vartuple::VarTuple;
        use zerovec::ule::AsULE;
        use zerovec::vecs::VarZeroVecOwned;

        let DataResponse::<TimezoneMetazonePeriodsV1> {
            payload: old_payload,
            metadata,
        } = provider.as_deserializing().load(req)?;

        let index = ZeroTrieSimpleAscii::<Vec<u8>>::from_iter(
            old_payload
                .get()
                .list
                .iter0()
                .enumerate()
                .map(|(i, v)| (v.key0().as_str(), i)),
        )
        .convert_store();

        let mut list = VarZeroVecOwned::new();

        for ps in old_payload.get().list.iter0() {
            let mut cursor = ps.into_iter1_copied();
            let Some((_, mz)) = cursor.next() else {
                continue; // unreachable
            };

            let rest = cursor
                .map(move |(&t, mz)| (Timestamp24(ZoneNameTimestamp::from_unaligned(t)), 0, mz))
                .collect::<ZeroVec<_>>();

            let rest = VarTuple {
                sized: (0, mz),
                variable: rest.as_slice(),
            };

            list.push(&rest);
        }

        Ok(DataResponse {
            payload: DataPayload::from_owned(TimezonePeriods {
                index,
                list: list.into(),
                offsets: ZeroVec::from(alloc::vec![Default::default()]),
            }),
            metadata,
        })
    }

    #[test]
    fn test_metazone_timezone_compat() {
        let converted = metazone_timezone_compat(
            &icu_provider_blob::BlobDataProvider::try_new_from_static_blob(
                // icu4x-datagen --markers TimezoneMetazonePeriodsV1 --format blob
                include_bytes!("../../tests/data/metazone_periods_old.postcard"),
            )
            .unwrap(),
            Default::default(),
        )
        .unwrap()
        .payload;

        let tz = TimeZone::from_iana_id("Antarctica/Casey");
        for t in [
            ZoneNameTimestamp::from_epoch_seconds(0),
            ZoneNameTimestamp::from_epoch_seconds(1255802400),
            ZoneNameTimestamp::from_epoch_seconds(1267714800),
            ZoneNameTimestamp::from_epoch_seconds(1319738400),
            ZoneNameTimestamp::from_epoch_seconds(1329843600),
            ZoneNameTimestamp::from_epoch_seconds(1477065600),
            ZoneNameTimestamp::from_epoch_seconds(1520701200),
            ZoneNameTimestamp::from_epoch_seconds(1538856000),
            ZoneNameTimestamp::from_epoch_seconds(1552752000),
            ZoneNameTimestamp::from_epoch_seconds(1570129200),
            ZoneNameTimestamp::from_epoch_seconds(1583596800),
            ZoneNameTimestamp::from_epoch_seconds(1615640400),
            ZoneNameTimestamp::from_epoch_seconds(1647090000),
            ZoneNameTimestamp::from_epoch_seconds(1678291200),
        ] {
            assert_eq!(
                converted
                    .get()
                    .get(tz, t)
                    .unwrap()
                    .1
                    .map(|mz| match mz.id.get() {
                        // the ID list changed with CLDR 48
                        22 => 21,
                        31 => 30,
                        _ => unreachable!(),
                    }),
                icu_time::provider::Baked::SINGLETON_TIMEZONE_PERIODS_V1
                    .get(tz, t)
                    .unwrap()
                    .1
                    .map(|mz| mz.id.get()),
                "{t:?}",
            );
        }
    }
}