Debian Codegraph @

debian/rust-vendor/icu_datetime/src/provider/time_zones.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 //! Data provider structs for time zones.
6
7 use alloc::borrow::Cow;
8 use icu_pattern::{DoublePlaceholderPattern, SinglePlaceholderPattern};
9 use icu_provider::prelude::*;
10 use icu_time::{TimeZone, zone::TimeZoneVariant};
11 use zerovec::{ZeroMap, ZeroVec};
12
13 pub use icu_time::provider::MetazoneId;
14
15 /// Time zone type aliases for cleaner code
16 pub(crate) mod tz {
17 pub(crate) use super::ExemplarCities;
18 pub(crate) use super::Locations;
19 pub(crate) use super::MetazoneGenericNames as MzGeneric;
20 pub(crate) use super::MetazoneSpecificNames as MzSpecific;
21 pub(crate) use super::TimeZoneEssentials as Essentials;
22 pub(crate) use super::TimezoneNamesCitiesOverrideV1 as CitiesOverrideV1;
23 pub(crate) use super::TimezoneNamesCitiesRootV1 as CitiesRootV1;
24 pub(crate) use super::TimezoneNamesEssentialsV1 as EssentialsV1;
25 pub(crate) use super::TimezoneNamesGenericLongV1 as MzGenericLongV1;
26 pub(crate) use super::TimezoneNamesGenericShortV1 as MzGenericShortV1;
27 pub(crate) use super::TimezoneNamesLocationsOverrideV1 as LocationsOverrideV1;
28 pub(crate) use super::TimezoneNamesLocationsRootV1 as LocationsRootV1;
29 pub(crate) use super::TimezoneNamesSpecificLongV1 as MzSpecificLongV1;
30 pub(crate) use super::TimezoneNamesSpecificShortV1 as MzSpecificShortV1;
31 pub(crate) use super::TimezoneNamesStandardLongV1 as MzStandardLongV1;
32 pub(crate) use icu_time::provider::TimezonePeriods as MzPeriod;
33 pub(crate) use icu_time::provider::TimezonePeriodsV1 as MzPeriodV1;
34 }
35
36 icu_provider::data_marker!(
37 /// `TimezoneNamesEssentialsV1`
38 TimezoneNamesEssentialsV1,
39 TimeZoneEssentials<'static>
40 );
41 icu_provider::data_marker!(
42 /// `TimezoneNamesLocationsOverrideV1`
43 TimezoneNamesLocationsOverrideV1,
44 Locations<'static>
45 );
46 icu_provider::data_marker!(
47 /// `TimezoneNamesLocationsRootV1`
48 TimezoneNamesLocationsRootV1,
49 Locations<'static>
50 );
51 icu_provider::data_marker!(
52 /// `TimezoneNamesCitiesOverrideV1`
53 TimezoneNamesCitiesOverrideV1,
54 ExemplarCities<'static>
55 );
56 icu_provider::data_marker!(
57 /// `TimezoneNamesCitiesRootV1`
58 TimezoneNamesCitiesRootV1,
59 ExemplarCities<'static>
60 );
61
62 icu_provider::data_marker!(
63 /// `TimezoneNamesGenericLongV1`
64 ///
65 /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
66 TimezoneNamesGenericLongV1,
67 MetazoneGenericNames<'static>,
68 has_checksum = true
69 );
70 icu_provider::data_marker!(
71 /// `TimezoneNamesGenericShortV1`
72 ///
73 /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
74 TimezoneNamesGenericShortV1,
75 MetazoneGenericNames<'static>,
76 has_checksum = true
77 );
78 icu_provider::data_marker!(
79 /// `TimezoneNamesStandardLongV1`
80 ///
81 /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
82 TimezoneNamesStandardLongV1,
83 MetazoneGenericNames<'static>,
84 has_checksum = true
85 );
86 icu_provider::data_marker!(
87 /// `TimezoneNamesSpecificLongV1`
88 ///
89 /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
90 TimezoneNamesSpecificLongV1,
91 MetazoneSpecificNames<'static>,
92 has_checksum = true
93 );
94 icu_provider::data_marker!(
95 /// `TimezoneNamesSpecificShortV1`
96 ///
97 /// Checksumed to ensure consistency with [`TimezoneMetazonePeriodsV1`].
98 TimezoneNamesSpecificShortV1,
99 MetazoneSpecificNames<'static>,
100 has_checksum = true,
101 );
102
103 /// An ICU4X mapping to the CLDR timeZoneNames format strings.
104 /// See CLDR-JSON timeZoneNames.json and <https://cldr.unicode.org/translation/time-zones-and-city-names>
105 /// for more context.
106 ///
107 /// <div class="stab unstable">
108 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
109 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
110 /// to be stable, their Rust representation might not be. Use with caution.
111 /// </div>
112 #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
113 #[cfg_attr(feature = "datagen", derive(databake::Bake))]
114 #[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
115 #[yoke(prove_covariance_manually)]
116 pub struct TimeZoneEssentials<'data> {
117 /// The separator sign
118 pub offset_separator: Cow<'data, str>,
119 /// The localized offset format.
120 pub offset_pattern: Cow<'data, SinglePlaceholderPattern>,
121 /// The localized unknown-offset format.
122 pub offset_unknown: Cow<'data, str>,
123 }
124
125 #[cfg(feature = "serde")]
126 impl<'de> serde::Deserialize<'de> for TimeZoneEssentials<'de> {
127 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
128 where
129 D: serde::Deserializer<'de>,
130 {
131 #[derive(serde::Deserialize)]
132 struct Raw<'data> {
133 #[cfg_attr(feature = "serde", serde(borrow))]
134 offset_separator: Cow<'data, str>,
135 #[cfg_attr(
136 feature = "serde",
137 serde(
138 borrow,
139 deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
140 )
141 )]
142 offset_pattern: Cow<'data, SinglePlaceholderPattern>,
143 #[cfg_attr(feature = "serde", serde(borrow))]
144 offset_zero: Cow<'data, str>,
145 #[cfg_attr(feature = "serde", serde(borrow))]
146 offset_unknown: Cow<'data, str>,
147 }
148
149 let Raw {
150 offset_separator,
151 offset_pattern,
152 offset_unknown,
153 offset_zero: _offset_zero,
154 } = Raw::deserialize(deserializer)?;
155 Ok(TimeZoneEssentials {
156 offset_separator,
157 offset_pattern,
158 offset_unknown,
159 })
160 }
161 }
162
163 #[cfg(feature = "datagen")]
164 impl serde::Serialize for TimeZoneEssentials<'_> {
165 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166 where
167 S: serde::Serializer,
168 {
169 #[derive(serde::Serialize)]
170 struct Raw<'data> {
171 offset_separator: Cow<'data, str>,
172 offset_pattern: Cow<'data, SinglePlaceholderPattern>,
173 offset_zero: Cow<'data, str>,
174 offset_unknown: Cow<'data, str>,
175 }
176
177 Raw {
178 offset_separator: Cow::Borrowed(&self.offset_separator),
179 offset_pattern: Cow::Borrowed(&self.offset_pattern),
180 offset_zero: Cow::Borrowed(""),
181 offset_unknown: Cow::Borrowed(&self.offset_unknown),
182 }
183 .serialize(serializer)
184 }
185 }
186
187 icu_provider::data_struct!(
188 TimeZoneEssentials<'_>,
189 #[cfg(feature = "datagen")]
190 );
191
192 /// An ICU4X mapping to the CLDR timeZoneNames exemplar cities.
193 /// See CLDR-JSON timeZoneNames.json for more context.
194 ///
195 /// <div class="stab unstable">
196 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
197 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
198 /// to be stable, their Rust representation might not be. Use with caution.
199 /// </div>
200 #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
201 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
202 #[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
203 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
204 #[yoke(prove_covariance_manually)]
205 pub struct Locations<'data> {
206 /// Per-zone location display name
207 #[cfg_attr(feature = "serde", serde(borrow))]
208 pub locations: ZeroMap<'data, TimeZone, str>,
209 /// The format string for a region's generic time.
210 #[cfg_attr(
211 feature = "serde",
212 serde(
213 borrow,
214 deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
215 )
216 )]
217 pub pattern_generic: Cow<'data, SinglePlaceholderPattern>,
218 /// The format string for a region's standard time.
219 #[cfg_attr(
220 feature = "serde",
221 serde(
222 borrow,
223 deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
224 )
225 )]
226 pub pattern_standard: Cow<'data, SinglePlaceholderPattern>,
227 /// The format string for a region's daylight time.
228 #[cfg_attr(
229 feature = "serde",
230 serde(
231 borrow,
232 deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::SinglePlaceholder, _>"
233 )
234 )]
235 pub pattern_daylight: Cow<'data, SinglePlaceholderPattern>,
236 /// Metazone Name with Location Pattern.
237 #[cfg_attr(
238 feature = "serde",
239 serde(
240 borrow,
241 deserialize_with = "icu_pattern::deserialize_borrowed_cow::<icu_pattern::DoublePlaceholder, _>"
242 )
243 )]
244 pub pattern_partial_location: Cow<'data, DoublePlaceholderPattern>,
245 }
246
247 icu_provider::data_struct!(
248 Locations<'_>,
249 #[cfg(feature = "datagen")]
250 );
251
252 /// An ICU4X mapping to the CLDR timeZoneNames exemplar cities.
253 /// See CLDR-JSON timeZoneNames.json for more context.
254 ///
255 /// <div class="stab unstable">
256 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
257 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
258 /// to be stable, their Rust representation might not be. Use with caution.
259 /// </div>
260 #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
261 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
262 #[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
263 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
264 #[yoke(prove_covariance_manually)]
265 pub struct ExemplarCities<'data> {
266 /// Per-zone exemplar city name. This is deduplicated against `Locations.locations`, so it
267 /// only contains time zones that don't use the exemplar city in the location format.
268 #[cfg_attr(feature = "serde", serde(borrow))]
269 pub exemplars: ZeroMap<'data, TimeZone, str>,
270 }
271
272 icu_provider::data_struct!(
273 ExemplarCities<'_>,
274 #[cfg(feature = "datagen")]
275 );
276
277 /// An ICU4X mapping to generic metazone names.
278 /// See CLDR-JSON timeZoneNames.json for more context.
279 ///
280 /// <div class="stab unstable">
281 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
282 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
283 /// to be stable, their Rust representation might not be. Use with caution.
284 /// </div>
285 #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
286 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
287 #[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
288 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
289 #[yoke(prove_covariance_manually)]
290 pub struct MetazoneGenericNames<'data> {
291 /// The default mapping between metazone id and localized metazone name.
292 #[cfg_attr(feature = "serde", serde(borrow))]
293 pub defaults: ZeroMap<'data, MetazoneId, str>,
294 /// The override mapping between timezone id and localized metazone name.
295 #[cfg_attr(feature = "serde", serde(borrow))]
296 pub overrides: ZeroMap<'data, TimeZone, str>,
297 }
298
299 icu_provider::data_struct!(
300 MetazoneGenericNames<'_>,
301 #[cfg(feature = "datagen")]
302 );
303
304 /// An ICU4X mapping to specific metazone names.
305 /// Specific names include time variants such as "daylight."
306 /// See CLDR-JSON timeZoneNames.json for more context.
307 ///
308 /// These markers use a checksum to ensure consistency with [`icu_time::provider::TimezonePeriodsV1`].
309 ///
310 /// <div class="stab unstable">
311 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
312 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
313 /// to be stable, their Rust representation might not be. Use with caution.
314 /// </div>
315 #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
316 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
317 #[cfg_attr(feature = "datagen", databake(path = icu_datetime::provider::time_zones))]
318 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
319 #[yoke(prove_covariance_manually)]
320 pub struct MetazoneSpecificNames<'data> {
321 /// The default mapping between metazone id and localized metazone name.
322 #[cfg_attr(feature = "serde", serde(borrow))]
323 pub defaults: ZeroMap<'data, (MetazoneId, TimeZoneVariant), str>,
324 /// The override mapping between timezone id and localized metazone name.
325 #[cfg_attr(feature = "serde", serde(borrow))]
326 pub overrides: ZeroMap<'data, (TimeZone, TimeZoneVariant), str>,
327 /// The metazones for which the standard name is in `MetazoneGenericStandardNames*V1`
328 #[cfg_attr(feature = "serde", serde(borrow))]
329 pub use_standard: ZeroVec<'data, MetazoneId>,
330 }
331
332 icu_provider::data_struct!(
333 MetazoneSpecificNames<'_>,
334 #[cfg(feature = "datagen")]
335 );
336
337 #[cfg(feature = "serde")]
338 pub(crate) mod legacy {
339 use super::*;
340 use icu_time::zone::ZoneNameTimestamp;
341 use zerovec::ZeroMap2d;
342 use zerovec::ule::NichedOption;
343
344 icu_provider::data_marker!(
345 /// `TimezoneMetazonePeriodsV1`
346 TimezoneMetazonePeriodsV1,
347 MetazonePeriod<'static>,
348 is_singleton = true,
349 has_checksum = true
350 );
351
352 /// An ICU4X mapping to the metazones at a given period.
353 /// See CLDR-JSON metaZones.json for more context.
354 ///
355 /// <div class="stab unstable">
356 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
357 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
358 /// to be stable, their Rust representation might not be. Use with caution.
359 /// </div>
360 #[derive(PartialEq, Debug, Clone, Default, yoke::Yokeable, zerofrom::ZeroFrom)]
361 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
362 #[yoke(prove_covariance_manually)]
363 #[allow(dead_code, reason = "We construct this struct through serde impls")]
364 pub struct MetazonePeriod<'data> {
365 /// The default mapping between period and offsets. The second level key is a wall-clock time encoded as
366 /// [`ZoneNameTimestamp`]. It represents when the metazone started to be used.
367 #[cfg_attr(feature = "serde", serde(borrow))]
368 pub list: ZeroMap2d<'data, TimeZone, ZoneNameTimestamp, NichedOption<MetazoneId, 1>>,
369 }
370
371 icu_provider::data_struct!(
372 MetazonePeriod<'_>,
373 #[cfg(feature = "datagen")]
374 );
375
376 #[inline(never)] // keep this compat code self-contained and not duplicated
377 pub(crate) fn metazone_timezone_compat(
378 provider: &impl BufferProvider,
379 req: DataRequest<'_>,
380 ) -> Result<DataResponse<icu_time::provider::TimezonePeriodsV1>, DataError> {
381 use alloc::vec::Vec;
382 use icu_time::provider::Timestamp24;
383 use icu_time::provider::TimezonePeriods;
384 use zerotrie::ZeroTrieSimpleAscii;
385 use zerovec::ule::AsULE;
386 use zerovec::ule::vartuple::VarTuple;
387 use zerovec::vecs::VarZeroVecOwned;
388
389 let DataResponse::<TimezoneMetazonePeriodsV1> {
390 payload: old_payload,
391 metadata,
392 } = provider.as_deserializing().load(req)?;
393
394 let index = ZeroTrieSimpleAscii::<Vec<u8>>::from_iter(
395 old_payload
396 .get()
397 .list
398 .iter0()
399 .enumerate()
400 .map(|(i, v)| (v.key0().as_str(), i)),
401 )
402 .convert_store();
403
404 let mut list = VarZeroVecOwned::new();
405
406 for ps in old_payload.get().list.iter0() {
407 let mut cursor = ps.into_iter1_copied();
408 let Some((_, mz)) = cursor.next() else {
409 continue; // unreachable
410 };
411
412 let rest = cursor
413 .map(move |(&t, mz)| (Timestamp24(ZoneNameTimestamp::from_unaligned(t)), 0, mz))
414 .collect::<ZeroVec<_>>();
415
416 let rest = VarTuple {
417 sized: (0, mz),
418 variable: rest.as_slice(),
419 };
420
421 list.push(&rest);
422 }
423
424 Ok(DataResponse {
425 payload: DataPayload::from_owned(TimezonePeriods {
426 index,
427 list: list.into(),
428 offsets: ZeroVec::from(alloc::vec![Default::default()]),
429 }),
430 metadata,
431 })
432 }
433
434 #[test]
435 fn test_metazone_timezone_compat() {
436 let converted = metazone_timezone_compat(
437 &icu_provider_blob::BlobDataProvider::try_new_from_static_blob(
438 // icu4x-datagen --markers TimezoneMetazonePeriodsV1 --format blob
439 include_bytes!("../../tests/data/metazone_periods_old.postcard"),
440 )
441 .unwrap(),
442 Default::default(),
443 )
444 .unwrap()
445 .payload;
446
447 let tz = TimeZone::from_iana_id("Antarctica/Casey");
448 for t in [
449 ZoneNameTimestamp::from_epoch_seconds(0),
450 ZoneNameTimestamp::from_epoch_seconds(1255802400),
451 ZoneNameTimestamp::from_epoch_seconds(1267714800),
452 ZoneNameTimestamp::from_epoch_seconds(1319738400),
453 ZoneNameTimestamp::from_epoch_seconds(1329843600),
454 ZoneNameTimestamp::from_epoch_seconds(1477065600),
455 ZoneNameTimestamp::from_epoch_seconds(1520701200),
456 ZoneNameTimestamp::from_epoch_seconds(1538856000),
457 ZoneNameTimestamp::from_epoch_seconds(1552752000),
458 ZoneNameTimestamp::from_epoch_seconds(1570129200),
459 ZoneNameTimestamp::from_epoch_seconds(1583596800),
460 ZoneNameTimestamp::from_epoch_seconds(1615640400),
461 ZoneNameTimestamp::from_epoch_seconds(1647090000),
462 ZoneNameTimestamp::from_epoch_seconds(1678291200),
463 ] {
464 assert_eq!(
465 converted
466 .get()
467 .get(tz, t)
468 .unwrap()
469 .1
470 .map(|mz| match mz.id.get() {
471 // the ID list changed with CLDR 48
472 22 => 21,
473 31 => 30,
474 _ => unreachable!(),
475 }),
476 icu_time::provider::Baked::SINGLETON_TIMEZONE_PERIODS_V1
477 .get(tz, t)
478 .unwrap()
479 .1
480 .map(|mz| mz.id.get()),
481 "{t:?}",
482 );
483 }
484 }
485 }