oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/datetime.rs
20.6 KiB, 17 runs
created by r1870400018:63228, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | // U3 owns this file. `datetime` and `duration`: constructors and methods, `display` with the `time` |
| 2 | // crate's format-description syntax Typst uses (`[year]-[month]-[day]`, `[month repr:long]`), and the |
| 3 | // date arithmetic the operators need (`datetime_add`, `datetime_sub`, for `ops.rs`). `today` reads the host |
| 4 | // clock; a document compiled across midnight may see two dates, which Typst shares. |
| 5 | |
| 6 | use crate::diag::DiagnosticKind; |
| 7 | use crate::eval::args::Args; |
| 8 | use crate::eval::func::{ |
| 9 | Func, |
| 10 | NativeFunc, |
| 11 | }; |
| 12 | use crate::eval::lib::foundations::{ |
| 13 | finish, |
| 14 | mismatch, |
| 15 | no_method, |
| 16 | receiver, |
| 17 | }; |
| 18 | use crate::eval::scope::Scope; |
| 19 | use crate::eval::value::{ |
| 20 | Datetime, |
| 21 | Duration, |
| 22 | Type, |
| 23 | Value, |
| 24 | }; |
| 25 | use crate::eval::Engine; |
| 26 | use crate::syntax::Span; |
| 27 | |
| 28 | use oxedyne_fe2o3_core::prelude::*; |
| 29 | |
| 30 | native_fns! { |
| 31 | pub enum DatetimeFn { |
| 32 | Datetime => "datetime", |
| 33 | Today => "today", |
| 34 | Display => "display", |
| 35 | Year => "year", |
| 36 | Month => "month", |
| 37 | Weekday => "weekday", |
| 38 | Day => "day", |
| 39 | Hour => "hour", |
| 40 | Minute => "minute", |
| 41 | Second => "second", |
| 42 | Ordinal => "ordinal", |
| 43 | Duration => "duration", |
| 44 | Seconds => "seconds", |
| 45 | Minutes => "minutes", |
| 46 | Hours => "hours", |
| 47 | Days => "days", |
| 48 | Weeks => "weeks", |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub fn define(_scope: &mut Scope) {} |
| 53 | |
| 54 | pub fn method(name: &str) -> Option<DatetimeFn> { |
| 55 | let f = match name { |
| 56 | "display" => DatetimeFn::Display, |
| 57 | "year" => DatetimeFn::Year, |
| 58 | "month" => DatetimeFn::Month, |
| 59 | "weekday" => DatetimeFn::Weekday, |
| 60 | "day" => DatetimeFn::Day, |
| 61 | "hour" => DatetimeFn::Hour, |
| 62 | "minute" => DatetimeFn::Minute, |
| 63 | "second" => DatetimeFn::Second, |
| 64 | "ordinal" => DatetimeFn::Ordinal, |
| 65 | other => return duration_method(other), |
| 66 | }; |
| 67 | Some(f) |
| 68 | } |
| 69 | |
| 70 | pub fn duration_method(name: &str) -> Option<DatetimeFn> { |
| 71 | let f = match name { |
| 72 | "seconds" => DatetimeFn::Seconds, |
| 73 | "minutes" => DatetimeFn::Minutes, |
| 74 | "hours" => DatetimeFn::Hours, |
| 75 | "days" => DatetimeFn::Days, |
| 76 | "weeks" => DatetimeFn::Weeks, |
| 77 | _ => return None, |
| 78 | }; |
| 79 | Some(f) |
| 80 | } |
| 81 | |
| 82 | /// `datetime.today` as a function value. |
| 83 | pub fn today_func() -> Value { Value::Func(Func::Native(NativeFunc::Datetime(DatetimeFn::Today))) } |
| 84 | |
| 85 | // Calendar arithmetic, after Howard Hinnant's `days_from_civil`: days since 1970-01-01. |
| 86 | |
| 87 | pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 { |
| 88 | let y = if m <= 2 { y - 1 } else { y }; |
| 89 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 90 | let yoe = y - era * 400; |
| 91 | let mp = (m as i64 + 9) % 12; |
| 92 | let doy = (153 * mp + 2) / 5 + d as i64 - 1; |
| 93 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| 94 | era * 146_097 + doe - 719_468 |
| 95 | } |
| 96 | |
| 97 | pub fn civil_from_days(z: i64) -> (i64, u32, u32) { |
| 98 | let z = z + 719_468; |
| 99 | let era = if z >= 0 { z } else { z - 146_096 } / 146_097; |
| 100 | let doe = z - era * 146_097; |
| 101 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 102 | let y = yoe + era * 400; |
| 103 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 104 | let mp = (5 * doy + 2) / 153; |
| 105 | let d = (doy - (153 * mp + 2) / 5 + 1) as u32; |
| 106 | let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; |
| 107 | (if m <= 2 { y + 1 } else { y }, m, d) |
| 108 | } |
| 109 | |
| 110 | fn is_leap(y: i64) -> bool { (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 } |
| 111 | |
| 112 | fn days_in_month(y: i64, m: u32) -> u32 { |
| 113 | match m { |
| 114 | 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, |
| 115 | 4 | 6 | 9 | 11 => 30, |
| 116 | _ => if is_leap(y) { 29 } else { 28 }, |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// Monday is 1, Sunday 7. |
| 121 | fn weekday(y: i64, m: u32, d: u32) -> u32 { |
| 122 | let z = days_from_civil(y, m, d); |
| 123 | ((z + 3).rem_euclid(7) + 1) as u32 |
| 124 | } |
| 125 | |
| 126 | fn ordinal(y: i64, m: u32, d: u32) -> u32 { (days_from_civil(y, m, d) - days_from_civil(y, 1, 1) + 1) as u32 } |
| 127 | |
| 128 | // The ISO 8601 week-numbering year and week. |
| 129 | fn iso_week(y: i64, m: u32, d: u32) -> (i64, u32) { |
| 130 | let ord = ordinal(y, m, d) as i64; |
| 131 | let wd = weekday(y, m, d) as i64; |
| 132 | let w = (ord - wd + 10) / 7; |
| 133 | if w < 1 { |
| 134 | let py = y - 1; |
| 135 | (py, weeks_in_year(py)) |
| 136 | } else if w > weeks_in_year(y) as i64 { |
| 137 | (y + 1, 1) |
| 138 | } else { |
| 139 | (y, w as u32) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | fn weeks_in_year(y: i64) -> u32 { |
| 144 | let p = |y: i64| (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7); |
| 145 | if p(y) == 4 || p(y - 1) == 3 { 53 } else { 52 } |
| 146 | } |
| 147 | |
| 148 | fn has_date(d: &Datetime) -> bool { d.year.is_some() && d.month.is_some() && d.day.is_some() } |
| 149 | |
| 150 | fn has_time(d: &Datetime) -> bool { d.hour.is_some() && d.minute.is_some() && d.second.is_some() } |
| 151 | |
| 152 | // Days since the epoch of a datetime's date part, and seconds since midnight of its time part; each |
| 153 | // called only once `has_date`/`has_time` has said the part is there. |
| 154 | fn epoch_days(dt: &Datetime) -> i64 { |
| 155 | days_from_civil(dt.year.unwrap_or(1970) as i64, dt.month.unwrap_or(1) as u32, dt.day.unwrap_or(1) as u32) |
| 156 | } |
| 157 | |
| 158 | fn clock_secs(dt: &Datetime) -> i64 { |
| 159 | dt.hour.unwrap_or(0) as i64 * 3600 + dt.minute.unwrap_or(0) as i64 * 60 + dt.second.unwrap_or(0) as i64 |
| 160 | } |
| 161 | |
| 162 | fn set_date(out: &mut Datetime, days: i64) -> bool { |
| 163 | let (y, m, d) = civil_from_days(days); |
| 164 | if !(-9999..=9999).contains(&y) { |
| 165 | return false; |
| 166 | } |
| 167 | out.year = Some(y as i32); |
| 168 | out.month = Some(m as u8); |
| 169 | out.day = Some(d as u8); |
| 170 | true |
| 171 | } |
| 172 | |
| 173 | fn set_clock(out: &mut Datetime, secs: i64) { |
| 174 | out.hour = Some((secs / 3600) as u8); |
| 175 | out.minute = Some((secs / 60 % 60) as u8); |
| 176 | out.second = Some((secs % 60) as u8); |
| 177 | } |
| 178 | |
| 179 | /// `datetime + duration`: a date moves by whole days, a time wraps round the clock, and a date with a time |
| 180 | /// carries across midnight, as Typst's. `None` past the representable years. |
| 181 | pub fn datetime_add(dt: &Datetime, dur: &Duration) -> Option<Datetime> { |
| 182 | let secs = dur.secs.trunc() as i64; |
| 183 | let mut out = *dt; |
| 184 | match (has_date(dt), has_time(dt)) { |
| 185 | (true, true) => { |
| 186 | let total = epoch_days(dt) * 86_400 + clock_secs(dt) + secs; |
| 187 | if !set_date(&mut out, total.div_euclid(86_400)) { |
| 188 | return None; |
| 189 | } |
| 190 | set_clock(&mut out, total.rem_euclid(86_400)); |
| 191 | } |
| 192 | (true, false) => if !set_date(&mut out, epoch_days(dt) + secs.div_euclid(86_400)) { |
| 193 | return None; |
| 194 | }, |
| 195 | (false, true) => set_clock(&mut out, (clock_secs(dt) + secs).rem_euclid(86_400)), |
| 196 | (false, false) => return None, |
| 197 | } |
| 198 | Some(out) |
| 199 | } |
| 200 | |
| 201 | /// `datetime - datetime`, when both have the same parts. |
| 202 | pub fn datetime_sub(a: &Datetime, b: &Datetime) -> Option<Duration> { |
| 203 | if has_date(a) != has_date(b) || has_time(a) != has_time(b) { |
| 204 | return None; |
| 205 | } |
| 206 | let secs = |dt: &Datetime| -> i64 { |
| 207 | let d = if has_date(dt) { epoch_days(dt) * 86_400 } else { 0 }; |
| 208 | d + if has_time(dt) { clock_secs(dt) } else { 0 } |
| 209 | }; |
| 210 | Some(Duration { secs: (secs(a) - secs(b)) as f64 }) |
| 211 | } |
| 212 | |
| 213 | // Milliseconds since the Unix epoch, UTC. |
| 214 | fn now_ms() -> Option<i64> { |
| 215 | #[cfg(target_arch = "wasm32")] |
| 216 | { |
| 217 | Some(js_sys::Date::now().floor() as i64) |
| 218 | } |
| 219 | #[cfg(not(target_arch = "wasm32"))] |
| 220 | { |
| 221 | match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) { |
| 222 | Ok(d) => i64::try_from(d.as_millis()).ok(), |
| 223 | Err(_) => None, |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | // The host zone's offset from UTC at instant `utc`, in milliseconds east; none where the zone cannot be read. |
| 229 | fn local_offset_ms(utc: i64) -> i64 { |
| 230 | #[cfg(target_arch = "wasm32")] |
| 231 | { |
| 232 | // `getTimezoneOffset` is in minutes, positive west of UTC. |
| 233 | let d = js_sys::Date::new(&wasm_bindgen::JsValue::from_f64(utc as f64)); |
| 234 | -(d.get_timezone_offset() * 60_000.0) as i64 |
| 235 | } |
| 236 | #[cfg(not(target_arch = "wasm32"))] |
| 237 | { |
| 238 | match oxedyne_fe2o3_datime::time::zone::CalClockZone::local().utc_to_local(utc) { |
| 239 | oxedyne_fe2o3_datime::time::tzif::LocalTimeResult::Single(l) => l - utc, |
| 240 | _ => 0, |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /// The calendar date at instant `utc` (milliseconds since the epoch) on a clock `shift` milliseconds east. |
| 246 | pub fn date_at(utc: i64, shift: i64) -> (i64, u32, u32) { |
| 247 | civil_from_days(utc.saturating_add(shift).div_euclid(86_400_000)) |
| 248 | } |
| 249 | |
| 250 | fn opt_int(engine: &mut Engine, span: Span, v: Option<Value>) -> Outcome<Option<i64>> { |
| 251 | match v { |
| 252 | None => Ok(None), |
| 253 | Some(Value::Int(i)) => Ok(Some(i)), |
| 254 | Some(other) => Err(mismatch(engine, span, "integer", &other)), |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | fn dt_recv(engine: &mut Engine, args: &mut Args) -> Outcome<Datetime> { |
| 259 | match res!(receiver(args)) { |
| 260 | Value::Datetime(d) => Ok(d), |
| 261 | other => Err(mismatch(engine, args.span, "datetime", &other)), |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | fn dur_recv(engine: &mut Engine, args: &mut Args) -> Outcome<Duration> { |
| 266 | match res!(receiver(args)) { |
| 267 | Value::Duration(d) => Ok(d), |
| 268 | other => Err(mismatch(engine, args.span, "duration", &other)), |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | fn opt(v: Option<u8>) -> Value { v.map(|x| Value::Int(x as i64)).unwrap_or(Value::None) } |
| 273 | |
| 274 | pub fn call(f: DatetimeFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> { |
| 275 | let span = args.span; |
| 276 | // Datetime and duration share one method table; each name belongs to one of the two types. |
| 277 | let owner = if duration_method(f.name()) == Some(f) { |
| 278 | Some(Type::Duration) |
| 279 | } else if method(f.name()) == Some(f) { |
| 280 | Some(Type::Datetime) |
| 281 | } else { |
| 282 | None |
| 283 | }; |
| 284 | if let (Some(owner), Some(a)) = (owner, args.items.iter().find(|a| a.name.is_none())) { |
| 285 | let ty = a.value.ty(); |
| 286 | if ty != owner { |
| 287 | return Err(no_method(engine, span, ty, f.name())); |
| 288 | } |
| 289 | } |
| 290 | let out = match f { |
| 291 | DatetimeFn::Datetime => { |
| 292 | let y = res!(args.named::<Value>("year")); |
| 293 | let y = res!(opt_int(engine, span, y)); |
| 294 | let mo = res!(args.named::<Value>("month")); |
| 295 | let mo = res!(opt_int(engine, span, mo)); |
| 296 | let d = res!(args.named::<Value>("day")); |
| 297 | let d = res!(opt_int(engine, span, d)); |
| 298 | let h = res!(args.named::<Value>("hour")); |
| 299 | let h = res!(opt_int(engine, span, h)); |
| 300 | let mi = res!(args.named::<Value>("minute")); |
| 301 | let mi = res!(opt_int(engine, span, mi)); |
| 302 | let s = res!(args.named::<Value>("second")); |
| 303 | let s = res!(opt_int(engine, span, s)); |
| 304 | res!(construct(engine, span, [y, mo, d], [h, mi, s])) |
| 305 | } |
| 306 | DatetimeFn::Today => { |
| 307 | let offset = res!(args.named::<Value>("offset")); |
| 308 | let utc = match now_ms() { |
| 309 | Some(t) => t, |
| 310 | None => return Err(engine.error(DiagnosticKind::Type, span, "unable to get the current date")), |
| 311 | }; |
| 312 | // As Typst: `auto` is the host's own zone, an integer that many hours east of UTC. |
| 313 | let shift = match offset { |
| 314 | None | Some(Value::Auto) => local_offset_ms(utc), |
| 315 | Some(Value::Int(h)) => h.saturating_mul(3_600_000), |
| 316 | Some(other) => return Err(mismatch(engine, span, "auto or integer", &other)), |
| 317 | }; |
| 318 | let (y, m, d) = date_at(utc, shift); |
| 319 | Value::Datetime(Datetime { |
| 320 | year: Some(y as i32), month: Some(m as u8), day: Some(d as u8), hour: None, minute: None, second: None, |
| 321 | }) |
| 322 | } |
| 323 | DatetimeFn::Display => { |
| 324 | let dt = res!(dt_recv(engine, &mut args)); |
| 325 | let pat = res!(args.eat::<Value>()); |
| 326 | let pat = match pat { |
| 327 | None | Some(Value::Auto) => match (has_date(&dt), has_time(&dt)) { |
| 328 | (true, true) => "[year]-[month]-[day] [hour]:[minute]:[second]".to_string(), |
| 329 | (true, false) => "[year]-[month]-[day]".to_string(), |
| 330 | _ => "[hour]:[minute]:[second]".to_string(), |
| 331 | }, |
| 332 | Some(Value::Str(s)) => (*s).clone(), |
| 333 | Some(other) => return Err(mismatch(engine, span, "auto or string", &other)), |
| 334 | }; |
| 335 | match display(&dt, &pat) { |
| 336 | Ok(s) => Value::str(s), |
| 337 | Err(m) => return Err(engine.error(DiagnosticKind::Type, span, m)), |
| 338 | } |
| 339 | } |
| 340 | DatetimeFn::Year => res!(dt_recv(engine, &mut args)).year.map(|y| Value::Int(y as i64)).unwrap_or(Value::None), |
| 341 | DatetimeFn::Month => opt(res!(dt_recv(engine, &mut args)).month), |
| 342 | DatetimeFn::Day => opt(res!(dt_recv(engine, &mut args)).day), |
| 343 | DatetimeFn::Hour => opt(res!(dt_recv(engine, &mut args)).hour), |
| 344 | DatetimeFn::Minute => opt(res!(dt_recv(engine, &mut args)).minute), |
| 345 | DatetimeFn::Second => opt(res!(dt_recv(engine, &mut args)).second), |
| 346 | DatetimeFn::Weekday => { |
| 347 | let dt = res!(dt_recv(engine, &mut args)); |
| 348 | match (dt.year, dt.month, dt.day) { |
| 349 | (Some(y), Some(m), Some(d)) => Value::Int(weekday(y as i64, m as u32, d as u32) as i64), |
| 350 | _ => Value::None, |
| 351 | } |
| 352 | } |
| 353 | DatetimeFn::Ordinal => { |
| 354 | let dt = res!(dt_recv(engine, &mut args)); |
| 355 | match (dt.year, dt.month, dt.day) { |
| 356 | (Some(y), Some(m), Some(d)) => Value::Int(ordinal(y as i64, m as u32, d as u32) as i64), |
| 357 | _ => Value::None, |
| 358 | } |
| 359 | } |
| 360 | DatetimeFn::Duration => { |
| 361 | let mut secs: i64 = 0; |
| 362 | for (name, unit) in [("seconds", 1i64), ("minutes", 60), ("hours", 3600), ("days", 86_400), ("weeks", 604_800)] { |
| 363 | let v = res!(args.named::<Value>(name)); |
| 364 | if let Some(n) = res!(opt_int(engine, span, v)) { |
| 365 | secs = match n.checked_mul(unit).and_then(|x| secs.checked_add(x)) { |
| 366 | Some(s) => s, |
| 367 | None => return Err(engine.error(DiagnosticKind::Type, span, "duration is too large")), |
| 368 | }; |
| 369 | } |
| 370 | } |
| 371 | Value::Duration(Duration { secs: secs as f64 }) |
| 372 | } |
| 373 | DatetimeFn::Seconds => Value::Float(res!(dur_recv(engine, &mut args)).secs), |
| 374 | DatetimeFn::Minutes => Value::Float(res!(dur_recv(engine, &mut args)).secs / 60.0), |
| 375 | DatetimeFn::Hours => Value::Float(res!(dur_recv(engine, &mut args)).secs / 3600.0), |
| 376 | DatetimeFn::Days => Value::Float(res!(dur_recv(engine, &mut args)).secs / 86_400.0), |
| 377 | DatetimeFn::Weeks => Value::Float(res!(dur_recv(engine, &mut args)).secs / 604_800.0), |
| 378 | }; |
| 379 | res!(finish(engine, args)); |
| 380 | Ok(out) |
| 381 | } |
| 382 | |
| 383 | fn construct(engine: &mut Engine, span: Span, date: [Option<i64>; 3], time: [Option<i64>; 3]) -> Outcome<Value> { |
| 384 | let names = [["year", "month", "day"], ["hour", "minute", "second"]]; |
| 385 | let date_n = date.iter().filter(|x| x.is_some()).count(); |
| 386 | let time_n = time.iter().filter(|x| x.is_some()).count(); |
| 387 | let missing = |parts: &[Option<i64>; 3], names: &[&str; 3]| -> String { |
| 388 | let ms: Vec<String> = parts.iter().zip(names.iter()).filter(|(p, _)| p.is_none()) |
| 389 | .map(|(_, n)| fmt!("`{}`", n)).collect(); |
| 390 | match ms.len() { |
| 391 | 1 => fmt!("add the {} argument", ms[0]), |
| 392 | 2 => fmt!("add the {} and {} arguments", ms[0], ms[1]), |
| 393 | _ => fmt!("add the {}, {}, and {} arguments", ms[0], ms[1], ms[2]), |
| 394 | } |
| 395 | }; |
| 396 | if date_n == 0 && time_n == 0 { |
| 397 | let e = engine.error_hint(DiagnosticKind::Type, span, "at least one of date or time must be fully specified", |
| 398 | "add the `hour`, `minute`, and `second` arguments to get a valid time"); |
| 399 | if let Some(d) = engine.diags.last_mut() { |
| 400 | d.hints.push("add the `year`, `month`, and `day` arguments to get a valid date".to_string()); |
| 401 | } |
| 402 | return Err(e); |
| 403 | } |
| 404 | if date_n > 0 && date_n < 3 { |
| 405 | let hint = fmt!("{} to get a valid date", missing(&date, &names[0])); |
| 406 | return Err(engine.error_hint(DiagnosticKind::Type, span, "date is incomplete", hint)); |
| 407 | } |
| 408 | if time_n > 0 && time_n < 3 { |
| 409 | let hint = fmt!("{} to get a valid time", missing(&time, &names[1])); |
| 410 | return Err(engine.error_hint(DiagnosticKind::Type, span, "time is incomplete", hint)); |
| 411 | } |
| 412 | let mut dt = Datetime::default(); |
| 413 | if let [Some(y), Some(m), Some(d)] = date { |
| 414 | if !(1..=12).contains(&m) { |
| 415 | return Err(engine.error(DiagnosticKind::Type, span, "month is invalid")); |
| 416 | } |
| 417 | if !(-9999..=9999).contains(&y) || d < 1 || d > days_in_month(y, m as u32) as i64 { |
| 418 | return Err(engine.error(DiagnosticKind::Type, span, "date is invalid")); |
| 419 | } |
| 420 | dt.year = Some(y as i32); |
| 421 | dt.month = Some(m as u8); |
| 422 | dt.day = Some(d as u8); |
| 423 | } |
| 424 | if let [Some(h), Some(mi), Some(s)] = time { |
| 425 | if !(0..24).contains(&h) || !(0..60).contains(&mi) || !(0..60).contains(&s) { |
| 426 | return Err(engine.error(DiagnosticKind::Type, span, "time is invalid")); |
| 427 | } |
| 428 | dt.hour = Some(h as u8); |
| 429 | dt.minute = Some(mi as u8); |
| 430 | dt.second = Some(s as u8); |
| 431 | } |
| 432 | Ok(Value::Datetime(dt)) |
| 433 | } |
| 434 | |
| 435 | const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", |
| 436 | "September", "October", "November", "December"]; |
| 437 | const WEEKDAYS: [&str; 7] = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; |
| 438 | |
| 439 | const INSUFFICIENT: &str = "failed to format datetime (insufficient information)"; |
| 440 | |
| 441 | /// Formats with a `time`-crate format description; the error is Typst's message. |
| 442 | pub fn display(dt: &Datetime, pat: &str) -> std::result::Result<String, String> { |
| 443 | let mut out = String::new(); |
| 444 | let chars: Vec<(usize, char)> = pat.char_indices().collect(); |
| 445 | let mut i = 0; |
| 446 | while i < chars.len() { |
| 447 | let (_, c) = chars[i]; |
| 448 | if c != '[' { |
| 449 | out.push(c); |
| 450 | i += 1; |
| 451 | continue; |
| 452 | } |
| 453 | let open = chars[i].0; |
| 454 | let close = match chars[i..].iter().find(|(_, x)| *x == ']') { |
| 455 | Some((b, _)) => *b, |
| 456 | None => return Err(fmt!("unclosed opening bracket at index {}", open)), |
| 457 | }; |
| 458 | let body = &pat[open + 1..close]; |
| 459 | let mut words = body.split_whitespace(); |
| 460 | let name = match words.next() { |
| 461 | Some(n) if n.chars().all(|x| x.is_ascii_alphanumeric() || x == '_') => n, |
| 462 | _ => return Err(fmt!("expected component name at index {}", open)), |
| 463 | }; |
| 464 | let mut mods: Vec<(&str, &str)> = Vec::new(); |
| 465 | for w in words { |
| 466 | match w.split_once(':') { |
| 467 | Some(kv) => mods.push(kv), |
| 468 | None => return Err(fmt!("expected modifier value at index {}", open)), |
| 469 | } |
| 470 | } |
| 471 | let get = |k: &str| mods.iter().find(|(m, _)| *m == k).map(|(_, v)| *v); |
| 472 | let pad = |n: i64, width: usize| -> String { |
| 473 | let s = n.unsigned_abs().to_string(); |
| 474 | let body = match get("padding").unwrap_or("zero") { |
| 475 | "none" => s, |
| 476 | "space" => fmt!("{:>w$}", s, w = width), |
| 477 | _ => fmt!("{:0>w$}", s, w = width), |
| 478 | }; |
| 479 | if n < 0 { fmt!("-{}", body) } else { body } |
| 480 | }; |
| 481 | let date = match (dt.year, dt.month, dt.day) { |
| 482 | (Some(y), Some(m), Some(d)) => Some((y as i64, m as u32, d as u32)), |
| 483 | _ => None, |
| 484 | }; |
| 485 | let time = match (dt.hour, dt.minute, dt.second) { |
| 486 | (Some(h), Some(m), Some(s)) => Some((h as u32, m as u32, s as u32)), |
| 487 | _ => None, |
| 488 | }; |
| 489 | let text = match name { |
| 490 | "day" => pad((match date { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }).2 as i64, 2), |
| 491 | "month" => { |
| 492 | let m = (match date { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }).1; |
| 493 | match get("repr").unwrap_or("numerical") { |
| 494 | "long" => MONTHS[(m - 1) as usize].to_string(), |
| 495 | "short" => MONTHS[(m - 1) as usize][..3].to_string(), |
| 496 | _ => pad(m as i64, 2), |
| 497 | } |
| 498 | } |
| 499 | "ordinal" => { |
| 500 | let (y, m, d) = match date { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }; |
| 501 | pad(ordinal(y, m, d) as i64, 3) |
| 502 | } |
| 503 | "weekday" => { |
| 504 | let (y, m, d) = match date { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }; |
| 505 | let wd = weekday(y, m, d); |
| 506 | let one = get("one_indexed").unwrap_or("true") != "false"; |
| 507 | match get("repr").unwrap_or("long") { |
| 508 | "short" => WEEKDAYS[(wd - 1) as usize][..3].to_string(), |
| 509 | "sunday" => ((wd % 7) + if one { 1 } else { 0 }).to_string(), |
| 510 | "monday" => ((wd - 1) + if one { 1 } else { 0 }).to_string(), |
| 511 | _ => WEEKDAYS[(wd - 1) as usize].to_string(), |
| 512 | } |
| 513 | } |
| 514 | "week_number" => { |
| 515 | let (y, m, d) = match date { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }; |
| 516 | let ord = ordinal(y, m, d) as i64; |
| 517 | let wd = weekday(y, m, d) as i64; |
| 518 | let w = match get("repr").unwrap_or("iso") { |
| 519 | "sunday" => (ord + 6 - (wd % 7)) / 7, |
| 520 | "monday" => (ord + 6 - (wd - 1)) / 7, |
| 521 | _ => iso_week(y, m, d).1 as i64, |
| 522 | }; |
| 523 | pad(w, 2) |
| 524 | } |
| 525 | "year" => { |
| 526 | let (y0, m, d) = match date { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }; |
| 527 | let y = if get("base") == Some("iso_week") { iso_week(y0, m, d).0 } else { y0 }; |
| 528 | let body = match get("repr").unwrap_or("full") { |
| 529 | "last_two" => pad(y.rem_euclid(100), 2), |
| 530 | "century" => pad(y.div_euclid(100), 2), |
| 531 | _ => pad(y, 4), |
| 532 | }; |
| 533 | if get("sign") == Some("mandatory") && y >= 0 { fmt!("+{}", body) } else { body } |
| 534 | } |
| 535 | "hour" => { |
| 536 | let h = (match time { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }).0; |
| 537 | if get("repr") == Some("12") { |
| 538 | let h12 = if h % 12 == 0 { 12 } else { h % 12 }; |
| 539 | pad(h12 as i64, 2) |
| 540 | } else { |
| 541 | pad(h as i64, 2) |
| 542 | } |
| 543 | } |
| 544 | "minute" => pad((match time { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }).1 as i64, 2), |
| 545 | "second" => pad((match time { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }).2 as i64, 2), |
| 546 | "period" => { |
| 547 | let h = (match time { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }).0; |
| 548 | let p = if h < 12 { "AM" } else { "PM" }; |
| 549 | if get("case") == Some("lower") { p.to_lowercase() } else { p.to_string() } |
| 550 | } |
| 551 | "subsecond" => { |
| 552 | (match time { Some(x) => x, None => return Err(INSUFFICIENT.to_string()) }); |
| 553 | let digits: usize = get("digits").and_then(|d| d.parse().ok()).unwrap_or(1); |
| 554 | "0".repeat(digits.max(1)) |
| 555 | } |
| 556 | "offset_hour" | "offset_minute" | "offset_second" | "unix_timestamp" => return Err(INSUFFICIENT.to_string()), |
| 557 | "ignore" | "end" => String::new(), |
| 558 | other => return Err(fmt!("invalid component name '{}' at index {}", other, open + 1)), |
| 559 | }; |
| 560 | out.push_str(&text); |
| 561 | i += chars[i..].iter().position(|(_, x)| *x == ']').unwrap_or(0) + 1; |
| 562 | } |
| 563 | Ok(out) |
| 564 | } |
| 565 | |
| 566 | #[cfg(test)] |
| 567 | mod tests { |
| 568 | use super::*; |
| 569 | |
| 570 | #[test] |
| 571 | fn test_today_is_the_date_on_the_shifted_clock() { |
| 572 | // 2026-10-11 16:09 UTC is already 12 October in Perth, eight hours east, and still the 11th five west. |
| 573 | let utc = (days_from_civil(2026, 10, 11) * 86_400 + 16 * 3_600 + 9 * 60) * 1_000; |
| 574 | assert_eq!(date_at(utc, 0), (2026, 10, 11)); |
| 575 | assert_eq!(date_at(utc, 8 * 3_600_000), (2026, 10, 12)); |
| 576 | assert_eq!(date_at(utc, -5 * 3_600_000), (2026, 10, 11)); |
| 577 | assert_eq!(date_at(utc, -17 * 3_600_000), (2026, 10, 10)); |
| 578 | // The offset is in hours, so 24 is a whole day on. |
| 579 | assert_eq!(date_at(utc, 24 * 3_600_000), (2026, 10, 12)); |
| 580 | } |
| 581 | } |