oxedyne/fe2o3/fe2o3_datime/src/parser/moment.rs
14.6 KiB, 1 run
created by r1870400018:63087, 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 | //! A moment as a person types it, and as a person reads it back. |
| 2 | //! |
| 3 | //! This is stricter than `Parser`, which swaps a day for a month when the first |
| 4 | //! guess fails. Here the answer picks a point in a history to return to, so a |
| 5 | //! reading is either exactly one instant or an error that says why not. The |
| 6 | //! zone's rules come from `CalClockZone::local_to_utc`, so a wall time in a |
| 7 | //! spring gap is refused and one in an autumn fold takes the earlier instant. |
| 8 | //! |
| 9 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 10 | //! Anthropic Claude |
| 11 | |
| 12 | use crate::{ |
| 13 | calendar::CalendarDate, |
| 14 | time::{ |
| 15 | CalClockZone, |
| 16 | LocalTimeResult, |
| 17 | }, |
| 18 | }; |
| 19 | |
| 20 | use oxedyne_fe2o3_core::prelude::*; |
| 21 | |
| 22 | const MICROS: i64 = 1_000_000; // per second |
| 23 | const DAY: i64 = 86_400; // seconds |
| 24 | |
| 25 | /// The forms `read` accepts, each with its meaning, for a caller to give a |
| 26 | /// person whose words it could not read. The refusal names the words and the |
| 27 | /// reason and leaves this list to the caller, which knows how it is being read. |
| 28 | pub const FORMS: [(&str, &str); 5] = [ |
| 29 | ("HH:MM[:SS]", "a clock time today, or yesterday's if today's has not come yet"), |
| 30 | ("<n>s|m|h|d|w, repeated: 1h30m", "that long ago, a day being 24 hours"), |
| 31 | ("today [HH:MM[:SS]]", "now, or that clock time today"), |
| 32 | ("yesterday [HH:MM[:SS]]", "24 hours ago, or that clock time yesterday"), |
| 33 | ("YYYY-MM-DD HH:MM[:SS[.ffffff]]", "that date and time here, or with a trailing Z or +HH:MM the instant that offset gives"), |
| 34 | ]; |
| 35 | |
| 36 | /// What a person typed, as an instant. |
| 37 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 38 | pub struct Moment { |
| 39 | pub micros: i64, // UTC microseconds since the Unix epoch |
| 40 | pub fold: bool, // the wall time came twice and the earlier was taken |
| 41 | } |
| 42 | |
| 43 | // A clock reading: whole seconds after midnight and the microseconds beyond. |
| 44 | struct Clock { |
| 45 | secs: i64, |
| 46 | micros: i64, |
| 47 | } |
| 48 | |
| 49 | /// The instant `said` names, in UTC microseconds. `now_utc_micros` is a single |
| 50 | /// clock reading taken by the caller, and `zone` is where a wall time is read. |
| 51 | pub fn read( |
| 52 | said: &str, |
| 53 | now_utc_micros: i64, |
| 54 | zone: &CalClockZone, |
| 55 | ) |
| 56 | -> Outcome<i64> |
| 57 | { |
| 58 | Ok(res!(read_noted(said, now_utc_micros, zone)).micros) |
| 59 | } |
| 60 | |
| 61 | /// As `read`, saying also whether the wall time fell in an autumn fold. |
| 62 | pub fn read_noted( |
| 63 | said: &str, |
| 64 | now_utc_micros: i64, |
| 65 | zone: &CalClockZone, |
| 66 | ) |
| 67 | -> Outcome<Moment> |
| 68 | { |
| 69 | let words: Vec<&str> = said.split_ascii_whitespace().collect(); |
| 70 | let is = |w: &str, name: &str| w.eq_ignore_ascii_case(name); |
| 71 | match words.as_slice() { |
| 72 | [] => Err(err!("Nothing was said, so there is no moment to read."; Invalid, Input, Missing)), |
| 73 | [w] if is(w, "today") => Ok(Moment { micros: now_utc_micros, fold: false }), |
| 74 | [w] if is(w, "yesterday") => { |
| 75 | let micros = res!(now_utc_micros.checked_sub(DAY * MICROS).ok_or_else(|| |
| 76 | err!("A day before {} is out of range.", now_utc_micros; Invalid, Input, Range))); |
| 77 | Ok(Moment { micros, fold: false }) |
| 78 | }, |
| 79 | [w, c] if is(w, "today") => { |
| 80 | let clock = res!(clock_of(c)); |
| 81 | let days = res!(today_of(now_utc_micros, zone)); |
| 82 | wall(days, &clock, zone) |
| 83 | }, |
| 84 | [w, c] if is(w, "yesterday") => { |
| 85 | let clock = res!(clock_of(c)); |
| 86 | let days = res!(today_of(now_utc_micros, zone)) - 1; |
| 87 | wall(days, &clock, zone) |
| 88 | }, |
| 89 | [w] => { |
| 90 | if let Some(secs) = res!(offset(w)) { |
| 91 | let back = res!(secs.checked_mul(MICROS).ok_or_else(|| |
| 92 | err!("The offset '{}' is too large.", w; Invalid, Input, Range))); |
| 93 | let micros = res!(now_utc_micros.checked_sub(back).ok_or_else(|| |
| 94 | err!("The offset '{}' reaches before the earliest instant.", w; |
| 95 | Invalid, Input, Range))); |
| 96 | return Ok(Moment { micros, fold: false }); |
| 97 | } |
| 98 | if let Some(clock) = res!(clock(w)) { |
| 99 | // A bare clock time is today's, unless that is still to come. |
| 100 | let days = res!(today_of(now_utc_micros, zone)); |
| 101 | let today = res!(wall(days, &clock, zone)); |
| 102 | if today.micros > now_utc_micros { |
| 103 | return wall(days - 1, &clock, zone); |
| 104 | } |
| 105 | return Ok(today); |
| 106 | } |
| 107 | stamp(&words, zone) |
| 108 | }, |
| 109 | _ => stamp(&words, zone), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// A moment as `read` takes it back: date, time to the second, and the offset |
| 114 | /// in force at that instant. A wall time that came twice is told apart by its |
| 115 | /// offset. |
| 116 | pub fn show(micros: i64, zone: &CalClockZone) -> Outcome<String> { |
| 117 | let secs = micros.div_euclid(MICROS); |
| 118 | let off = res!(zone.offset_millis_at_time(secs.saturating_mul(1000))) as i64 / 1000; |
| 119 | let (date, sod) = res!(split_local(secs + off)); |
| 120 | let sign = if off < 0 { '-' } else { '+' }; |
| 121 | let a = off.abs(); |
| 122 | if a % 60 != 0 { |
| 123 | Ok(fmt!("{} {:02}:{:02}:{:02} {}{:02}:{:02}:{:02}", |
| 124 | date, sod / 3600, sod / 60 % 60, sod % 60, sign, a / 3600, a / 60 % 60, a % 60)) |
| 125 | } else { |
| 126 | Ok(fmt!("{} {:02}:{:02}:{:02} {}{:02}:{:02}", |
| 127 | date, sod / 3600, sod / 60 % 60, sod % 60, sign, a / 3600, a / 60 % 60)) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /// A moment in UTC, ending in Z. |
| 132 | pub fn show_utc(micros: i64) -> Outcome<String> { |
| 133 | let (date, sod) = res!(split_local(micros.div_euclid(MICROS))); |
| 134 | Ok(fmt!("{} {:02}:{:02}:{:02}Z", date, sod / 3600, sod / 60 % 60, sod % 60)) |
| 135 | } |
| 136 | |
| 137 | // The calendar date and the seconds into it of a count of local seconds. |
| 138 | fn split_local(local_secs: i64) -> Outcome<(String, i64)> { |
| 139 | let date = res!(CalendarDate::from_days_since_epoch( |
| 140 | local_secs.div_euclid(DAY), |
| 141 | CalClockZone::utc(), |
| 142 | )); |
| 143 | Ok(( |
| 144 | fmt!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day()), |
| 145 | local_secs.rem_euclid(DAY), |
| 146 | )) |
| 147 | } |
| 148 | |
| 149 | // The local date, as days since the epoch, on which `now` falls. |
| 150 | fn today_of(now: i64, zone: &CalClockZone) -> Outcome<i64> { |
| 151 | match zone.utc_to_local(now.div_euclid(1000)) { |
| 152 | LocalTimeResult::Single(local) => Ok(local.div_euclid(DAY * 1000)), |
| 153 | _ => Err(err!( |
| 154 | "The zone {} has no local time at {} microseconds.", zone.id(), now; |
| 155 | Invalid, Input, Range)), |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // A wall time on a local date, in the zone. |
| 160 | fn wall(days: i64, clock: &Clock, zone: &CalClockZone) -> Outcome<Moment> { |
| 161 | let local_ms = res!(days.checked_mul(DAY).ok_or_else(|| |
| 162 | err!("The day {} is out of range.", days; Invalid, Input, Range))) |
| 163 | .saturating_add(clock.secs).saturating_mul(1000); |
| 164 | match zone.local_to_utc(local_ms) { |
| 165 | LocalTimeResult::Single(utc) => Ok(Moment { |
| 166 | micros: utc * 1000 + clock.micros, |
| 167 | fold: false, |
| 168 | }), |
| 169 | LocalTimeResult::Ambiguous(first, _) => Ok(Moment { |
| 170 | micros: first * 1000 + clock.micros, |
| 171 | fold: true, |
| 172 | }), |
| 173 | LocalTimeResult::None => { |
| 174 | let date = res!(split_local(local_ms.div_euclid(1000))).0; |
| 175 | Err(err!( |
| 176 | "{} {} does not exist in {}{}.", |
| 177 | date, clock_text(clock), zone.id(), gap_note(zone, local_ms); |
| 178 | Invalid, Input, Range)) |
| 179 | }, |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | // What the clocks did, when a wall time falls where they skipped. |
| 184 | fn gap_note(zone: &CalClockZone, local_ms: i64) -> String { |
| 185 | const WINDOW: i64 = 2 * DAY * 1000; |
| 186 | let before = match zone.offset_millis_at_time(local_ms - WINDOW) { |
| 187 | Ok(off) => off as i64, |
| 188 | Err(_) => return String::new(), |
| 189 | }; |
| 190 | let after = match zone.offset_millis_at_time(local_ms + WINDOW) { |
| 191 | Ok(off) => off as i64, |
| 192 | Err(_) => return String::new(), |
| 193 | }; |
| 194 | if before == after { |
| 195 | return String::new(); |
| 196 | } |
| 197 | // The first second under the new offset. |
| 198 | let mut lo = (local_ms - WINDOW).div_euclid(1000); |
| 199 | let mut hi = (local_ms + WINDOW).div_euclid(1000); |
| 200 | while hi - lo > 1 { |
| 201 | let mid = lo + (hi - lo) / 2; |
| 202 | match zone.offset_millis_at_time(mid * 1000) { |
| 203 | Ok(off) if off as i64 == before => lo = mid, |
| 204 | _ => hi = mid, |
| 205 | } |
| 206 | } |
| 207 | let stood = (hi * 1000 + before).div_euclid(1000); |
| 208 | let became = (hi * 1000 + after).div_euclid(1000); |
| 209 | match (split_local(stood), split_local(became)) { |
| 210 | (Ok((_, a)), Ok((_, b))) => fmt!( |
| 211 | ": the clocks there went from {:02}:{:02} to {:02}:{:02}, {} to {}", |
| 212 | a / 3600, a / 60 % 60, b / 3600, b / 60 % 60, offset_text(before), offset_text(after)), |
| 213 | _ => String::new(), |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | fn offset_text(millis: i64) -> String { |
| 218 | let secs = millis / 1000; |
| 219 | let a = secs.abs(); |
| 220 | fmt!("{}{:02}:{:02}", if secs < 0 { '-' } else { '+' }, a / 3600, a / 60 % 60) |
| 221 | } |
| 222 | |
| 223 | fn clock_text(clock: &Clock) -> String { |
| 224 | let (h, m, s) = (clock.secs / 3600, clock.secs / 60 % 60, clock.secs % 60); |
| 225 | if clock.micros != 0 { |
| 226 | fmt!("{:02}:{:02}:{:02}.{:06}", h, m, s, clock.micros) |
| 227 | } else if s != 0 { |
| 228 | fmt!("{:02}:{:02}:{:02}", h, m, s) |
| 229 | } else { |
| 230 | fmt!("{:02}:{:02}", h, m) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // A clock time that must be one, for after today or yesterday. |
| 235 | fn clock_of(word: &str) -> Outcome<Clock> { |
| 236 | match res!(clock(word)) { |
| 237 | Some(clock) => Ok(clock), |
| 238 | None => Err(err!( |
| 239 | "'{}' is not a clock time; HH:MM or HH:MM:SS is read after today or yesterday.", word; |
| 240 | Invalid, Input)), |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | // H:MM or HH:MM, then optionally :SS and a fraction of up to six digits. None |
| 245 | // when the word is not shaped like a clock time, and an error when it is but |
| 246 | // its numbers cannot be. |
| 247 | fn clock(word: &str) -> Outcome<Option<Clock>> { |
| 248 | let colon = match word.find(':') { |
| 249 | Some(c) => c, |
| 250 | None => return Ok(None), |
| 251 | }; |
| 252 | let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); |
| 253 | let hour = &word[..colon]; |
| 254 | if !digits(hour) || hour.len() > 2 { |
| 255 | return Ok(None); |
| 256 | } |
| 257 | let mut rest = word[colon + 1..].splitn(2, ':'); |
| 258 | let minute = rest.next().unwrap_or(""); |
| 259 | if !digits(minute) || minute.len() != 2 { |
| 260 | return Ok(None); |
| 261 | } |
| 262 | let mut micros = 0; |
| 263 | let second = match rest.next() { |
| 264 | None => "00", |
| 265 | Some(tail) => { |
| 266 | let mut parts = tail.splitn(2, '.'); |
| 267 | let s = parts.next().unwrap_or(""); |
| 268 | if let Some(f) = parts.next() { |
| 269 | if !digits(f) || f.len() > 6 { |
| 270 | return Ok(None); |
| 271 | } |
| 272 | micros = res!(f.parse::<i64>().map_err(|e| err!(e, "{}", f; Invalid, Input))) |
| 273 | * 10i64.pow(6 - f.len() as u32); |
| 274 | } |
| 275 | if !digits(s) || s.len() != 2 { |
| 276 | return Ok(None); |
| 277 | } |
| 278 | s |
| 279 | }, |
| 280 | }; |
| 281 | let h: i64 = res!(hour.parse().map_err(|e| err!(e, "{}", word; Invalid, Input))); |
| 282 | let m: i64 = res!(minute.parse().map_err(|e| err!(e, "{}", word; Invalid, Input))); |
| 283 | let s: i64 = res!(second.parse().map_err(|e| err!(e, "{}", word; Invalid, Input))); |
| 284 | if h > 23 { |
| 285 | return Err(err!("The hour in '{}' is {}, which is not between 0 and 23.", word, h; |
| 286 | Invalid, Input, Range)); |
| 287 | } |
| 288 | if m > 59 { |
| 289 | return Err(err!("The minute in '{}' is {}, which is not between 0 and 59.", word, m; |
| 290 | Invalid, Input, Range)); |
| 291 | } |
| 292 | if s > 59 { |
| 293 | return Err(err!("The second in '{}' is {}, which is not between 0 and 59.", word, s; |
| 294 | Invalid, Input, Range)); |
| 295 | } |
| 296 | Ok(Some(Clock { secs: h * 3600 + m * 60 + s, micros })) |
| 297 | } |
| 298 | |
| 299 | // Runs of a number and a unit, 1h30m, as seconds. None when the word is not |
| 300 | // shaped like that, which includes a bare number. |
| 301 | fn offset(word: &str) -> Outcome<Option<i64>> { |
| 302 | let b = word.as_bytes(); |
| 303 | if b.is_empty() || !b[0].is_ascii_digit() { |
| 304 | return Ok(None); |
| 305 | } |
| 306 | let mut total: i64 = 0; |
| 307 | let mut i = 0; |
| 308 | while i < b.len() { |
| 309 | let from = i; |
| 310 | let mut n: i64 = 0; |
| 311 | while i < b.len() && b[i].is_ascii_digit() { |
| 312 | n = res!(n.checked_mul(10).and_then(|n| n.checked_add((b[i] - b'0') as i64)) |
| 313 | .ok_or_else(|| err!("The offset '{}' is too large.", word; Invalid, Input, Range))); |
| 314 | i += 1; |
| 315 | } |
| 316 | if i == from || i >= b.len() { |
| 317 | return Ok(None); |
| 318 | } |
| 319 | let unit = match b[i] { |
| 320 | b's' => 1, |
| 321 | b'm' => 60, |
| 322 | b'h' => 3600, |
| 323 | b'd' => DAY, |
| 324 | b'w' => 7 * DAY, |
| 325 | _ => return Ok(None), |
| 326 | }; |
| 327 | i += 1; |
| 328 | total = res!(n.checked_mul(unit).and_then(|n| total.checked_add(n)) |
| 329 | .ok_or_else(|| err!("The offset '{}' is too large.", word; Invalid, Input, Range))); |
| 330 | } |
| 331 | Ok(Some(total)) |
| 332 | } |
| 333 | |
| 334 | // A date and a time, joined by a space or T, with an optional Z or +HH:MM |
| 335 | // attached to the time or standing as a word of its own. |
| 336 | fn stamp(words: &[&str], zone: &CalClockZone) -> Outcome<Moment> { |
| 337 | let said = words.join(" "); |
| 338 | let bad = || err!("'{}' is not a time that can be read.", said; Invalid, Input); |
| 339 | let splits_at_t = |w: &str| w.len() > 11 && matches!(w.as_bytes()[10], b'T' | b't'); |
| 340 | let (date, time, word_zone) = match words { |
| 341 | [a] if splits_at_t(a) => (&a[..10], &a[11..], None), |
| 342 | [a, z] if splits_at_t(a) => (&a[..10], &a[11..], Some(*z)), |
| 343 | [a, t] => (*a, *t, None), |
| 344 | [a, t, z] => (*a, *t, Some(*z)), |
| 345 | _ => return Err(bad()), |
| 346 | }; |
| 347 | let days = match res!(date_of(date)) { |
| 348 | Some(days) => days, |
| 349 | None => return Err(bad()), |
| 350 | }; |
| 351 | // A zone attached to the time, unless one was also given as a word. |
| 352 | let (time, attached) = split_zone(time); |
| 353 | let given = match (attached, word_zone) { |
| 354 | (Some(_), Some(_)) => return Err(err!( |
| 355 | "'{}' gives its offset twice.", said; Invalid, Input)), |
| 356 | (Some(z), None) => Some(z), |
| 357 | (None, Some(z)) => Some(z), |
| 358 | (None, None) => None, |
| 359 | }; |
| 360 | let clock = match res!(clock(time)) { |
| 361 | Some(c) => c, |
| 362 | None => return Err(bad()), |
| 363 | }; |
| 364 | match given { |
| 365 | None => wall(days, &clock, zone), |
| 366 | Some(z) => { |
| 367 | let east = match res!(zone_offset(z)) { |
| 368 | Some(east) => east, |
| 369 | None => return Err(bad()), |
| 370 | }; |
| 371 | let secs = days * DAY + clock.secs - east; |
| 372 | Ok(Moment { micros: secs * MICROS + clock.micros, fold: false }) |
| 373 | }, |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | // A time and the zone text on its end, if any: ...30Z, ...30+08:00. |
| 378 | fn split_zone(time: &str) -> (&str, Option<&str>) { |
| 379 | if let Some(t) = time.strip_suffix('Z').or_else(|| time.strip_suffix('z')) { |
| 380 | return (t, Some("Z")); |
| 381 | } |
| 382 | match time.rfind(|c| c == '+' || c == '-') { |
| 383 | Some(at) if at > 0 => (&time[..at], Some(&time[at..])), |
| 384 | _ => (time, None), |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // Seconds east of UTC for Z, +HH:MM or +HHMM; None for anything else. |
| 389 | fn zone_offset(text: &str) -> Outcome<Option<i64>> { |
| 390 | if text == "Z" || text == "z" { |
| 391 | return Ok(Some(0)); |
| 392 | } |
| 393 | let (sign, rest) = match text.as_bytes().first() { |
| 394 | Some(b'+') => (1, &text[1..]), |
| 395 | Some(b'-') => (-1, &text[1..]), |
| 396 | _ => return Ok(None), |
| 397 | }; |
| 398 | let (h, m) = match rest.len() { |
| 399 | 5 if rest.as_bytes()[2] == b':' => (&rest[..2], &rest[3..]), |
| 400 | 4 => (&rest[..2], &rest[2..]), |
| 401 | _ => return Ok(None), |
| 402 | }; |
| 403 | if !h.bytes().all(|b| b.is_ascii_digit()) || !m.bytes().all(|b| b.is_ascii_digit()) { |
| 404 | return Ok(None); |
| 405 | } |
| 406 | let h: i64 = res!(h.parse().map_err(|e| err!(e, "{}", text; Invalid, Input))); |
| 407 | let m: i64 = res!(m.parse().map_err(|e| err!(e, "{}", text; Invalid, Input))); |
| 408 | if h > 23 || m > 59 { |
| 409 | return Err(err!( |
| 410 | "The offset '{}' is more than 23:59 from UTC.", text; Invalid, Input, Range)); |
| 411 | } |
| 412 | Ok(Some(sign * (h * 3600 + m * 60))) |
| 413 | } |
| 414 | |
| 415 | // YYYY-MM-DD as days since the epoch. None when the word is not shaped like a |
| 416 | // date, and an error when it is but there was no such day. |
| 417 | fn date_of(word: &str) -> Outcome<Option<i64>> { |
| 418 | let b = word.as_bytes(); |
| 419 | if b.len() != 10 || b[4] != b'-' || b[7] != b'-' { |
| 420 | return Ok(None); |
| 421 | } |
| 422 | let part = |from: usize, to: usize| -> Option<i32> { |
| 423 | let s = &word[from..to]; |
| 424 | if s.bytes().all(|c| c.is_ascii_digit()) { s.parse().ok() } else { None } |
| 425 | }; |
| 426 | let (y, m, d) = match (part(0, 4), part(5, 7), part(8, 10)) { |
| 427 | (Some(y), Some(m), Some(d)) => (y, m, d), |
| 428 | _ => return Ok(None), |
| 429 | }; |
| 430 | if y < 1 { |
| 431 | return Err(err!("The year in '{}' is before 0001.", word; Invalid, Input, Range)); |
| 432 | } |
| 433 | let date = res!(CalendarDate::new(y, m as u8, d as u8, CalClockZone::utc()).map_err(|e| |
| 434 | err!(e, "'{}' is not a date.", word; Invalid, Input, Range))); |
| 435 | Ok(Some(res!(date.days_since_epoch()))) |
| 436 | } |