| 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 |
use super::time_zone::{FormatTimeZone, FormatTimeZoneError, Iso8601Format, TimeZoneFormatterUnit}; |
| 6 |
use crate::error::ErrorField; |
| 7 |
use crate::format::{DateTimeInputUnchecked, numeric_override}; |
| 8 |
use crate::provider::fields::{self, FieldLength, FieldSymbol, Second, Year}; |
| 9 |
use crate::provider::pattern::PatternItem; |
| 10 |
use crate::provider::pattern::runtime::PatternMetadata; |
| 11 |
use crate::unchecked::MissingInputFieldKind; |
| 12 |
use crate::{parts, pattern::*}; |
| 13 |
|
| 14 |
use core::fmt::{self, Write}; |
| 15 |
use fixed_decimal::Decimal; |
| 16 |
use icu_calendar::types::{DayOfWeekInMonth, RataDie, Weekday}; |
| 17 |
use icu_decimal::DecimalFormatter; |
| 18 |
use writeable::{Part, PartsWrite, Writeable}; |
| 19 |
|
| 20 |
/// Apply length to input number and write to result using `decimal_formatter`. |
| 21 |
fn try_write_number<W>( |
| 22 |
part: Part, |
| 23 |
w: &mut W, |
| 24 |
decimal_formatter: Option<&DecimalFormatter>, |
| 25 |
mut num: Decimal, |
| 26 |
length: FieldLength, |
| 27 |
) -> Result<Result<(), FormattedDateTimePatternError>, fmt::Error> |
| 28 |
where |
| 29 |
W: PartsWrite + ?Sized, |
| 30 |
{ |
| 31 |
num.pad_start(length.to_len() as i16); |
| 32 |
|
| 33 |
if let Some(fdf) = decimal_formatter { |
| 34 |
w.with_part(part, |w| fdf.format(&num).write_to_parts(w))?; |
| 35 |
Ok(Ok(())) |
| 36 |
} else { |
| 37 |
// Fallback behavior in the error case. |
| 38 |
w.with_part(part, |w| { |
| 39 |
w.with_part(Part::ERROR, |r| num.write_to_parts(r)) |
| 40 |
})?; |
| 41 |
Ok(Err( |
| 42 |
FormattedDateTimePatternError::DecimalFormatterNotLoaded, |
| 43 |
)) |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/// Apply length to input number and write to result using `decimal_formatter`. |
| 48 |
/// Don't annotate it with a part. |
| 49 |
fn try_write_number_without_part<W>( |
| 50 |
w: &mut W, |
| 51 |
decimal_formatter: Option<&DecimalFormatter>, |
| 52 |
mut num: Decimal, |
| 53 |
length: FieldLength, |
| 54 |
) -> Result<Result<(), FormattedDateTimePatternError>, fmt::Error> |
| 55 |
where |
| 56 |
W: PartsWrite + ?Sized, |
| 57 |
{ |
| 58 |
num.pad_start(length.to_len() as i16); |
| 59 |
|
| 60 |
if let Some(fdf) = decimal_formatter { |
| 61 |
fdf.format(&num).write_to(w)?; |
| 62 |
Ok(Ok(())) |
| 63 |
} else { |
| 64 |
// Fallback behavior in the error case. |
| 65 |
w.with_part(Part::ERROR, |r| num.write_to(r))?; |
| 66 |
Ok(Err( |
| 67 |
FormattedDateTimePatternError::DecimalFormatterNotLoaded, |
| 68 |
)) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
pub(crate) fn try_write_pattern_items<W>( |
| 73 |
pattern_metadata: PatternMetadata, |
| 74 |
pattern_items: impl Iterator<Item = PatternItem>, |
| 75 |
input: &DateTimeInputUnchecked, |
| 76 |
datetime_names: &RawDateTimeNamesBorrowed, |
| 77 |
decimal_formatter: Option<&DecimalFormatter>, |
| 78 |
w: &mut W, |
| 79 |
) -> Result<Result<(), FormattedDateTimePatternError>, fmt::Error> |
| 80 |
where |
| 81 |
W: PartsWrite + ?Sized, |
| 82 |
{ |
| 83 |
let mut r = Ok(()); |
| 84 |
for item in pattern_items { |
| 85 |
match item { |
| 86 |
PatternItem::Literal(ch) => w.write_char(ch)?, |
| 87 |
PatternItem::Field(field) => { |
| 88 |
r = r.and(try_write_field( |
| 89 |
field, |
| 90 |
pattern_metadata, |
| 91 |
input, |
| 92 |
datetime_names, |
| 93 |
decimal_formatter, |
| 94 |
w, |
| 95 |
)?); |
| 96 |
} |
| 97 |
} |
| 98 |
} |
| 99 |
Ok(r) |
| 100 |
} |
| 101 |
|
| 102 |
// This function assumes that the correct decision has been |
| 103 |
// made regarding availability of symbols in the caller. |
| 104 |
// |
| 105 |
// When modifying the list of fields using symbols, |
| 106 |
// update the matching query in `analyze_pattern` function. |
| 107 |
pub(crate) fn try_write_field<W>( |
| 108 |
field: fields::Field, |
| 109 |
pattern_metadata: PatternMetadata, |
| 110 |
input: &DateTimeInputUnchecked, |
| 111 |
datetime_names: &RawDateTimeNamesBorrowed, |
| 112 |
decimal_formatter: Option<&DecimalFormatter>, |
| 113 |
w: &mut W, |
| 114 |
) -> Result<Result<(), FormattedDateTimePatternError>, fmt::Error> |
| 115 |
where |
| 116 |
W: PartsWrite + ?Sized, |
| 117 |
{ |
| 118 |
macro_rules! input { |
| 119 |
// Get the input. If not found, write a replacement string but do NOT write a part. |
| 120 |
(_, $kind:ident, $name:ident = $input:expr) => { |
| 121 |
let Some($name) = $input else { |
| 122 |
write_value_missing(w, field)?; |
| 123 |
return Ok(Err(FormattedDateTimePatternError::MissingInputField( |
| 124 |
MissingInputFieldKind::$kind, |
| 125 |
))); |
| 126 |
}; |
| 127 |
}; |
| 128 |
// Get the input. If not found, write a replacement string and a part. |
| 129 |
($part:ident, $kind:ident, $name:ident = $input:expr) => { |
| 130 |
let Some($name) = $input else { |
| 131 |
w.with_part($part, |w| write_value_missing(w, field))?; |
| 132 |
return Ok(Err(FormattedDateTimePatternError::MissingInputField( |
| 133 |
MissingInputFieldKind::$kind, |
| 134 |
))); |
| 135 |
}; |
| 136 |
}; |
| 137 |
} |
| 138 |
|
| 139 |
Ok(match (field.symbol, field.length) { |
| 140 |
(FieldSymbol::Era, l) => { |
| 141 |
const PART: Part = parts::ERA; |
| 142 |
input!(PART, Year, year = input.year); |
| 143 |
input!(PART, YearEra, era_year = year.era()); |
| 144 |
let era_symbol = datetime_names |
| 145 |
.get_name_for_era(l, era_year) |
| 146 |
.map_err(|e| match e { |
| 147 |
GetNameForEraError::InvalidEraCode => { |
| 148 |
FormattedDateTimePatternError::InvalidEra(era_year.era) |
| 149 |
} |
| 150 |
GetNameForEraError::InvalidFieldLength => { |
| 151 |
FormattedDateTimePatternError::UnsupportedLength(ErrorField(field)) |
| 152 |
} |
| 153 |
GetNameForEraError::NotLoaded => { |
| 154 |
FormattedDateTimePatternError::NamesNotLoaded(ErrorField(field)) |
| 155 |
} |
| 156 |
}); |
| 157 |
match era_symbol { |
| 158 |
Err(e) => { |
| 159 |
w.with_part(PART, |w| { |
| 160 |
w.with_part(Part::ERROR, |w| w.write_str(&era_year.era)) |
| 161 |
})?; |
| 162 |
Err(e) |
| 163 |
} |
| 164 |
Ok(era) => Ok(w.with_part(PART, |w| w.write_str(era))?), |
| 165 |
} |
| 166 |
} |
| 167 |
(FieldSymbol::Year(Year::Calendar), l) => { |
| 168 |
const PART: Part = parts::YEAR; |
| 169 |
input!(PART, Year, year = input.year); |
| 170 |
|
| 171 |
let year_val = year.era_year_or_related_iso(); |
| 172 |
match l { |
| 173 |
// We only support overriding for positive numbers. |
| 174 |
// For negative numbers RBNF coverage is spotty and often not actually |
| 175 |
// what you want in years, so we fall back. |
| 176 |
FieldLength::NumericOverride(o) if year_val >= 0 => { |
| 177 |
numeric_override::format(PART, w, year_val as u32, o)? |
| 178 |
} |
| 179 |
_ => { |
| 180 |
let mut year = Decimal::from(year.era_year_or_related_iso()); |
| 181 |
if matches!(l, FieldLength::Two) { |
| 182 |
// 'yy' and 'YY' truncate |
| 183 |
year.set_max_position(2); |
| 184 |
} |
| 185 |
try_write_number(PART, w, decimal_formatter, year, l)? |
| 186 |
} |
| 187 |
} |
| 188 |
} |
| 189 |
(FieldSymbol::Year(Year::Cyclic), l) => { |
| 190 |
const PART: Part = parts::YEAR_NAME; |
| 191 |
input!(PART, Year, year = input.year); |
| 192 |
|
| 193 |
let Some(cyclic) = year.cyclic() else { |
| 194 |
w.with_part(PART, |w| { |
| 195 |
try_write_number( |
| 196 |
Part::ERROR, |
| 197 |
w, |
| 198 |
decimal_formatter, |
| 199 |
year.era_year_or_related_iso().into(), |
| 200 |
FieldLength::One, |
| 201 |
) |
| 202 |
.map(|_| ()) |
| 203 |
})?; |
| 204 |
return Ok(Err(FormattedDateTimePatternError::UnsupportedField( |
| 205 |
ErrorField(field), |
| 206 |
))); |
| 207 |
}; |
| 208 |
|
| 209 |
match datetime_names.get_name_for_cyclic(l, cyclic.year) { |
| 210 |
Ok(name) => Ok(w.with_part(PART, |w| w.write_str(name))?), |
| 211 |
Err(e) => { |
| 212 |
w.with_part(PART, |w| { |
| 213 |
try_write_number( |
| 214 |
Part::ERROR, |
| 215 |
w, |
| 216 |
decimal_formatter, |
| 217 |
cyclic.related_iso.into(), |
| 218 |
FieldLength::One, |
| 219 |
) |
| 220 |
.map(|_| ()) |
| 221 |
})?; |
| 222 |
return Ok(Err(match e { |
| 223 |
GetNameForCyclicYearError::InvalidYearNumber { max } => { |
| 224 |
FormattedDateTimePatternError::InvalidCyclicYear { |
| 225 |
value: cyclic.year, |
| 226 |
max, |
| 227 |
} |
| 228 |
} |
| 229 |
GetNameForCyclicYearError::InvalidFieldLength => { |
| 230 |
FormattedDateTimePatternError::UnsupportedLength(ErrorField(field)) |
| 231 |
} |
| 232 |
GetNameForCyclicYearError::NotLoaded => { |
| 233 |
FormattedDateTimePatternError::NamesNotLoaded(ErrorField(field)) |
| 234 |
} |
| 235 |
})); |
| 236 |
} |
| 237 |
} |
| 238 |
} |
| 239 |
(FieldSymbol::Year(Year::RelatedIso), l) => { |
| 240 |
const PART: Part = parts::RELATED_YEAR; |
| 241 |
input!(PART, Year, year = input.year); |
| 242 |
input!(PART, YearCyclic, cyclic = year.cyclic()); |
| 243 |
|
| 244 |
// Always in latin digits according to spec |
| 245 |
w.with_part(PART, |w| { |
| 246 |
let mut num = Decimal::from(cyclic.related_iso); |
| 247 |
num.pad_start(l.to_len() as i16); |
| 248 |
num.write_to(w) |
| 249 |
})?; |
| 250 |
Ok(()) |
| 251 |
} |
| 252 |
(FieldSymbol::Year(Year::Extended), l) => { |
| 253 |
const PART: Part = parts::EXTENDED_YEAR; |
| 254 |
input!(PART, Year, year = input.year); |
| 255 |
let extended = year.extended_year(); |
| 256 |
try_write_number(PART, w, decimal_formatter, extended.into(), l)? |
| 257 |
} |
| 258 |
(FieldSymbol::Month(_), FieldLength::NumericOverride(o)) => { |
| 259 |
const PART: Part = parts::MONTH; |
| 260 |
input!(PART, Month, month = input.month); |
| 261 |
numeric_override::format(PART, w, u32::from(month.number()), o)? |
| 262 |
} |
| 263 |
(FieldSymbol::Month(symbol), l) => { |
| 264 |
const PART: Part = parts::MONTH; |
| 265 |
input!(PART, Month, month = input.month); |
| 266 |
match datetime_names.get_name_for_month(symbol, l, month) { |
| 267 |
Ok(MonthPlaceholderValue::PlainString(symbol)) => { |
| 268 |
w.with_part(PART, |w| w.write_str(symbol))?; |
| 269 |
Ok(()) |
| 270 |
} |
| 271 |
Ok(MonthPlaceholderValue::Numeric) => { |
| 272 |
try_write_number(PART, w, decimal_formatter, month.number().into(), l)? |
| 273 |
} |
| 274 |
Ok(MonthPlaceholderValue::NumericPattern(substitution_pattern, offset)) => { |
| 275 |
if let Some(formatter) = decimal_formatter { |
| 276 |
let mut num = Decimal::from(month.number().saturating_add_signed(offset)); |
| 277 |
num.pad_start(l.to_len() as i16); |
| 278 |
w.with_part(PART, |w| { |
| 279 |
substitution_pattern |
| 280 |
.interpolate([formatter.format(&num)]) |
| 281 |
.write_to(w) |
| 282 |
})?; |
| 283 |
Ok(()) |
| 284 |
} else { |
| 285 |
w.with_part(PART, |w| { |
| 286 |
w.with_part(Part::ERROR, |w| { |
| 287 |
substitution_pattern |
| 288 |
.interpolate([{ |
| 289 |
let mut num = Decimal::from(month.number()); |
| 290 |
num.pad_start(l.to_len() as i16); |
| 291 |
num |
| 292 |
}]) |
| 293 |
.write_to(w) |
| 294 |
}) |
| 295 |
})?; |
| 296 |
Err(FormattedDateTimePatternError::DecimalFormatterNotLoaded) |
| 297 |
} |
| 298 |
} |
| 299 |
Ok(MonthPlaceholderValue::StringPattern(string, substitution_pattern)) => { |
| 300 |
w.with_part(PART, |w| { |
| 301 |
substitution_pattern.interpolate([string]).write_to(w) |
| 302 |
})?; |
| 303 |
Ok(()) |
| 304 |
} |
| 305 |
Err(e) => { |
| 306 |
w.with_part(PART, |w| { |
| 307 |
w.with_part(Part::ERROR, |w| w.write_str(&month.to_input().code().0)) |
| 308 |
})?; |
| 309 |
Err(match e { |
| 310 |
GetNameForMonthError::InvalidMonthCode => { |
| 311 |
FormattedDateTimePatternError::InvalidMonthCode(month.to_input().code()) |
| 312 |
} |
| 313 |
GetNameForMonthError::InvalidFieldLength => { |
| 314 |
FormattedDateTimePatternError::UnsupportedLength(ErrorField(field)) |
| 315 |
} |
| 316 |
GetNameForMonthError::NotLoaded => { |
| 317 |
FormattedDateTimePatternError::NamesNotLoaded(ErrorField(field)) |
| 318 |
} |
| 319 |
}) |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
(FieldSymbol::Week(w), _) => match w {}, |
| 324 |
(FieldSymbol::Weekday(weekday), l) => { |
| 325 |
const PART: Part = parts::WEEKDAY; |
| 326 |
input!(PART, Weekday, iso_weekday = input.weekday); |
| 327 |
match datetime_names |
| 328 |
.get_name_for_weekday(weekday, l, iso_weekday) |
| 329 |
.map_err(|e| match e { |
| 330 |
GetNameForWeekdayError::InvalidFieldLength => { |
| 331 |
FormattedDateTimePatternError::UnsupportedLength(ErrorField(field)) |
| 332 |
} |
| 333 |
GetNameForWeekdayError::NotLoaded => { |
| 334 |
FormattedDateTimePatternError::NamesNotLoaded(ErrorField(field)) |
| 335 |
} |
| 336 |
}) { |
| 337 |
Err(e) => { |
| 338 |
w.with_part(PART, |w| { |
| 339 |
w.with_part(Part::ERROR, |w| { |
| 340 |
w.write_str(match iso_weekday { |
| 341 |
Weekday::Monday => "mon", |
| 342 |
Weekday::Tuesday => "tue", |
| 343 |
Weekday::Wednesday => "wed", |
| 344 |
Weekday::Thursday => "thu", |
| 345 |
Weekday::Friday => "fri", |
| 346 |
Weekday::Saturday => "sat", |
| 347 |
Weekday::Sunday => "sun", |
| 348 |
}) |
| 349 |
}) |
| 350 |
})?; |
| 351 |
Err(e) |
| 352 |
} |
| 353 |
Ok(s) => Ok(w.with_part(PART, |w| w.write_str(s))?), |
| 354 |
} |
| 355 |
} |
| 356 |
(FieldSymbol::Day(fields::Day::DayOfMonth), FieldLength::NumericOverride(o)) => { |
| 357 |
const PART: Part = parts::DAY; |
| 358 |
input!(PART, DayOfMonth, day_of_month = input.day_of_month); |
| 359 |
numeric_override::format(PART, w, u32::from(day_of_month.0), o)? |
| 360 |
} |
| 361 |
(FieldSymbol::Day(fields::Day::DayOfMonth), l) => { |
| 362 |
const PART: Part = parts::DAY; |
| 363 |
input!(PART, DayOfMonth, day_of_month = input.day_of_month); |
| 364 |
try_write_number(PART, w, decimal_formatter, day_of_month.0.into(), l)? |
| 365 |
} |
| 366 |
(FieldSymbol::Day(fields::Day::DayOfWeekInMonth), l) => { |
| 367 |
input!(_, DayOfMonth, day_of_month = input.day_of_month); |
| 368 |
try_write_number_without_part( |
| 369 |
w, |
| 370 |
decimal_formatter, |
| 371 |
DayOfWeekInMonth::from(day_of_month).0.into(), |
| 372 |
l, |
| 373 |
)? |
| 374 |
} |
| 375 |
(FieldSymbol::Day(fields::Day::DayOfYear), l) => { |
| 376 |
input!(_, DayOfYear, day_of_year = input.day_of_year); |
| 377 |
try_write_number_without_part(w, decimal_formatter, day_of_year.0.into(), l)? |
| 378 |
} |
| 379 |
(FieldSymbol::Day(fields::Day::ModifiedJulianDay), l) => { |
| 380 |
const PART: Part = parts::JULIAN_DAY; |
| 381 |
const MODIFIED_JULIAN_DAY_EPOCH: RataDie = RataDie::new(-1721425); |
| 382 |
input!(_, RataDie, rata_die = input.rata_die); |
| 383 |
let julian_day = rata_die - MODIFIED_JULIAN_DAY_EPOCH; |
| 384 |
try_write_number(PART, w, decimal_formatter, julian_day.into(), l)? |
| 385 |
} |
| 386 |
(FieldSymbol::Hour(symbol), l) => { |
| 387 |
const PART: Part = parts::HOUR; |
| 388 |
input!(PART, Hour, hour = input.hour); |
| 389 |
let h = hour.number(); |
| 390 |
let h = match symbol { |
| 391 |
fields::Hour::H11 => h % 12, |
| 392 |
fields::Hour::H12 => { |
| 393 |
let v = h % 12; |
| 394 |
if v == 0 { 12 } else { v } |
| 395 |
} |
| 396 |
fields::Hour::H23 => h, |
| 397 |
}; |
| 398 |
try_write_number(PART, w, decimal_formatter, h.into(), l)? |
| 399 |
} |
| 400 |
(FieldSymbol::Minute, l) => { |
| 401 |
const PART: Part = parts::MINUTE; |
| 402 |
input!(PART, Minute, minute = input.minute); |
| 403 |
try_write_number(PART, w, decimal_formatter, minute.number().into(), l)? |
| 404 |
} |
| 405 |
(FieldSymbol::Second(Second::Second), l) => { |
| 406 |
const PART: Part = parts::SECOND; |
| 407 |
input!(PART, Second, second = input.second); |
| 408 |
try_write_number(PART, w, decimal_formatter, second.number().into(), l)? |
| 409 |
} |
| 410 |
(FieldSymbol::Second(Second::MillisInDay), l) => { |
| 411 |
input!(_, Hour, hour = input.hour); |
| 412 |
input!(_, Minute, minute = input.minute); |
| 413 |
input!(_, Second, second = input.second); |
| 414 |
input!(_, Subsecond, subsecond = input.subsecond); |
| 415 |
|
| 416 |
let milliseconds = (((hour.number() as u32 * 60) + minute.number() as u32) * 60 |
| 417 |
+ second.number() as u32) |
| 418 |
* 1000 |
| 419 |
+ subsecond.number() / 1_000_000; |
| 420 |
try_write_number_without_part(w, decimal_formatter, milliseconds.into(), l)? |
| 421 |
} |
| 422 |
(FieldSymbol::DecimalSecond(decimal_second), l) => { |
| 423 |
const PART: Part = parts::SECOND; |
| 424 |
input!(PART, Second, second = input.second); |
| 425 |
input!(PART, Subsecond, subsecond = input.subsecond); |
| 426 |
|
| 427 |
// Formatting with fractional seconds |
| 428 |
let mut s = Decimal::from(second.number()); |
| 429 |
let _infallible = s.concatenate_end( |
| 430 |
Decimal::from(subsecond.number()) |
| 431 |
.absolute |
| 432 |
.multiplied_pow10(-9), |
| 433 |
); |
| 434 |
debug_assert!(_infallible.is_ok()); |
| 435 |
let position = -(decimal_second as i16); |
| 436 |
s.trunc(position); |
| 437 |
s.pad_end(position); |
| 438 |
try_write_number(PART, w, decimal_formatter, s, l)? |
| 439 |
} |
| 440 |
(FieldSymbol::DayPeriod(period), l) => { |
| 441 |
const PART: Part = parts::DAY_PERIOD; |
| 442 |
input!(PART, Hour, hour = input.hour); |
| 443 |
|
| 444 |
match datetime_names.get_name_for_day_period( |
| 445 |
period, |
| 446 |
l, |
| 447 |
hour, |
| 448 |
pattern_metadata.time_granularity().is_top_of_hour( |
| 449 |
input.minute.unwrap_or_default().number(), |
| 450 |
input.second.unwrap_or_default().number(), |
| 451 |
input.subsecond.unwrap_or_default().number(), |
| 452 |
), |
| 453 |
) { |
| 454 |
Err(e) => { |
| 455 |
w.with_part(PART, |w| { |
| 456 |
w.with_part(Part::ERROR, |w| { |
| 457 |
w.write_str(if hour.number() < 12 { "AM" } else { "PM" }) |
| 458 |
}) |
| 459 |
})?; |
| 460 |
Err(match e { |
| 461 |
GetNameForDayPeriodError::InvalidFieldLength => { |
| 462 |
FormattedDateTimePatternError::UnsupportedLength(ErrorField(field)) |
| 463 |
} |
| 464 |
GetNameForDayPeriodError::NotLoaded => { |
| 465 |
FormattedDateTimePatternError::NamesNotLoaded(ErrorField(field)) |
| 466 |
} |
| 467 |
}) |
| 468 |
} |
| 469 |
Ok(s) => Ok(w.with_part(PART, |w| w.write_str(s))?), |
| 470 |
} |
| 471 |
} |
| 472 |
(FieldSymbol::TimeZone(fields::TimeZone::SpecificNonLocation), FieldLength::Four) => { |
| 473 |
perform_timezone_fallback( |
| 474 |
w, |
| 475 |
input, |
| 476 |
datetime_names, |
| 477 |
decimal_formatter, |
| 478 |
field, |
| 479 |
&[ |
| 480 |
TimeZoneFormatterUnit::SpecificNonLocation(FieldLength::Four), |
| 481 |
TimeZoneFormatterUnit::LocalizedOffset(FieldLength::Four), |
| 482 |
], |
| 483 |
)? |
| 484 |
} |
| 485 |
(FieldSymbol::TimeZone(fields::TimeZone::SpecificNonLocation), l) => { |
| 486 |
perform_timezone_fallback( |
| 487 |
w, |
| 488 |
input, |
| 489 |
datetime_names, |
| 490 |
decimal_formatter, |
| 491 |
field, |
| 492 |
&[ |
| 493 |
TimeZoneFormatterUnit::SpecificNonLocation(l), |
| 494 |
TimeZoneFormatterUnit::LocalizedOffset(l), |
| 495 |
], |
| 496 |
)? |
| 497 |
} |
| 498 |
(FieldSymbol::TimeZone(fields::TimeZone::GenericNonLocation), l) => { |
| 499 |
perform_timezone_fallback( |
| 500 |
w, |
| 501 |
input, |
| 502 |
datetime_names, |
| 503 |
decimal_formatter, |
| 504 |
field, |
| 505 |
&[ |
| 506 |
TimeZoneFormatterUnit::GenericNonLocation(l), |
| 507 |
TimeZoneFormatterUnit::GenericLocation, |
| 508 |
TimeZoneFormatterUnit::LocalizedOffset(l), |
| 509 |
], |
| 510 |
)? |
| 511 |
} |
| 512 |
(FieldSymbol::TimeZone(fields::TimeZone::Location), FieldLength::Four) => { |
| 513 |
perform_timezone_fallback( |
| 514 |
w, |
| 515 |
input, |
| 516 |
datetime_names, |
| 517 |
decimal_formatter, |
| 518 |
field, |
| 519 |
&[ |
| 520 |
TimeZoneFormatterUnit::GenericLocation, |
| 521 |
TimeZoneFormatterUnit::LocalizedOffset(FieldLength::Four), |
| 522 |
], |
| 523 |
)? |
| 524 |
} |
| 525 |
(FieldSymbol::TimeZone(fields::TimeZone::Location), FieldLength::Three) => { |
| 526 |
perform_timezone_fallback( |
| 527 |
w, |
| 528 |
input, |
| 529 |
datetime_names, |
| 530 |
decimal_formatter, |
| 531 |
field, |
| 532 |
&[TimeZoneFormatterUnit::ExemplarCity], |
| 533 |
)? |
| 534 |
} |
| 535 |
(FieldSymbol::TimeZone(fields::TimeZone::LocalizedOffset), l) => perform_timezone_fallback( |
| 536 |
w, |
| 537 |
input, |
| 538 |
datetime_names, |
| 539 |
decimal_formatter, |
| 540 |
field, |
| 541 |
&[TimeZoneFormatterUnit::LocalizedOffset(l)], |
| 542 |
)?, |
| 543 |
(FieldSymbol::TimeZone(fields::TimeZone::Location), _) => perform_timezone_fallback( |
| 544 |
w, |
| 545 |
input, |
| 546 |
datetime_names, |
| 547 |
decimal_formatter, |
| 548 |
field, |
| 549 |
&[TimeZoneFormatterUnit::Bcp47Id], |
| 550 |
)?, |
| 551 |
(FieldSymbol::TimeZone(fields::TimeZone::IsoWithZ), l) => perform_timezone_fallback( |
| 552 |
w, |
| 553 |
input, |
| 554 |
datetime_names, |
| 555 |
decimal_formatter, |
| 556 |
field, |
| 557 |
&[TimeZoneFormatterUnit::Iso8601(Iso8601Format::with_z(l))], |
| 558 |
)?, |
| 559 |
(FieldSymbol::TimeZone(fields::TimeZone::Iso), l) => perform_timezone_fallback( |
| 560 |
w, |
| 561 |
input, |
| 562 |
datetime_names, |
| 563 |
decimal_formatter, |
| 564 |
field, |
| 565 |
&[TimeZoneFormatterUnit::Iso8601(Iso8601Format::without_z(l))], |
| 566 |
)?, |
| 567 |
}) |
| 568 |
} |
| 569 |
|
| 570 |
// Writes an error string for the given symbol |
| 571 |
fn write_value_missing( |
| 572 |
w: &mut (impl PartsWrite + ?Sized), |
| 573 |
field: fields::Field, |
| 574 |
) -> Result<(), fmt::Error> { |
| 575 |
w.with_part(Part::ERROR, |w| { |
| 576 |
"{".write_to(w)?; |
| 577 |
char::from(field.symbol).write_to(w)?; |
| 578 |
"}".write_to(w) |
| 579 |
}) |
| 580 |
} |
| 581 |
|
| 582 |
fn perform_timezone_fallback( |
| 583 |
w: &mut (impl PartsWrite + ?Sized), |
| 584 |
input: &DateTimeInputUnchecked, |
| 585 |
datetime_names: &RawDateTimeNamesBorrowed, |
| 586 |
fdf: Option<&DecimalFormatter>, |
| 587 |
field: fields::Field, |
| 588 |
units: &[TimeZoneFormatterUnit], |
| 589 |
) -> Result<Result<(), FormattedDateTimePatternError>, fmt::Error> { |
| 590 |
const PART: Part = parts::TIME_ZONE_NAME; |
| 591 |
let payloads = datetime_names.get_payloads(); |
| 592 |
let mut r = Err(FormatTimeZoneError::Fallback); |
| 593 |
for unit in units { |
| 594 |
let mut inner_result = None; |
| 595 |
w.with_part(PART, |w| { |
| 596 |
inner_result = Some(unit.format(w, input, payloads, fdf)?); |
| 597 |
Ok(()) |
| 598 |
})?; |
| 599 |
match inner_result { |
| 600 |
Some(Err(FormatTimeZoneError::Fallback)) => { |
| 601 |
// Expected, try the next unit |
| 602 |
continue; |
| 603 |
} |
| 604 |
Some(r2) => { |
| 605 |
r = r2; |
| 606 |
break; |
| 607 |
} |
| 608 |
None => { |
| 609 |
debug_assert!(false, "unreachable"); |
| 610 |
return Err(fmt::Error); |
| 611 |
} |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
Ok(match r { |
| 616 |
Ok(()) => Ok(()), |
| 617 |
Err(e) => { |
| 618 |
if let Some(offset) = input.zone_offset { |
| 619 |
w.with_part(PART, |w| { |
| 620 |
w.with_part(Part::ERROR, |w| { |
| 621 |
Iso8601Format::without_z(field.length).format_infallible(w, offset) |
| 622 |
}) |
| 623 |
})?; |
| 624 |
} else { |
| 625 |
w.with_part(PART, |w| write_value_missing(w, field))?; |
| 626 |
} |
| 627 |
match e { |
| 628 |
FormatTimeZoneError::DecimalFormatterNotLoaded => { |
| 629 |
Err(FormattedDateTimePatternError::DecimalFormatterNotLoaded) |
| 630 |
} |
| 631 |
FormatTimeZoneError::NamesNotLoaded => Err( |
| 632 |
FormattedDateTimePatternError::NamesNotLoaded(ErrorField(field)), |
| 633 |
), |
| 634 |
FormatTimeZoneError::MissingInputField(kind) => { |
| 635 |
Err(FormattedDateTimePatternError::MissingInputField(kind)) |
| 636 |
} |
| 637 |
FormatTimeZoneError::Fallback => { |
| 638 |
debug_assert!(false, "timezone fallback chain fell through {input:?}"); |
| 639 |
Ok(()) |
| 640 |
} |
| 641 |
} |
| 642 |
} |
| 643 |
}) |
| 644 |
} |
| 645 |
|
| 646 |
#[cfg(test)] |
| 647 |
#[allow(unused_imports)] |
| 648 |
#[cfg(feature = "compiled_data")] |
| 649 |
mod tests { |
| 650 |
use super::*; |
| 651 |
use icu_decimal::options::{DecimalFormatterOptions, GroupingStrategy}; |
| 652 |
|
| 653 |
#[test] |
| 654 |
fn test_format_number() { |
| 655 |
let values = &[2, 20, 201, 2017, 20173]; |
| 656 |
let samples = &[ |
| 657 |
(FieldLength::One, ["2", "20", "201", "2017", "20173"]), |
| 658 |
(FieldLength::Two, ["02", "20", "201", "2017", "20173"]), |
| 659 |
(FieldLength::Three, ["002", "020", "201", "2017", "20173"]), |
| 660 |
(FieldLength::Four, ["0002", "0020", "0201", "2017", "20173"]), |
| 661 |
]; |
| 662 |
|
| 663 |
let mut decimal_formatter_options = DecimalFormatterOptions::default(); |
| 664 |
decimal_formatter_options.grouping_strategy = Some(GroupingStrategy::Never); |
| 665 |
let decimal_formatter = DecimalFormatter::try_new( |
| 666 |
icu_locale_core::locale!("en").into(), |
| 667 |
decimal_formatter_options, |
| 668 |
) |
| 669 |
.unwrap(); |
| 670 |
|
| 671 |
for (length, expected) in samples { |
| 672 |
for (value, expected) in values.iter().zip(expected) { |
| 673 |
let mut s = String::new(); |
| 674 |
try_write_number_without_part( |
| 675 |
&mut writeable::adapters::CoreWriteAsPartsWrite(&mut s), |
| 676 |
Some(&decimal_formatter), |
| 677 |
Decimal::from(*value), |
| 678 |
*length, |
| 679 |
) |
| 680 |
.unwrap() |
| 681 |
.unwrap(); |
| 682 |
assert_eq!(s, *expected); |
| 683 |
} |
| 684 |
} |
| 685 |
} |
| 686 |
|
| 687 |
#[test] |
| 688 |
fn julian_day() { |
| 689 |
let locale = icu_locale_core::locale!("en"); |
| 690 |
let parsed_pattern = DateTimePattern::try_from_pattern_str("g").unwrap(); |
| 691 |
let mut names = FixedCalendarDateTimeNames::< |
| 692 |
icu_calendar::cal::Gregorian, |
| 693 |
crate::fieldsets::enums::DateFieldSet, |
| 694 |
>::try_new(locale.into()) |
| 695 |
.unwrap(); |
| 696 |
let formatted_datetime = names |
| 697 |
.include_for_pattern(&parsed_pattern) |
| 698 |
.unwrap() |
| 699 |
.format(&crate::input::Date::try_new_gregorian(1996, 9, 2).unwrap()); |
| 700 |
writeable::assert_try_writeable_eq!(formatted_datetime, "2450329", Ok(())); |
| 701 |
} |
| 702 |
|
| 703 |
#[test] |
| 704 |
fn extended_year() { |
| 705 |
let locale = icu_locale_core::locale!("en"); |
| 706 |
let parsed_pattern = DateTimePattern::try_from_pattern_str("u").unwrap(); |
| 707 |
let mut names = FixedCalendarDateTimeNames::< |
| 708 |
icu_calendar::cal::Ethiopian, |
| 709 |
crate::fieldsets::enums::DateFieldSet, |
| 710 |
>::try_new(locale.into()) |
| 711 |
.unwrap(); |
| 712 |
let formatted_datetime = names.include_for_pattern(&parsed_pattern).unwrap().format( |
| 713 |
&crate::input::Date::try_new_ethiopian( |
| 714 |
icu_calendar::cal::EthiopianEraStyle::AmeteMihret, |
| 715 |
10, |
| 716 |
9, |
| 717 |
2, |
| 718 |
) |
| 719 |
.unwrap(), |
| 720 |
); |
| 721 |
writeable::assert_try_writeable_eq!(formatted_datetime, "10", Ok(())); |
| 722 |
} |
| 723 |
} |