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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
// 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 ).
//! A formatter specifically for the time zone.
use crate::provider::time_zones::TimeZoneBcp47Id;
use alloc::borrow::Cow;
use alloc::string::String;
use core::fmt;
use icu_timezone::GmtOffset;
use smallvec::SmallVec;
use tinystr::tinystr;
use crate::{
error::DateTimeError,
fields::{FieldSymbol, TimeZone},
format::time_zone::FormattedTimeZone,
input::TimeZoneInput,
pattern::{PatternError, PatternItem},
provider::{self, calendar::patterns::PatternPluralsFromPatternsV1Marker},
};
use core::fmt::Write;
use icu_provider::prelude::*;
use writeable::{adapters::CoreWriteAsPartsWrite, Part, Writeable};
/// Loads a resource into its destination if the destination has not already been filled.
fn load<D, P>(
locale: &DataLocale,
destination: &mut Option<DataPayload<D>>,
provider: &P,
) -> Result<(), DateTimeError>
where
D: KeyedDataMarker,
P: DataProvider<D> + ?Sized,
{
if destination.is_none() {
*destination = Some(
provider
.load(DataRequest {
locale,
metadata: Default::default(),
})?
.take_payload()?,
);
}
Ok(())
}
/// [`TimeZoneFormatter`] is available for users who need to separately control the formatting of time
/// zones. Note: most users might prefer [`ZonedDateTimeFormatter`](super::ZonedDateTimeFormatter), which includes default time zone
/// formatting according to the calendar.
///
/// [`TimeZoneFormatter`] uses data from the [data provider] and the selected locale
/// to format time zones into that locale.
///
/// The various time-zone configs specified in UTS-35 require different sets of data for
/// formatting. As such,[`TimeZoneFormatter`] will pull in only the resources needed to format the
/// config that it is given upon construction.
///
/// For that reason, one should think of the process of formatting a time zone in two steps:
/// first, a computationally heavy construction of [`TimeZoneFormatter`], and then fast formatting
/// of the time-zone data using the instance.
///
/// [`CustomTimeZone`](icu_timezone::CustomTimeZone) can be used as formatting input.
///
/// # Examples
///
/// Here, we configure the [`TimeZoneFormatter`] to first look for time zone formatting symbol
/// data for `generic_non_location_short`, and if it does not exist, to subsequently check
/// for `generic_non_location_long` data.
///
/// ```
/// use icu::calendar::DateTime;
/// use icu::timezone::{CustomTimeZone, MetazoneCalculator, TimeZoneIdMapper};
/// use icu::datetime::{DateTimeError, time_zone::TimeZoneFormatter};
/// use icu::locid::locale;
/// use tinystr::tinystr;
/// use writeable::assert_writeable_eq;
///
/// // Set up the time zone. Note: the inputs here are
/// // 1. The GMT offset
/// // 2. The IANA time zone ID
/// // 3. A datetime (for metazone resolution)
/// // 4. Note: we do not need the zone variant because of `load_generic_*()`
///
/// // Set up the Metazone calculator, time zone ID mapper,
/// // and the DateTime to use in calculation
/// let mzc = MetazoneCalculator::new();
/// let mapper = TimeZoneIdMapper::new();
/// let datetime = DateTime::try_new_iso_datetime(2022, 8, 29, 0, 0, 0)
/// .unwrap();
///
/// // Set up the formatter
/// let mut tzf = TimeZoneFormatter::try_new(
/// &locale!("en").into(),
/// Default::default(),
/// )
/// .unwrap();
/// tzf.include_generic_non_location_short()?
/// .include_generic_non_location_long()?;
///
/// // "uschi" - has metazone symbol data for generic_non_location_short
/// let mut time_zone = "-0600".parse::<CustomTimeZone>().unwrap();
/// time_zone.time_zone_id = mapper.as_borrowed().iana_to_bcp47("America/Chicago");
/// time_zone.maybe_calculate_metazone(&mzc, &datetime);
/// assert_writeable_eq!(
/// tzf.format(&time_zone),
/// "CT"
/// );
///
/// // "ushnl" - has time zone override symbol data for generic_non_location_short
/// let mut time_zone = "-1000".parse::<CustomTimeZone>().unwrap();
/// time_zone.time_zone_id = Some(tinystr!(8, "ushnl").into());
/// time_zone.maybe_calculate_metazone(&mzc, &datetime);
/// assert_writeable_eq!(
/// tzf.format(&time_zone),
/// "HST"
/// );
///
/// // "frpar" - does not have symbol data for generic_non_location_short, so falls
/// // back to generic_non_location_long
/// let mut time_zone = "+0100".parse::<CustomTimeZone>().unwrap();
/// time_zone.time_zone_id = Some(tinystr!(8, "frpar").into());
/// time_zone.maybe_calculate_metazone(&mzc, &datetime);
/// assert_writeable_eq!(
/// tzf.format(&time_zone),
/// "Central European Time"
/// );
///
/// // GMT with offset - used when metazone is not available
/// let mut time_zone = "+0530".parse::<CustomTimeZone>().unwrap();
/// assert_writeable_eq!(
/// tzf.format(&time_zone),
/// "GMT+05:30"
/// );
///
/// # Ok::<(), DateTimeError>(())
/// ```
///
/// [data provider]: icu_provider
#[derive(Debug)]
pub struct TimeZoneFormatter {
pub(super) locale: DataLocale,
pub(super) data_payloads: TimeZoneDataPayloads,
pub(super) format_units: SmallVec<[TimeZoneFormatterUnit; 3]>,
pub(super) fallback_unit: FallbackTimeZoneFormatterUnit,
}
/// A container contains all data payloads for CustomTimeZone.
#[derive(Debug)]
pub(super) struct TimeZoneDataPayloads {
/// The data that contains meta information about how to display content.
pub(super) zone_formats: DataPayload<provider::time_zones::TimeZoneFormatsV1Marker>,
/// The exemplar cities for time zones.
pub(super) exemplar_cities: Option<DataPayload<provider::time_zones::ExemplarCitiesV1Marker>>,
/// The generic long metazone names, e.g. Pacific Time
pub(super) mz_generic_long:
Option<DataPayload<provider::time_zones::MetazoneGenericNamesLongV1Marker>>,
/// The generic short metazone names, e.g. PT
pub(super) mz_generic_short:
Option<DataPayload<provider::time_zones::MetazoneGenericNamesShortV1Marker>>,
/// The specific long metazone names, e.g. Pacific Daylight Time
pub(super) mz_specific_long:
Option<DataPayload<provider::time_zones::MetazoneSpecificNamesLongV1Marker>>,
/// The specific short metazone names, e.g. Pacific Daylight Time
pub(super) mz_specific_short:
Option<DataPayload<provider::time_zones::MetazoneSpecificNamesShortV1Marker>>,
}
impl TimeZoneFormatter {
/// Constructor that selectively loads data based on what is required to
/// format the given pattern into the given locale.
pub(super) fn try_new_for_pattern<ZP>(
zone_provider: &ZP,
locale: &DataLocale,
patterns: DataPayload<PatternPluralsFromPatternsV1Marker>,
options: &TimeZoneFormatterOptions,
) -> Result<Self, DateTimeError>
where
ZP: DataProvider<provider::time_zones::TimeZoneFormatsV1Marker>
+ DataProvider<provider::time_zones::ExemplarCitiesV1Marker>
+ DataProvider<provider::time_zones::MetazoneGenericNamesLongV1Marker>
+ DataProvider<provider::time_zones::MetazoneGenericNamesShortV1Marker>
+ DataProvider<provider::time_zones::MetazoneSpecificNamesLongV1Marker>
+ DataProvider<provider::time_zones::MetazoneSpecificNamesShortV1Marker>
+ ?Sized,
{
let format_units = SmallVec::<[TimeZoneFormatterUnit; 3]>::new();
let data_payloads = TimeZoneDataPayloads {
zone_formats: zone_provider
.load(DataRequest {
locale,
metadata: Default::default(),
})?
.take_payload()?,
exemplar_cities: None,
mz_generic_long: None,
mz_generic_short: None,
mz_specific_long: None,
mz_specific_short: None,
};
let zone_symbols = patterns
.get()
.0
.patterns_iter()
.flat_map(|pattern| pattern.items.iter())
.filter_map(|item| match item {
PatternItem::Field(field) => Some(field),
_ => None,
})
.filter_map(|field| match field.symbol {
FieldSymbol::TimeZone(zone) => Some((field.length.idx(), zone)),
_ => None,
});
let mut tz_format: TimeZoneFormatter = Self {
data_payloads,
// TODO(#2237): Determine whether we need to save the locale in the formatter
locale: locale.clone(),
format_units,
fallback_unit: options.fallback_format.into(),
};
let mut prev_length = None;
let mut prev_symbol = None;
for (length, symbol) in zone_symbols {
if prev_length.is_none() && prev_symbol.is_none() {
prev_length = Some(length);
prev_symbol = Some(symbol);
} else if prev_length != Some(length) && prev_symbol != Some(symbol) {
// We don't support the pattern that has multiple different timezone fields of different types.
return Err(DateTimeError::Pattern(PatternError::UnsupportedPluralPivot));
}
match symbol {
TimeZone::LowerZ => match length {
1..=3 => {
tz_format.load_specific_non_location_short(zone_provider)?;
}
4 => {
tz_format.load_specific_non_location_long(zone_provider)?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
TimeZone::LowerV => match length {
1 => {
tz_format.load_generic_non_location_short(zone_provider)?;
}
4 => {
tz_format.load_generic_non_location_long(zone_provider)?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
TimeZone::UpperV => match length {
1 => (), // BCP-47 identifier, no CLDR-data necessary.
2 => (), // IANA time-zone ID, no CLDR data necessary.
3 => {
tz_format.load_exemplar_city_format(zone_provider)?;
}
4 => {
tz_format.load_generic_location_format(zone_provider)?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
TimeZone::UpperZ => match length {
1..=3 => {
tz_format.include_iso_8601_format(
IsoFormat::Basic,
IsoMinutes::Required,
IsoSeconds::Optional,
)?;
}
4 => {
tz_format.include_localized_gmt_format()?;
}
5 => {
tz_format.include_iso_8601_format(
IsoFormat::UtcExtended,
IsoMinutes::Required,
IsoSeconds::Optional,
)?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
TimeZone::LowerX => match length {
1 => {
tz_format.include_iso_8601_format(
IsoFormat::UtcBasic,
IsoMinutes::Optional,
IsoSeconds::Never,
)?;
}
2 => {
tz_format.include_iso_8601_format(
IsoFormat::UtcBasic,
IsoMinutes::Required,
IsoSeconds::Never,
)?;
}
3 => {
tz_format.include_iso_8601_format(
IsoFormat::UtcExtended,
IsoMinutes::Required,
IsoSeconds::Never,
)?;
}
4 => {
tz_format.include_iso_8601_format(
IsoFormat::UtcBasic,
IsoMinutes::Required,
IsoSeconds::Optional,
)?;
}
5 => {
tz_format.include_iso_8601_format(
IsoFormat::UtcExtended,
IsoMinutes::Required,
IsoSeconds::Optional,
)?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
TimeZone::UpperX => match length {
1 => {
tz_format.include_iso_8601_format(
IsoFormat::Basic,
IsoMinutes::Optional,
IsoSeconds::Never,
)?;
}
2 => {
tz_format.include_iso_8601_format(
IsoFormat::Basic,
IsoMinutes::Required,
IsoSeconds::Never,
)?;
}
3 => {
tz_format.include_iso_8601_format(
IsoFormat::Extended,
IsoMinutes::Required,
IsoSeconds::Never,
)?;
}
4 => {
tz_format.include_iso_8601_format(
IsoFormat::Basic,
IsoMinutes::Required,
IsoSeconds::Optional,
)?;
}
5 => {
tz_format.include_iso_8601_format(
IsoFormat::Extended,
IsoMinutes::Required,
IsoSeconds::Optional,
)?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
TimeZone::UpperO => match length {
1..=4 => {
tz_format.include_localized_gmt_format()?;
}
_ => {
return Err(DateTimeError::Pattern(PatternError::FieldLengthInvalid(
FieldSymbol::TimeZone(symbol),
)))
}
},
}
}
Ok(tz_format)
}
icu_provider::gen_any_buffer_data_constructors!(
locale: include,
options: TimeZoneFormatterOptions,
error: DateTimeError,
/// Creates a new [`TimeZoneFormatter`] with a GMT or ISO format using compiled data.
///
/// To enable other time zone styles, use one of the `with` (compiled data) or `load` (runtime
/// data provider) methods.
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// # Examples
///
/// Default format is Localized GMT:
///
/// ```
/// use icu::datetime::time_zone::{
/// TimeZoneFormatter, TimeZoneFormatterOptions,
/// };
/// use icu::locid::locale;
/// use icu::timezone::CustomTimeZone;
/// use writeable::assert_writeable_eq;
///
/// let tzf = TimeZoneFormatter::try_new(
/// &locale!("es").into(),
/// TimeZoneFormatterOptions::default(),
/// )
/// .unwrap();
///
/// let time_zone = "-0700".parse::<CustomTimeZone>().unwrap();
///
/// assert_writeable_eq!(tzf.format(&time_zone), "GMT-07:00");
/// ```
);
#[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
pub fn try_new_unstable<P>(
provider: &P,
locale: &DataLocale,
options: TimeZoneFormatterOptions,
) -> Result<Self, DateTimeError>
where
P: DataProvider<provider::time_zones::TimeZoneFormatsV1Marker> + ?Sized,
{
let format_units = SmallVec::<[TimeZoneFormatterUnit; 3]>::new();
let data_payloads = TimeZoneDataPayloads {
zone_formats: provider
.load(DataRequest {
locale,
metadata: Default::default(),
})?
.take_payload()?,
exemplar_cities: None,
mz_generic_long: None,
mz_generic_short: None,
mz_specific_long: None,
mz_specific_short: None,
};
Ok(Self {
data_payloads,
locale: locale.clone(),
format_units,
fallback_unit: options.fallback_format.into(),
})
}
/// Include generic-non-location-long format for timezone from compiled data. For example, "Pacific Time".
#[cfg(feature = "compiled_data")]
pub fn include_generic_non_location_long(
&mut self,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.load_generic_non_location_long(&crate::provider::Baked)
}
/// Include generic-non-location-short format for timezone from compiled data. For example, "PT".
#[cfg(feature = "compiled_data")]
pub fn include_generic_non_location_short(
&mut self,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.load_generic_non_location_short(&crate::provider::Baked)
}
/// Include specific-non-location-long format for timezone from compiled data. For example, "Pacific Standard Time".
#[cfg(feature = "compiled_data")]
pub fn include_specific_non_location_long(
&mut self,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.load_specific_non_location_long(&crate::provider::Baked)
}
/// Include specific-non-location-short format for timezone from compiled data. For example, "PDT".
#[cfg(feature = "compiled_data")]
pub fn include_specific_non_location_short(
&mut self,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.load_specific_non_location_short(&crate::provider::Baked)
}
/// Include generic-location format for timezone from compiled data. For example, "Los Angeles Time".
#[cfg(feature = "compiled_data")]
pub fn include_generic_location_format(
&mut self,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.load_generic_location_format(&crate::provider::Baked)
}
/// Include localized-GMT format for timezone. For example, "GMT-07:00".
pub fn include_localized_gmt_format(
&mut self,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.format_units.push(TimeZoneFormatterUnit::WithFallback(
FallbackTimeZoneFormatterUnit::LocalizedGmt(LocalizedGmtFormat {}),
));
Ok(self)
}
/// Include ISO-8601 format for timezone. For example, "-07:00".
pub fn include_iso_8601_format(
&mut self,
format: IsoFormat,
minutes: IsoMinutes,
seconds: IsoSeconds,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.format_units.push(TimeZoneFormatterUnit::WithFallback(
FallbackTimeZoneFormatterUnit::Iso8601(Iso8601Format {
format,
minutes,
seconds,
}),
));
Ok(self)
}
/// Load generic-non-location-long format for timezone. For example, "Pacific Time".
pub fn load_generic_non_location_long<ZP>(
&mut self,
zone_provider: &ZP,
) -> Result<&mut TimeZoneFormatter, DateTimeError>
where
ZP: DataProvider<provider::time_zones::MetazoneGenericNamesLongV1Marker> + ?Sized,
{
if self.data_payloads.mz_generic_long.is_none() {
load(
&self.locale,
&mut self.data_payloads.mz_generic_long,
zone_provider,
)?;
}
self.format_units
.push(TimeZoneFormatterUnit::GenericNonLocationLong(
GenericNonLocationLongFormat {},
));
Ok(self)
}
/// Load generic-non-location-short format for timezone. For example, "PT".
pub fn load_generic_non_location_short<ZP>(
&mut self,
zone_provider: &ZP,
) -> Result<&mut TimeZoneFormatter, DateTimeError>
where
ZP: DataProvider<provider::time_zones::MetazoneGenericNamesShortV1Marker> + ?Sized,
{
if self.data_payloads.mz_generic_short.is_none() {
load(
&self.locale,
&mut self.data_payloads.mz_generic_short,
zone_provider,
)?;
}
self.format_units
.push(TimeZoneFormatterUnit::GenericNonLocationShort(
GenericNonLocationShortFormat {},
));
Ok(self)
}
/// Load specific-non-location-long format for timezone. For example, "Pacific Standard Time".
pub fn load_specific_non_location_long<ZP>(
&mut self,
zone_provider: &ZP,
) -> Result<&mut TimeZoneFormatter, DateTimeError>
where
ZP: DataProvider<provider::time_zones::MetazoneSpecificNamesLongV1Marker> + ?Sized,
{
if self.data_payloads.mz_specific_long.is_none() {
load(
&self.locale,
&mut self.data_payloads.mz_specific_long,
zone_provider,
)?;
}
self.format_units
.push(TimeZoneFormatterUnit::SpecificNonLocationLong(
SpecificNonLocationLongFormat {},
));
Ok(self)
}
/// Load specific-non-location-short format for timezone. For example, "PDT".
pub fn load_specific_non_location_short<ZP>(
&mut self,
zone_provider: &ZP,
) -> Result<&mut TimeZoneFormatter, DateTimeError>
where
ZP: DataProvider<provider::time_zones::MetazoneSpecificNamesShortV1Marker> + ?Sized,
{
if self.data_payloads.mz_specific_short.is_none() {
load(
&self.locale,
&mut self.data_payloads.mz_specific_short,
zone_provider,
)?;
}
self.format_units
.push(TimeZoneFormatterUnit::SpecificNonLocationShort(
SpecificNonLocationShortFormat {},
));
Ok(self)
}
/// Load generic-location format for timezone. For example, "Los Angeles Time".
pub fn load_generic_location_format<ZP>(
&mut self,
zone_provider: &ZP,
) -> Result<&mut TimeZoneFormatter, DateTimeError>
where
ZP: DataProvider<provider::time_zones::ExemplarCitiesV1Marker> + ?Sized,
{
if self.data_payloads.exemplar_cities.is_none() {
load(
&self.locale,
&mut self.data_payloads.exemplar_cities,
zone_provider,
)?;
}
self.format_units
.push(TimeZoneFormatterUnit::GenericLocation(
GenericLocationFormat {},
));
Ok(self)
}
/// Load exemplar-city format for timezone. For example, "Los Angeles".
fn load_exemplar_city_format<ZP>(
&mut self,
zone_provider: &ZP,
) -> Result<&mut TimeZoneFormatter, DateTimeError>
where
ZP: DataProvider<provider::time_zones::ExemplarCitiesV1Marker> + ?Sized,
{
if self.data_payloads.exemplar_cities.is_none() {
load(
&self.locale,
&mut self.data_payloads.exemplar_cities,
zone_provider,
)?;
}
self.format_units
.push(TimeZoneFormatterUnit::ExemplarCity(ExemplarCityFormat {}));
Ok(self)
}
/// Alias to [`TimeZoneFormatter::include_localized_gmt_format`].
#[deprecated(since = "1.3.0", note = "renamed to `include_localized_gmt_format`")]
pub fn load_localized_gmt_format(&mut self) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.include_localized_gmt_format()
}
/// Alias to [`TimeZoneFormatter::include_iso_8601_format`].
#[deprecated(since = "1.3.0", note = "renamed to `include_iso_8601_format`")]
pub fn load_iso_8601_format(
&mut self,
format: IsoFormat,
minutes: IsoMinutes,
seconds: IsoSeconds,
) -> Result<&mut TimeZoneFormatter, DateTimeError> {
self.include_iso_8601_format(format, minutes, seconds)
}
/// Takes a [`TimeZoneInput`] implementer and returns an instance of a [`FormattedTimeZone`]
/// that contains all information necessary to display a formatted time zone and operate on it.
///
/// # Examples
///
/// ```
/// use icu::datetime::time_zone::{
/// TimeZoneFormatter, TimeZoneFormatterOptions,
/// };
/// use icu::locid::locale;
/// use icu::timezone::CustomTimeZone;
/// use writeable::assert_writeable_eq;
///
/// let tzf = TimeZoneFormatter::try_new(
/// &locale!("en").into(),
/// TimeZoneFormatterOptions::default(),
/// )
/// .expect("Failed to create TimeZoneFormatter");
///
/// let time_zone = CustomTimeZone::utc();
///
/// assert_writeable_eq!(tzf.format(&time_zone), "GMT");
/// ```
pub fn format<'l, T>(&'l self, value: &'l T) -> FormattedTimeZone<'l, T>
where
T: TimeZoneInput,
{
FormattedTimeZone {
time_zone_format: self,
time_zone: value,
}
}
/// Takes a [`TimeZoneInput`] implementer and returns a string with the formatted value.
pub fn format_to_string(&self, value: &impl TimeZoneInput) -> String {
self.format(value).write_to_string().into_owned()
}
}
/// Determines which ISO-8601 format should be used to format a [`GmtOffset`].
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(clippy::exhaustive_enums)] // this type is stable
pub enum IsoFormat {
/// ISO-8601 Basic Format.
/// Formats zero-offset numerically.
/// e.g. +0500, +0000
Basic,
/// ISO-8601 Extended Format.
/// Formats zero-offset numerically.
/// e.g. +05:00, +00:00
Extended,
/// ISO-8601 Basic Format.
/// Formats zero-offset with the ISO-8601 UTC indicator: "Z"
/// e.g. +0500, Z
UtcBasic,
/// ISO-8601 Extended Format.
/// Formats zero-offset with the ISO-8601 UTC indicator: "Z"
/// e.g. +05:00, Z
UtcExtended,
}
/// Whether the minutes field should be optional or required in ISO-8601 format.
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(clippy::exhaustive_enums)] // this type is stable
pub enum IsoMinutes {
/// Minutes are always displayed.
Required,
/// Minutes are displayed only if they are non-zero.
Optional,
}
/// Whether the seconds field should be optional or excluded in ISO-8601 format.
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(clippy::exhaustive_enums)] // this type is stable
pub enum IsoSeconds {
/// Seconds are displayed only if they are non-zero.
Optional,
/// Seconds are not displayed.
Never,
}
/// Whether a field should be zero-padded in ISO-8601 format.
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(clippy::exhaustive_enums)] // this type is stable
pub(crate) enum ZeroPadding {
/// Add zero-padding.
On,
/// Do not add zero-padding.
Off,
}
/// An enum for time zone fallback formats.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
#[derive(Default)]
pub enum FallbackFormat {
/// The ISO 8601 format for time zone format fallback.
Iso8601(IsoFormat, IsoMinutes, IsoSeconds),
/// The localized GMT format for time zone format fallback.
///
/// See [UTS 35 on Dates](https://unicode.org/reports/tr35/tr35-dates.html#71-time-zone-format-terminology) for more information.
#[default]
LocalizedGmt,
}
/// A bag of options to define how time zone will be formatted.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TimeZoneFormatterOptions {
/// The time zone format fallback option.
///
/// See [UTS 35 on Dates](https://unicode.org/reports/tr35/tr35-dates.html#71-time-zone-format-terminology) for more information.
pub fallback_format: FallbackFormat,
}
impl From<FallbackFormat> for TimeZoneFormatterOptions {
fn from(fallback_format: FallbackFormat) -> Self {
Self { fallback_format }
}
}
// Pacific Time
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct GenericNonLocationLongFormat {}
// PT
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct GenericNonLocationShortFormat {}
// Pacific Standard Time
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct SpecificNonLocationLongFormat {}
// PDT
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct SpecificNonLocationShortFormat {}
// Los Angeles Time
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct GenericLocationFormat {}
// GMT-07:00
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct LocalizedGmtFormat {}
// -07:00
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Iso8601Format {
format: IsoFormat,
minutes: IsoMinutes,
seconds: IsoSeconds,
}
// It is only used for pattern in special case and not public to users.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct ExemplarCityFormat {}
// An enum for time zone format unit.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum TimeZoneFormatterUnit {
GenericNonLocationLong(GenericNonLocationLongFormat),
GenericNonLocationShort(GenericNonLocationShortFormat),
SpecificNonLocationLong(SpecificNonLocationLongFormat),
SpecificNonLocationShort(SpecificNonLocationShortFormat),
GenericLocation(GenericLocationFormat),
ExemplarCity(ExemplarCityFormat),
WithFallback(FallbackTimeZoneFormatterUnit),
}
impl Default for TimeZoneFormatterUnit {
fn default() -> Self {
TimeZoneFormatterUnit::WithFallback(FallbackTimeZoneFormatterUnit::LocalizedGmt(
LocalizedGmtFormat {},
))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum FallbackTimeZoneFormatterUnit {
LocalizedGmt(LocalizedGmtFormat),
Iso8601(Iso8601Format),
}
/// Load a fallback format for timezone. The fallback format will be executed if there are no
/// matching format results.
impl From<FallbackFormat> for FallbackTimeZoneFormatterUnit {
fn from(value: FallbackFormat) -> Self {
match value {
FallbackFormat::LocalizedGmt => Self::LocalizedGmt(LocalizedGmtFormat {}),
FallbackFormat::Iso8601(format, minutes, seconds) => Self::Iso8601(Iso8601Format {
format,
minutes,
seconds,
}),
}
}
}
pub(super) trait FormatTimeZone {
/// Tries to write the timezone to the sink. If a DateTimeError is returned, the sink
/// has not been touched, so another format can be attempted.
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError>;
}
pub(super) trait FormatTimeZoneWithFallback {
fn format_gmt_offset<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
gmt_offset: GmtOffset,
_data_payloads: &TimeZoneDataPayloads,
) -> fmt::Result;
/// Formats the GMT offset, or falls back to a fallback string. This does
/// lossy writing, so even in the Ok(Err(_)) case, something has been written.
fn format_with_last_resort_fallback<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<Result<(), DateTimeError>, fmt::Error> {
Ok(if let Some(gmt_offset) = time_zone.gmt_offset() {
self.format_gmt_offset(sink, gmt_offset, data_payloads)?;
Ok(())
} else {
sink.with_part(Part::ERROR, |sink| {
sink.write_str(&data_payloads.zone_formats.get().gmt_offset_fallback)
})?;
Err(DateTimeError::MissingInputField(Some("gmt_offset")))
})
}
}
impl FormatTimeZone for TimeZoneFormatterUnit {
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
match self {
Self::GenericNonLocationLong(unit) => unit.format(sink, time_zone, data_payloads),
Self::GenericNonLocationShort(unit) => unit.format(sink, time_zone, data_payloads),
Self::SpecificNonLocationLong(unit) => unit.format(sink, time_zone, data_payloads),
Self::SpecificNonLocationShort(unit) => unit.format(sink, time_zone, data_payloads),
Self::GenericLocation(unit) => unit.format(sink, time_zone, data_payloads),
Self::WithFallback(unit) => unit.format(sink, time_zone, data_payloads),
Self::ExemplarCity(unit) => unit.format(sink, time_zone, data_payloads),
}
}
}
impl FormatTimeZone for FallbackTimeZoneFormatterUnit {
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
match self {
Self::LocalizedGmt(unit) => unit.format(sink, time_zone, data_payloads),
Self::Iso8601(unit) => unit.format(sink, time_zone, data_payloads),
}
}
}
impl FormatTimeZoneWithFallback for FallbackTimeZoneFormatterUnit {
fn format_gmt_offset<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
gmt_offset: GmtOffset,
data_payloads: &TimeZoneDataPayloads,
) -> fmt::Result {
match self {
Self::LocalizedGmt(unit) => unit.format_gmt_offset(sink, gmt_offset, data_payloads),
Self::Iso8601(unit) => unit.format_gmt_offset(sink, gmt_offset, data_payloads),
}
}
}
impl FormatTimeZone for GenericNonLocationLongFormat {
/// Writes the time zone in long generic non-location format as defined by the UTS-35 spec.
/// e.g. Pacific Time
/// <https://unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Format_Terminology>
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
let formatted_time_zone: Option<&str> = data_payloads
.mz_generic_long
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone
.time_zone_id()
.and_then(|tz| metazones.overrides.get(&tz))
})
.or_else(|| {
data_payloads
.mz_generic_long
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone
.metazone_id()
.and_then(|mz| metazones.defaults.get(&mz))
})
});
match formatted_time_zone {
Some(ftz) => Ok(sink.write_str(ftz)),
None => Err(DateTimeError::UnsupportedOptions),
}
}
}
impl FormatTimeZone for GenericNonLocationShortFormat {
/// Writes the time zone in short generic non-location format as defined by the UTS-35 spec.
/// e.g. PT
/// <https://unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Format_Terminology>
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
let formatted_time_zone: Option<&str> = data_payloads
.mz_generic_short
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone
.time_zone_id()
.and_then(|tz| metazones.overrides.get(&tz))
})
.or_else(|| {
data_payloads
.mz_generic_short
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone
.metazone_id()
.and_then(|mz| metazones.defaults.get(&mz))
})
});
match formatted_time_zone {
Some(ftz) => Ok(sink.write_str(ftz)),
None => Err(DateTimeError::UnsupportedOptions),
}
}
}
impl FormatTimeZone for SpecificNonLocationShortFormat {
/// Writes the time zone in short specific non-location format as defined by the UTS-35 spec.
/// e.g. PDT
/// <https://unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Format_Terminology>
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
let formatted_time_zone: Option<&str> = data_payloads
.mz_specific_short
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone.time_zone_id().and_then(|tz| {
time_zone
.zone_variant()
.and_then(|variant| metazones.overrides.get_2d(&tz, &variant))
})
})
.or_else(|| {
data_payloads
.mz_specific_short
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone.metazone_id().and_then(|mz| {
time_zone
.zone_variant()
.and_then(|variant| metazones.defaults.get_2d(&mz, &variant))
})
})
});
match formatted_time_zone {
Some(ftz) => Ok(sink.write_str(ftz)),
None => Err(DateTimeError::UnsupportedOptions),
}
}
}
impl FormatTimeZone for SpecificNonLocationLongFormat {
/// Writes the time zone in long specific non-location format as defined by the UTS-35 spec.
/// e.g. Pacific Daylight Time
/// <https://unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Format_Terminology>
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
let formatted_time_zone: Option<&str> = data_payloads
.mz_specific_long
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone.time_zone_id().and_then(|tz| {
time_zone
.zone_variant()
.and_then(|variant| metazones.overrides.get_2d(&tz, &variant))
})
})
.or_else(|| {
data_payloads
.mz_specific_long
.as_ref()
.map(|p| p.get())
.and_then(|metazones| {
time_zone.metazone_id().and_then(|mz| {
time_zone
.zone_variant()
.and_then(|variant| metazones.defaults.get_2d(&mz, &variant))
})
})
});
match formatted_time_zone {
Some(ftz) => Ok(sink.write_str(ftz)),
None => Err(DateTimeError::UnsupportedOptions),
}
}
}
impl FormatTimeZoneWithFallback for LocalizedGmtFormat {
/// Writes the time zone in localized GMT format according to the CLDR localized hour format.
/// This goes explicitly against the UTS-35 spec, which specifies long or short localized
/// GMT formats regardless of locale.
///
/// You can see more information about our decision to resolve this conflict here:
/// <https://docs.google.com/document/d/16GAqaDRS6hzL8jNYjus5MglSevGBflISM-BrIS7bd4A/edit?usp=sharing>
fn format_gmt_offset<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
gmt_offset: GmtOffset,
data_payloads: &TimeZoneDataPayloads,
) -> fmt::Result {
if gmt_offset.is_zero() {
sink.write_str(&data_payloads.zone_formats.get().gmt_zero_format.clone())
} else {
// TODO(blocked on #277) Use formatter utility instead of replacing "{0}".
let mut scratch = String::new();
sink.write_str(
&data_payloads
.zone_formats
.get()
.gmt_format
.replace(
"{0}",
if gmt_offset.is_positive() {
&data_payloads.zone_formats.get().hour_format.0
} else {
&data_payloads.zone_formats.get().hour_format.1
},
)
// support all combos of "(HH|H):mm" by replacing longest patterns first.
.replace("HH", {
scratch.clear();
let _infallible = format_offset_hours(
&mut CoreWriteAsPartsWrite(&mut scratch),
gmt_offset,
ZeroPadding::On,
);
&scratch
})
.replace("mm", {
scratch.clear();
let _infallible = format_offset_minutes(
&mut CoreWriteAsPartsWrite(&mut scratch),
gmt_offset,
);
&scratch
})
.replace('H', {
scratch.clear();
let _infallible = format_offset_hours(
&mut CoreWriteAsPartsWrite(&mut scratch),
gmt_offset,
ZeroPadding::Off,
);
&scratch
}),
)
}
}
}
impl FormatTimeZone for LocalizedGmtFormat {
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
Ok(self.format_gmt_offset(
sink,
time_zone
.gmt_offset()
.ok_or(DateTimeError::MissingInputField(Some("gmt_offset")))?,
data_payloads,
))
}
}
impl FormatTimeZone for GenericLocationFormat {
/// Writes the time zone in generic location format as defined by the UTS-35 spec.
/// e.g. France Time
/// <https://unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Format_Terminology>
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
// TODO(blocked on #277) Use formatter utility instead of replacing "{0}".
let formatted_time_zone: Option<alloc::string::String> = data_payloads
.exemplar_cities
.as_ref()
.map(|p| p.get())
.and_then(|cities| time_zone.time_zone_id().and_then(|id| cities.0.get(&id)))
.map(|location| {
data_payloads
.zone_formats
.get()
.region_format
.replace("{0}", location)
});
match formatted_time_zone {
Some(ftz) => Ok(sink.write_str(&ftz)),
None => Err(DateTimeError::UnsupportedOptions),
}
}
}
impl FormatTimeZoneWithFallback for Iso8601Format {
/// Writes a [`GmtOffset`](crate::input::GmtOffset) in ISO-8601 format according to the
/// given formatting options.
///
/// [`IsoFormat`] determines whether the format should be Basic or Extended,
/// and whether a zero-offset should be formatted numerically or with
/// The UTC indicator: "Z"
/// - Basic e.g. +0800
/// - Extended e.g. +08:00
///
/// [`IsoMinutes`] can be required or optional.
/// [`IsoSeconds`] can be optional or never.
fn format_gmt_offset<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
gmt_offset: GmtOffset,
_data_payloads: &TimeZoneDataPayloads,
) -> fmt::Result {
if gmt_offset.is_zero()
&& matches!(self.format, IsoFormat::UtcBasic | IsoFormat::UtcExtended)
{
sink.write_char('Z')?;
}
let extended_format = matches!(self.format, IsoFormat::Extended | IsoFormat::UtcExtended);
sink.write_char(if gmt_offset.is_positive() { '+' } else { '-' })?;
format_offset_hours(sink, gmt_offset, ZeroPadding::On)?;
if self.minutes == IsoMinutes::Required
|| (self.minutes == IsoMinutes::Optional && gmt_offset.has_minutes())
{
if extended_format {
sink.write_char(':')?;
}
format_offset_minutes(sink, gmt_offset)?;
}
if self.seconds == IsoSeconds::Optional && gmt_offset.has_seconds() {
if extended_format {
sink.write_char(':')?;
}
format_offset_seconds(sink, gmt_offset)?;
}
Ok(())
}
}
impl FormatTimeZone for Iso8601Format {
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
Ok(self.format_gmt_offset(
sink,
time_zone
.gmt_offset()
.ok_or(DateTimeError::MissingInputField(Some("gmt_offset")))?,
data_payloads,
))
}
}
impl FormatTimeZone for ExemplarCityFormat {
fn format<W: writeable::PartsWrite + ?Sized>(
&self,
sink: &mut W,
time_zone: &impl TimeZoneInput,
data_payloads: &TimeZoneDataPayloads,
) -> Result<fmt::Result, DateTimeError> {
// Writes the exemplar city associated with this time zone.
let formatted_exemplar_city = data_payloads
.exemplar_cities
.as_ref()
.map(|p| p.get())
.and_then(|cities| time_zone.time_zone_id().and_then(|id| cities.0.get(&id)));
match formatted_exemplar_city {
Some(ftz) => Ok(sink.write_str(ftz)),
None => {
// Writes the unknown city "Etc/Unknown" for the current locale.
//
// If there is no localized form of "Etc/Unknown" for the current locale,
// returns the "Etc/Unknown" value of the `und` locale as a hard-coded string.
//
// This can be used as a fallback if [`exemplar_city()`](TimeZoneFormatter::exemplar_city())
// is unable to produce a localized form of the time zone's exemplar city in the current locale.
let formatted_unknown_city = data_payloads
.exemplar_cities
.as_ref()
.map(|p| p.get())
.and_then(|cities| cities.0.get(&TimeZoneBcp47Id(tinystr!(8, "unk"))))
.unwrap_or(&Cow::Borrowed("Unknown"));
Ok(sink.write_str(formatted_unknown_city))
}
}
}
}
/// Formats a time segment with optional zero-padding.
fn format_time_segment<W: writeable::PartsWrite + ?Sized>(
sink: &mut W,
n: u8,
padding: ZeroPadding,
) -> fmt::Result {
debug_assert!((0..60).contains(&n));
if padding == ZeroPadding::On && n < 10 {
sink.write_char('0')?;
}
n.write_to(sink)
}
fn format_offset_hours<W: writeable::PartsWrite + ?Sized>(
sink: &mut W,
gmt_offset: GmtOffset,
padding: ZeroPadding,
) -> fmt::Result {
format_time_segment(
sink,
(gmt_offset.offset_seconds() / 3600).unsigned_abs() as u8,
padding,
)
}
fn format_offset_minutes<W: writeable::PartsWrite + ?Sized>(
sink: &mut W,
gmt_offset: GmtOffset,
) -> fmt::Result {
format_time_segment(
sink,
(gmt_offset.offset_seconds() % 3600 / 60).unsigned_abs() as u8,
ZeroPadding::On,
)
}
fn format_offset_seconds<W: writeable::PartsWrite + ?Sized>(
sink: &mut W,
gmt_offset: GmtOffset,
) -> fmt::Result {
format_time_segment(
sink,
(gmt_offset.offset_seconds() % 3600 % 60).unsigned_abs() as u8,
ZeroPadding::On,
)
}