1pub const TIMER_UNITS: [TimerUnit; 4] = [
14 TimerUnit::Days,
15 TimerUnit::Hours,
16 TimerUnit::Minutes,
17 TimerUnit::Seconds,
18];
19
20pub const TIMER_PLACEHOLDER: &str = "--:--";
22
23pub const TIMER_DEFAULT_COMPLETE_LABEL: &str = "Timer complete";
25
26const MAX_EPOCH_MS: i64 = 8_640_000_000_000_000;
28const MAX_EPOCH_MS_FLOAT: f64 = 8.64e15;
29const MAX_INSTANT_LENGTH: usize = 40;
30const MAX_EPOCH_DIGITS: usize = 16;
31const MAX_FRACTION_DIGITS: usize = 9;
32const MAX_UNIT_LIST_LENGTH: usize = 200;
34const MS_PER_DAY: i64 = 86_400_000;
35
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum TimerMode {
40 #[default]
42 Countdown,
43 Elapsed,
45}
46
47impl TimerMode {
48 pub const fn as_str(self) -> &'static str {
50 match self {
51 Self::Countdown => "countdown",
52 Self::Elapsed => "elapsed",
53 }
54 }
55}
56
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
59#[non_exhaustive]
60pub enum TimerFormat {
61 #[default]
63 Clock,
64 Units,
66}
67
68impl TimerFormat {
69 pub const fn as_str(self) -> &'static str {
71 match self {
72 Self::Clock => "clock",
73 Self::Units => "units",
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
80#[non_exhaustive]
81pub enum TimerAnnounce {
82 #[default]
84 Off,
85 Minute,
87 Complete,
89}
90
91impl TimerAnnounce {
92 pub const fn as_str(self) -> &'static str {
94 match self {
95 Self::Off => "off",
96 Self::Minute => "minute",
97 Self::Complete => "complete",
98 }
99 }
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
104#[non_exhaustive]
105pub enum TimerState {
106 Running,
108 Complete,
110 Invalid,
112}
113
114impl TimerState {
115 pub const fn as_str(self) -> &'static str {
117 match self {
118 Self::Running => "running",
119 Self::Complete => "complete",
120 Self::Invalid => "invalid",
121 }
122 }
123}
124
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127#[non_exhaustive]
128pub enum TimerUnit {
129 Days,
131 Hours,
133 Minutes,
135 Seconds,
137}
138
139impl TimerUnit {
140 pub const fn as_str(self) -> &'static str {
142 match self {
143 Self::Days => "days",
144 Self::Hours => "hours",
145 Self::Minutes => "minutes",
146 Self::Seconds => "seconds",
147 }
148 }
149
150 fn from_name(name: &str) -> Option<Self> {
151 TIMER_UNITS.into_iter().find(|unit| unit.as_str() == name)
152 }
153
154 const fn seconds(self) -> u64 {
155 match self {
156 Self::Days => 86_400,
157 Self::Hours => 3600,
158 Self::Minutes => 60,
159 Self::Seconds => 1,
160 }
161 }
162
163 const fn iso_designator(self) -> char {
164 match self {
165 Self::Days => 'D',
166 Self::Hours => 'H',
167 Self::Minutes => 'M',
168 Self::Seconds => 'S',
169 }
170 }
171
172 const fn narrow_suffix(self) -> &'static str {
174 match self {
175 Self::Days => "d",
176 Self::Hours => "h",
177 Self::Minutes => "m",
178 Self::Seconds => "s",
179 }
180 }
181
182 const fn long_name(self, plural: bool) -> &'static str {
184 match (self, plural) {
185 (Self::Days, false) => "day",
186 (Self::Days, true) => "days",
187 (Self::Hours, false) => "hour",
188 (Self::Hours, true) => "hours",
189 (Self::Minutes, false) => "minute",
190 (Self::Minutes, true) => "minutes",
191 (Self::Seconds, false) => "second",
192 (Self::Seconds, true) => "seconds",
193 }
194 }
195}
196
197#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
199pub struct TimerParts {
200 pub days: u64,
202 pub hours: u64,
204 pub minutes: u64,
206 pub seconds: u64,
208}
209
210impl TimerParts {
211 const fn value(&self, unit: TimerUnit) -> u64 {
212 match unit {
213 TimerUnit::Days => self.days,
214 TimerUnit::Hours => self.hours,
215 TimerUnit::Minutes => self.minutes,
216 TimerUnit::Seconds => self.seconds,
217 }
218 }
219
220 const fn set(&mut self, unit: TimerUnit, value: u64) {
221 match unit {
222 TimerUnit::Days => self.days = value,
223 TimerUnit::Hours => self.hours = value,
224 TimerUnit::Minutes => self.minutes = value,
225 TimerUnit::Seconds => self.seconds = value,
226 }
227 }
228}
229
230#[derive(Clone, Debug, PartialEq, Eq)]
232pub struct TimerConfig {
233 pub announce: TimerAnnounce,
235 pub complete_label: String,
237 pub format: TimerFormat,
239 pub instant: Option<i64>,
241 pub mode: TimerMode,
243 pub units: Vec<TimerUnit>,
245}
246
247impl Default for TimerConfig {
248 fn default() -> Self {
249 resolve_timer_config(
250 TimerMode::default(),
251 TimerFormat::default(),
252 TimerAnnounce::default(),
253 None,
254 None,
255 &[],
256 )
257 }
258}
259
260#[derive(Clone, Debug, PartialEq, Eq)]
262pub struct TimerSnapshot {
263 pub date_time: Option<String>,
265 pub minute: u64,
267 pub seconds: u64,
269 pub spoken_minute: String,
271 pub state: TimerState,
273 pub text: String,
275}
276
277fn is_js_whitespace(character: char) -> bool {
280 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
281}
282
283fn trim_js(value: &str) -> &str {
284 value.trim_matches(is_js_whitespace)
285}
286
287fn within_epoch_range(time: i64) -> bool {
288 (-MAX_EPOCH_MS..=MAX_EPOCH_MS).contains(&time)
289}
290
291fn parse_epoch(bytes: &[u8]) -> Option<i64> {
293 let (negative, digits) = bytes
294 .strip_prefix(b"-")
295 .map_or((false, bytes), |rest| (true, rest));
296
297 if digits.is_empty()
298 || digits.len() > MAX_EPOCH_DIGITS
299 || !digits.iter().all(u8::is_ascii_digit)
300 {
301 return None;
302 }
303
304 let magnitude = digits
305 .iter()
306 .fold(0_i64, |total, digit| total * 10 + i64::from(digit - b'0'));
307
308 Some(if negative { -magnitude } else { magnitude })
309}
310
311struct IsoScanner<'a> {
314 bytes: &'a [u8],
315 position: usize,
316}
317
318impl IsoScanner<'_> {
319 fn eat(&mut self, expected: u8) -> bool {
320 if self.bytes.get(self.position) == Some(&expected) {
321 self.position += 1;
322
323 true
324 } else {
325 false
326 }
327 }
328
329 fn number(&mut self, width: usize) -> Option<i64> {
331 let digits = self.bytes.get(self.position..self.position + width)?;
332
333 if !digits.iter().all(u8::is_ascii_digit) {
334 return None;
335 }
336
337 self.position += width;
338
339 Some(
340 digits
341 .iter()
342 .fold(0, |total, digit| total * 10 + i64::from(digit - b'0')),
343 )
344 }
345
346 fn fraction(&mut self) -> Option<(i64, bool)> {
349 let mut count = 0;
350 let mut millis = 0;
351 let mut nonzero = false;
352
353 while let Some(&byte) = self.bytes.get(self.position)
354 && byte.is_ascii_digit()
355 {
356 if count == MAX_FRACTION_DIGITS {
357 return None;
358 }
359
360 let digit = i64::from(byte - b'0');
361
362 if count < 3 {
363 millis = millis * 10 + digit;
364 }
365
366 nonzero |= digit != 0;
367 count += 1;
368 self.position += 1;
369 }
370
371 if count == 0 {
372 return None;
373 }
374
375 for _ in count..3 {
376 millis *= 10;
377 }
378
379 Some((millis, nonzero))
380 }
381
382 fn done(&self) -> bool {
383 self.position == self.bytes.len()
384 }
385}
386
387const fn is_leap_year(year: i64) -> bool {
388 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
389}
390
391const fn days_in_month(year: i64, month: i64) -> i64 {
392 match month {
393 2 if is_leap_year(year) => 29,
394 2 => 28,
395 4 | 6 | 9 | 11 => 30,
396 _ => 31,
397 }
398}
399
400const fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
402 let year = if month <= 2 { year - 1 } else { year };
403 let era = year.div_euclid(400);
404 let year_of_era = year - era * 400;
405 let month_from_march = (month + 9) % 12;
406 let day_of_year = (153 * month_from_march + 2) / 5 + day - 1;
407 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
408
409 era * 146_097 + day_of_era - 719_468
410}
411
412fn parse_iso_instant(bytes: &[u8]) -> Option<i64> {
414 let mut scanner = IsoScanner { bytes, position: 0 };
415 let year = scanner.number(4)?;
416
417 if !scanner.eat(b'-') {
418 return None;
419 }
420
421 let month = scanner.number(2)?;
422
423 if !scanner.eat(b'-') {
424 return None;
425 }
426
427 let day = scanner.number(2)?;
428
429 if !(1..=12).contains(&month) || !(1..=days_in_month(year, month)).contains(&day) {
431 return None;
432 }
433
434 let midnight = days_from_civil(year, month, day) * MS_PER_DAY;
435
436 if scanner.done() {
437 return Some(midnight);
438 }
439
440 if !scanner.eat(b'T') {
441 return None;
442 }
443
444 let hour = scanner.number(2)?;
445
446 if !scanner.eat(b':') {
447 return None;
448 }
449
450 let minute = scanner.number(2)?;
451 let mut second = 0;
452 let mut millis = 0;
453 let mut fraction_nonzero = false;
454
455 if scanner.eat(b':') {
456 second = scanner.number(2)?;
457
458 if scanner.eat(b'.') {
459 (millis, fraction_nonzero) = scanner.fraction()?;
460 }
461 }
462
463 let offset_minutes = if scanner.eat(b'Z') {
464 0
465 } else {
466 let sign = if scanner.eat(b'+') {
467 1
468 } else if scanner.eat(b'-') {
469 -1
470 } else {
471 return None;
472 };
473
474 let hours = scanner.number(2)?;
475
476 if !scanner.eat(b':') {
477 return None;
478 }
479
480 let minutes = scanner.number(2)?;
481
482 if hours > 23 || minutes > 59 {
483 return None;
484 }
485
486 sign * (hours * 60 + minutes)
487 };
488
489 if !scanner.done() || minute > 59 || second > 59 {
490 return None;
491 }
492
493 if hour > 24 || (hour == 24 && (minute > 0 || second > 0 || fraction_nonzero)) {
495 return None;
496 }
497
498 let time = ((hour * 60 + minute) * 60 + second) * 1000 + millis;
499
500 Some(midnight + time - offset_minutes * 60_000)
501}
502
503pub fn parse_timer_instant(value: &str) -> Option<i64> {
511 let text = trim_js(value);
512
513 if text.is_empty() || text.len() > MAX_INSTANT_LENGTH {
515 return None;
516 }
517
518 let bytes = text.as_bytes();
519 let time = parse_epoch(bytes).or_else(|| parse_iso_instant(bytes))?;
520
521 within_epoch_range(time).then_some(time)
522}
523
524pub fn timer_instant_from_millis(value: f64) -> Option<i64> {
529 if !value.is_finite() || value.abs() > MAX_EPOCH_MS_FLOAT {
530 return None;
531 }
532
533 parse_epoch(format!("{:.0}", value.trunc()).as_bytes())
535}
536
537fn units_from_flags(mode: TimerMode, requested: [bool; 4]) -> Vec<TimerUnit> {
538 let units: Vec<TimerUnit> = TIMER_UNITS
539 .into_iter()
540 .zip(requested)
541 .filter_map(|(unit, wanted)| wanted.then_some(unit))
542 .collect();
543
544 if !units.is_empty() {
545 return units;
546 }
547
548 match mode {
549 TimerMode::Countdown => TIMER_UNITS.to_vec(),
550 TimerMode::Elapsed => vec![TimerUnit::Hours, TimerUnit::Minutes, TimerUnit::Seconds],
551 }
552}
553
554fn unit_flag(requested: &mut [bool; 4], unit: TimerUnit) {
555 if let Some(index) = TIMER_UNITS.iter().position(|candidate| *candidate == unit) {
556 requested[index] = true;
557 }
558}
559
560pub fn resolve_timer_units(mode: TimerMode, units: &[TimerUnit]) -> Vec<TimerUnit> {
565 let mut requested = [false; 4];
566
567 for unit in units {
568 unit_flag(&mut requested, *unit);
569 }
570
571 units_from_flags(mode, requested)
572}
573
574pub fn resolve_timer_units_list(mode: TimerMode, value: &str) -> Vec<TimerUnit> {
579 let mut requested = [false; 4];
580 let mut item = String::new();
581 let mut budget = MAX_UNIT_LIST_LENGTH;
582
583 let mut flush = |item: &mut String| {
584 if let Some(unit) = TimerUnit::from_name(item) {
585 unit_flag(&mut requested, unit);
586 }
587
588 item.clear();
589 };
590
591 for character in value.chars() {
593 let width = character.len_utf16();
594
595 if width > budget {
596 if budget > 0 {
598 item.push(character);
599 }
600
601 break;
602 }
603
604 budget -= width;
605
606 if character == ',' || is_js_whitespace(character) {
607 flush(&mut item);
608 } else {
609 item.push(character);
610 }
611 }
612
613 flush(&mut item);
614
615 units_from_flags(mode, requested)
616}
617
618pub fn timer_seconds(mode: TimerMode, instant: i64, now: i64) -> u64 {
624 let difference = match mode {
625 TimerMode::Countdown => i128::from(instant) - i128::from(now),
626 TimerMode::Elapsed => i128::from(now) - i128::from(instant),
627 };
628
629 let Ok(difference) = u128::try_from(difference) else {
630 return 0;
631 };
632
633 let seconds = match mode {
634 TimerMode::Countdown => difference.div_ceil(1000),
635 TimerMode::Elapsed => difference / 1000,
636 };
637
638 u64::try_from(seconds).unwrap_or(u64::MAX)
639}
640
641pub fn timer_tick_delay(instant: i64, now: i64) -> u64 {
646 let remainder = (i128::from(now) - i128::from(instant)).rem_euclid(1000);
647
648 u64::try_from(1000 - remainder).unwrap_or(1000)
649}
650
651pub fn split_timer_duration(total_seconds: u64, units: &[TimerUnit]) -> TimerParts {
656 let mut parts = TimerParts::default();
657 let mut remaining = total_seconds;
658
659 for unit in TIMER_UNITS {
660 if !units.contains(&unit) {
661 continue;
662 }
663
664 let amount = remaining / unit.seconds();
665
666 parts.set(unit, amount);
667 remaining -= amount * unit.seconds();
668 }
669
670 parts
671}
672
673pub fn format_timer_iso_duration(parts: TimerParts) -> String {
675 let mut time = String::new();
676
677 for unit in [TimerUnit::Hours, TimerUnit::Minutes, TimerUnit::Seconds] {
678 let value = parts.value(unit);
679
680 if value > 0 {
681 time.push_str(&value.to_string());
682 time.push(unit.iso_designator());
683 }
684 }
685
686 if parts.days == 0 && time.is_empty() {
687 return String::from("PT0S");
688 }
689
690 let mut duration = String::from("P");
691
692 if parts.days > 0 {
693 duration.push_str(&parts.days.to_string());
694 duration.push(TimerUnit::Days.iso_designator());
695 }
696
697 if !time.is_empty() {
698 duration.push('T');
699 duration.push_str(&time);
700 }
701
702 duration
703}
704
705fn group_digits(value: u64) -> String {
707 let digits = value.to_string();
708 let mut grouped = String::with_capacity(digits.len() + digits.len() / 3);
709
710 for (index, digit) in digits.chars().enumerate() {
711 if index > 0 && (digits.len() - index).is_multiple_of(3) {
712 grouped.push(',');
713 }
714
715 grouped.push(digit);
716 }
717
718 grouped
719}
720
721fn trim_leading<'a>(parts: &TimerParts, units: &'a [TimerUnit]) -> &'a [TimerUnit] {
723 match units.iter().position(|unit| parts.value(*unit) > 0) {
724 Some(first) => &units[first..],
725 None => &units[units.len().saturating_sub(1)..],
726 }
727}
728
729fn format_clock(parts: &TimerParts, units: &[TimerUnit]) -> String {
731 let shown = match units {
732 [TimerUnit::Days, rest @ ..] if !rest.is_empty() && parts.days == 0 => rest,
733 _ => units,
734 };
735
736 shown
737 .iter()
738 .map(|unit| format!("{:02}", parts.value(*unit)))
739 .collect::<Vec<_>>()
740 .join(":")
741}
742
743fn format_units(parts: &TimerParts, units: &[TimerUnit]) -> String {
745 trim_leading(parts, units)
746 .iter()
747 .map(|unit| {
748 format!(
749 "{}{}",
750 group_digits(parts.value(*unit)),
751 unit.narrow_suffix()
752 )
753 })
754 .collect::<Vec<_>>()
755 .join(" ")
756}
757
758fn format_spoken(parts: &TimerParts, units: &[TimerUnit]) -> String {
760 trim_leading(parts, units)
761 .iter()
762 .map(|unit| {
763 let value = parts.value(*unit);
764
765 format!("{} {}", group_digits(value), unit.long_name(value != 1))
766 })
767 .collect::<Vec<_>>()
768 .join(", ")
769}
770
771pub fn resolve_timer_config(
777 mode: TimerMode,
778 format: TimerFormat,
779 announce: TimerAnnounce,
780 complete_label: Option<&str>,
781 instant: Option<i64>,
782 units: &[TimerUnit],
783) -> TimerConfig {
784 let label = complete_label.map_or("", trim_js);
785
786 TimerConfig {
787 announce,
788 complete_label: if label.is_empty() {
789 TIMER_DEFAULT_COMPLETE_LABEL
790 } else {
791 label
792 }
793 .to_owned(),
794 format,
795 instant: instant.filter(|time| within_epoch_range(*time)),
796 mode,
797 units: resolve_timer_units(mode, units),
798 }
799}
800
801pub fn timer_snapshot(config: &TimerConfig, now: i64) -> TimerSnapshot {
803 let Some(instant) = config.instant else {
804 return TimerSnapshot {
805 date_time: None,
806 minute: 0,
807 seconds: 0,
808 spoken_minute: TIMER_PLACEHOLDER.to_owned(),
809 state: TimerState::Invalid,
810 text: TIMER_PLACEHOLDER.to_owned(),
811 };
812 };
813
814 let seconds = timer_seconds(config.mode, instant, now);
815 let parts = split_timer_duration(seconds, &config.units);
816
817 let minute = match config.mode {
818 TimerMode::Countdown => seconds.div_ceil(60),
819 TimerMode::Elapsed => seconds / 60,
820 };
821
822 let minute_units: Vec<TimerUnit> = config
823 .units
824 .iter()
825 .copied()
826 .filter(|unit| *unit != TimerUnit::Seconds)
827 .collect();
828
829 let (spoken_units, spoken_seconds) = if minute_units.is_empty() {
830 (config.units.as_slice(), seconds)
831 } else {
832 (minute_units.as_slice(), minute.saturating_mul(60))
833 };
834
835 let state = if config.mode == TimerMode::Countdown && seconds == 0 {
836 TimerState::Complete
837 } else {
838 TimerState::Running
839 };
840
841 let text = match config.format {
842 TimerFormat::Units => format_units(&parts, &config.units),
843 TimerFormat::Clock => format_clock(&parts, &config.units),
844 };
845
846 TimerSnapshot {
847 date_time: Some(format_timer_iso_duration(parts)),
848 minute,
849 seconds,
850 spoken_minute: format_spoken(
851 &split_timer_duration(spoken_seconds, spoken_units),
852 spoken_units,
853 ),
854 state,
855 text,
856 }
857}
858
859pub fn is_timer_completion(previous: Option<&TimerSnapshot>, next: &TimerSnapshot) -> bool {
861 previous.is_some_and(|previous| previous.state == TimerState::Running)
862 && next.state == TimerState::Complete
863}
864
865pub fn timer_announcement(
871 config: &TimerConfig,
872 previous: Option<&TimerSnapshot>,
873 next: &TimerSnapshot,
874) -> Option<String> {
875 if config.announce == TimerAnnounce::Off {
876 return None;
877 }
878
879 let previous = previous?;
880
881 if is_timer_completion(Some(previous), next) {
882 return Some(config.complete_label.clone());
883 }
884
885 let minute_changed = config.announce == TimerAnnounce::Minute
886 && next.state == TimerState::Running
887 && previous.state == TimerState::Running
888 && next.minute != previous.minute;
889
890 minute_changed.then(|| next.spoken_minute.clone())
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896
897 const START: i64 = 1_767_268_800_000;
899
900 const ALL: &[TimerUnit] = &TIMER_UNITS;
901 const HMS: &[TimerUnit] = &[TimerUnit::Hours, TimerUnit::Minutes, TimerUnit::Seconds];
902
903 fn parts(days: u64, hours: u64, minutes: u64, seconds: u64) -> TimerParts {
904 TimerParts {
905 days,
906 hours,
907 minutes,
908 seconds,
909 }
910 }
911
912 fn countdown(instant: i64) -> TimerConfig {
913 resolve_timer_config(
914 TimerMode::Countdown,
915 TimerFormat::Clock,
916 TimerAnnounce::Off,
917 None,
918 Some(instant),
919 &[],
920 )
921 }
922
923 #[test]
924 fn parses_epoch_milliseconds_and_offset_iso_date_times() {
925 assert_eq!(timer_instant_from_millis(1_767_268_800_000.0), Some(START));
926 assert_eq!(parse_timer_instant("1767268800000"), Some(START));
927 assert_eq!(parse_timer_instant(" -1000 "), Some(-1000));
928 assert_eq!(parse_timer_instant("2026-01-01T12:00:00Z"), Some(START));
929 assert_eq!(
930 parse_timer_instant("2026-01-01T07:00:00-05:00"),
931 Some(START)
932 );
933 assert_eq!(parse_timer_instant("2026-01-01T12:00Z"), Some(START));
934 assert_eq!(
935 parse_timer_instant("2026-01-01T12:00:00.250Z"),
936 Some(START + 250)
937 );
938 assert_eq!(parse_timer_instant("2026-01-01"), Some(1_767_225_600_000));
939 }
940
941 #[test]
942 fn rejects_invalid_ambiguous_and_out_of_range_input() {
943 let long = format!("2026-01-01T12:00:00{}Z", "0".repeat(10_000));
944
945 for value in [
946 "",
947 " ",
948 "soon",
949 "March 7 2026",
950 "2026-13-45T99:99:99Z",
951 "2026-01-01T12:00:00",
952 "99999999999999999",
953 long.as_str(),
954 ] {
955 assert_eq!(parse_timer_instant(value), None, "{value:?}");
956 }
957
958 assert_eq!(timer_instant_from_millis(f64::NAN), None);
959 assert_eq!(timer_instant_from_millis(f64::INFINITY), None);
960 assert_eq!(timer_instant_from_millis(f64::NEG_INFINITY), None);
961 assert_eq!(timer_instant_from_millis(8.64e15 + 1.0), None);
962 assert_eq!(timer_instant_from_millis(-8.64e15 - 1.0), None);
963 }
964
965 #[test]
966 fn numeric_instants_truncate_toward_zero_within_the_date_range() {
967 assert_eq!(timer_instant_from_millis(1000.7), Some(1000));
968 assert_eq!(timer_instant_from_millis(-1000.7), Some(-1000));
969 assert_eq!(timer_instant_from_millis(-0.0), Some(0));
970 assert_eq!(timer_instant_from_millis(8.64e15), Some(MAX_EPOCH_MS));
971 assert_eq!(timer_instant_from_millis(-8.64e15), Some(-MAX_EPOCH_MS));
972 }
973
974 #[test]
975 fn epoch_text_follows_the_sixteen_digit_pattern_and_date_range() {
976 assert_eq!(parse_timer_instant("8640000000000000"), Some(MAX_EPOCH_MS));
977 assert_eq!(
978 parse_timer_instant("-8640000000000000"),
979 Some(-MAX_EPOCH_MS)
980 );
981 assert_eq!(parse_timer_instant("8640000000000001"), None);
982 assert_eq!(parse_timer_instant("9999999999999999"), None);
983 assert_eq!(
984 parse_timer_instant("1234567890123456"),
985 Some(1_234_567_890_123_456)
986 );
987 assert_eq!(parse_timer_instant("-0"), Some(0));
988 assert_eq!(parse_timer_instant("0001"), Some(1));
989 assert_eq!(parse_timer_instant("2026"), Some(2026));
991
992 for value in ["-", "--1", "+1", "1e3", "1.5", "1 000", "0x10"] {
993 assert_eq!(parse_timer_instant(value), None, "{value:?}");
994 }
995 }
996
997 #[test]
998 fn iso_dates_validate_the_calendar() {
999 assert_eq!(parse_timer_instant("2024-02-29"), Some(1_709_164_800_000));
1000 assert_eq!(parse_timer_instant("2000-02-29"), Some(951_782_400_000));
1001 assert_eq!(parse_timer_instant("0000-02-29"), Some(-62_162_121_600_000));
1002 assert_eq!(parse_timer_instant("0000-01-01"), Some(-62_167_219_200_000));
1003 assert_eq!(parse_timer_instant("1970-01-01"), Some(0));
1004 assert_eq!(parse_timer_instant("1969-12-31T23:59:59.999Z"), Some(-1));
1005 assert_eq!(
1006 parse_timer_instant("9999-12-31T23:59:59.999Z"),
1007 Some(253_402_300_799_999)
1008 );
1009
1010 for value in [
1012 "2023-02-29",
1013 "1900-02-29",
1014 "2024-02-30",
1015 "2026-04-31",
1016 "2026-02-31",
1017 ] {
1018 assert_eq!(parse_timer_instant(value), None, "{value:?}");
1019 }
1020
1021 for value in [
1022 "2026-00-01",
1023 "2026-13-01",
1024 "2026-01-00",
1025 "2026-01-32",
1026 "2026-1-01",
1027 "2026-01-1",
1028 "+2026-01-01",
1029 "2026-0101",
1030 "2026/01/01",
1031 ] {
1032 assert_eq!(parse_timer_instant(value), None, "{value:?}");
1033 }
1034 }
1035
1036 #[test]
1037 fn iso_times_validate_ranges_like_v8() {
1038 let next_midnight = Some(1_767_312_000_000);
1039
1040 assert_eq!(parse_timer_instant("2026-01-01T24:00Z"), next_midnight);
1041 assert_eq!(parse_timer_instant("2026-01-01T24:00:00Z"), next_midnight);
1042 assert_eq!(
1043 parse_timer_instant("2026-01-01T24:00:00.000Z"),
1044 next_midnight
1045 );
1046 assert_eq!(
1047 parse_timer_instant("2026-01-01T24:00:00.000000000Z"),
1048 next_midnight
1049 );
1050 assert_eq!(
1051 parse_timer_instant("2026-12-31T24:00Z"),
1052 Some(1_798_761_600_000)
1053 );
1054
1055 for value in [
1056 "2026-01-01T24:00:01Z",
1057 "2026-01-01T24:01Z",
1058 "2026-01-01T24:00:00.001Z",
1059 "2026-01-01T24:00:00.0001Z",
1060 "2026-01-01T25:00Z",
1061 "2026-01-01T23:60Z",
1062 "2026-01-01T23:59:60Z",
1063 "2026-01-01T12:00+24:00",
1064 "2026-01-01T12:00+23:60",
1065 "2026-01-01T12:00+99:00",
1066 ] {
1067 assert_eq!(parse_timer_instant(value), None, "{value:?}");
1068 }
1069 }
1070
1071 #[test]
1072 fn iso_offsets_and_fractions_match_date_parse() {
1073 assert_eq!(
1074 parse_timer_instant("2026-01-01T12:00+05:30"),
1075 Some(1_767_249_000_000)
1076 );
1077 assert_eq!(parse_timer_instant("2026-01-01T12:00-00:00"), Some(START));
1078 assert_eq!(parse_timer_instant("2026-01-01T12:00+00:00"), Some(START));
1079 assert_eq!(
1080 parse_timer_instant("2026-01-01T12:00+23:59"),
1081 Some(1_767_182_460_000)
1082 );
1083 assert_eq!(
1084 parse_timer_instant("2026-01-01T12:00:00.1Z"),
1085 Some(START + 100)
1086 );
1087 assert_eq!(
1088 parse_timer_instant("2026-01-01T12:00:00.12Z"),
1089 Some(START + 120)
1090 );
1091 assert_eq!(
1092 parse_timer_instant("2026-01-01T12:00:00.001Z"),
1093 Some(START + 1)
1094 );
1095 assert_eq!(
1096 parse_timer_instant("2026-01-01T12:00:00.9999Z"),
1097 Some(START + 999)
1098 );
1099 assert_eq!(
1100 parse_timer_instant("2026-01-01T12:00:00.123456789Z"),
1101 Some(START + 123)
1102 );
1103 assert_eq!(
1104 parse_timer_instant("2026-01-01T00:00:00.5-00:00"),
1105 Some(1_767_225_600_500)
1106 );
1107
1108 for value in [
1109 "2026-01-01T12:00:00.1234567890Z",
1110 "2026-01-01T12:00:00.Z",
1111 "2026-01-01T12:00.5Z",
1112 "2026-01-01T12:00",
1113 "2026-01-01T12Z",
1114 "2026-01-01T12:00:00+0530",
1115 "2026-01-01T12:00:00+05",
1116 "2026-01-01 12:00Z",
1117 "2026-01-01t12:00Z",
1118 "2026-01-01T12:00z",
1119 "2026-01-01T12:00:00ZZ",
1120 "\u{ff12}\u{ff10}\u{ff12}\u{ff16}-01-01",
1121 ] {
1122 assert_eq!(parse_timer_instant(value), None, "{value:?}");
1123 }
1124 }
1125
1126 #[test]
1127 fn trims_like_javascript_before_the_length_check() {
1128 let padded = format!("{0}2026-01-01{0}", " ".repeat(100_000));
1129
1130 assert_eq!(parse_timer_instant(&padded), Some(1_767_225_600_000));
1131 assert_eq!(
1132 parse_timer_instant("\u{feff}\u{a0}\t2026-01-01\n\u{2028}"),
1133 Some(1_767_225_600_000)
1134 );
1135 assert_eq!(parse_timer_instant("\u{85}2026-01-01"), None);
1137 assert_eq!(parse_timer_instant(&"0".repeat(41)), None);
1138 }
1139
1140 #[test]
1141 fn stays_linear_on_adversarial_length_input() {
1142 let started = std::time::Instant::now();
1143
1144 for value in [
1145 format!("{}-", "1".repeat(200_000)),
1146 "2".repeat(100_000),
1147 format!("2026-01-01T{}", "0".repeat(100_000)),
1148 format!("2026-01-01T12:00:00.{}Z", "1".repeat(100_000)),
1149 "-".repeat(100_000),
1150 ":".repeat(100_000),
1151 ] {
1152 assert_eq!(parse_timer_instant(&value), None);
1153 }
1154
1155 assert_eq!(
1156 resolve_timer_units_list(TimerMode::Elapsed, &format!("{}days", ", ".repeat(200_000))),
1157 HMS
1158 );
1159 assert_eq!(
1160 resolve_timer_units_list(TimerMode::Countdown, &"x".repeat(100_000)),
1161 ALL
1162 );
1163 assert!(started.elapsed() < std::time::Duration::from_millis(500));
1164 }
1165
1166 #[test]
1167 fn rounds_a_countdown_up_and_elapsed_time_down_clamping_at_zero() {
1168 assert_eq!(timer_seconds(TimerMode::Countdown, START + 1500, START), 2);
1169 assert_eq!(timer_seconds(TimerMode::Countdown, START + 1, START), 1);
1170 assert_eq!(timer_seconds(TimerMode::Countdown, START, START), 0);
1171 assert_eq!(timer_seconds(TimerMode::Countdown, START - 5000, START), 0);
1172 assert_eq!(timer_seconds(TimerMode::Elapsed, START, START + 1999), 1);
1173 assert_eq!(timer_seconds(TimerMode::Elapsed, START + 5000, START), 0);
1174 assert_eq!(
1175 timer_seconds(TimerMode::Countdown, i64::MAX, i64::MIN),
1176 u64::MAX.div_ceil(1000)
1177 );
1178 assert_eq!(timer_seconds(TimerMode::Elapsed, i64::MAX, i64::MIN), 0);
1179 }
1180
1181 #[test]
1182 fn uses_absolute_milliseconds_across_daylight_saving_changes() {
1183 let before = parse_timer_instant("2026-03-08T06:00:00Z");
1184 let after = parse_timer_instant("2026-03-09T06:00:00Z");
1185
1186 assert_eq!(
1187 before.zip(after).map(|(before, after)| timer_seconds(
1188 TimerMode::Countdown,
1189 after,
1190 before
1191 )),
1192 Some(86_400)
1193 );
1194 }
1195
1196 #[test]
1197 fn aligns_ticks_to_the_next_displayed_second() {
1198 assert_eq!(timer_tick_delay(START, START), 1000);
1199 assert_eq!(timer_tick_delay(START, START + 250), 750);
1200 assert_eq!(timer_tick_delay(START + 1250, START), 250);
1201 assert_eq!(timer_tick_delay(START, START - 1), 1);
1202 assert_eq!(timer_tick_delay(i64::MIN, i64::MAX), 385);
1203 }
1204
1205 #[test]
1206 fn splits_into_requested_units_with_the_largest_absorbing_overflow() {
1207 assert_eq!(split_timer_duration(93_784, ALL), parts(1, 2, 3, 4));
1208 assert_eq!(split_timer_duration(93_784, HMS), parts(0, 26, 3, 4));
1209 assert_eq!(
1210 split_timer_duration(93_784, &[TimerUnit::Minutes]),
1211 parts(0, 0, 1563, 0)
1212 );
1213 assert_eq!(split_timer_duration(0, ALL), parts(0, 0, 0, 0));
1214 assert_eq!(split_timer_duration(93_784, &[]), parts(0, 0, 0, 0));
1215 assert_eq!(
1216 split_timer_duration(8_640_000_000_000, ALL).days,
1217 100_000_000
1218 );
1219 }
1220
1221 #[test]
1222 fn formats_iso_8601_durations() {
1223 assert_eq!(format_timer_iso_duration(parts(0, 1, 2, 3)), "PT1H2M3S");
1224 assert_eq!(format_timer_iso_duration(parts(2, 4, 0, 0)), "P2DT4H");
1225 assert_eq!(format_timer_iso_duration(parts(3, 0, 0, 0)), "P3D");
1226 assert_eq!(format_timer_iso_duration(parts(0, 0, 0, 0)), "PT0S");
1227 assert_eq!(format_timer_iso_duration(parts(0, 36, 0, 1)), "PT36H1S");
1228 }
1229
1230 #[test]
1231 fn resolves_units_in_canonical_order_with_mode_defaults() {
1232 assert_eq!(resolve_timer_units(TimerMode::Countdown, &[]), ALL);
1233 assert_eq!(resolve_timer_units(TimerMode::Elapsed, &[]), HMS);
1234 assert_eq!(
1235 resolve_timer_units(
1236 TimerMode::Elapsed,
1237 &[TimerUnit::Seconds, TimerUnit::Minutes, TimerUnit::Minutes]
1238 ),
1239 [TimerUnit::Minutes, TimerUnit::Seconds]
1240 );
1241 assert_eq!(
1242 resolve_timer_units_list(TimerMode::Elapsed, "seconds,minutes,minutes,weeks"),
1243 [TimerUnit::Minutes, TimerUnit::Seconds]
1244 );
1245 assert_eq!(
1246 resolve_timer_units_list(TimerMode::Countdown, "hours, seconds minutes"),
1247 HMS
1248 );
1249 assert_eq!(resolve_timer_units_list(TimerMode::Countdown, "weeks"), ALL);
1250 assert_eq!(resolve_timer_units_list(TimerMode::Elapsed, ""), HMS);
1251 assert_eq!(resolve_timer_units_list(TimerMode::Countdown, "Days"), ALL);
1252 }
1253
1254 #[test]
1255 fn unit_lists_split_like_javascript() {
1256 assert_eq!(
1257 resolve_timer_units_list(TimerMode::Countdown, "hours\t\n\u{a0}\u{feff}minutes"),
1258 [TimerUnit::Hours, TimerUnit::Minutes]
1259 );
1260 assert_eq!(
1262 resolve_timer_units_list(TimerMode::Countdown, "hours\u{85}minutes"),
1263 ALL
1264 );
1265 assert_eq!(
1267 resolve_timer_units_list(TimerMode::Countdown, &format!("{}days", " ".repeat(196))),
1268 [TimerUnit::Days]
1269 );
1270 assert_eq!(
1271 resolve_timer_units_list(TimerMode::Countdown, &format!("{}days", " ".repeat(197))),
1272 ALL
1273 );
1274 assert_eq!(
1276 resolve_timer_units_list(
1277 TimerMode::Countdown,
1278 &format!("{}days\u{1f600}", " ".repeat(196))
1279 ),
1280 [TimerUnit::Days]
1281 );
1282 assert_eq!(
1283 resolve_timer_units_list(
1284 TimerMode::Countdown,
1285 &format!("{}days\u{1f600}", " ".repeat(195))
1286 ),
1287 ALL
1288 );
1289 }
1290
1291 #[test]
1292 fn names_match_the_other_adapters() {
1293 assert_eq!(
1294 TIMER_UNITS.map(TimerUnit::as_str),
1295 ["days", "hours", "minutes", "seconds"]
1296 );
1297 assert_eq!(TimerMode::Countdown.as_str(), "countdown");
1298 assert_eq!(TimerMode::Elapsed.as_str(), "elapsed");
1299 assert_eq!(TimerFormat::Clock.as_str(), "clock");
1300 assert_eq!(TimerFormat::Units.as_str(), "units");
1301 assert_eq!(TimerAnnounce::Off.as_str(), "off");
1302 assert_eq!(TimerAnnounce::Minute.as_str(), "minute");
1303 assert_eq!(TimerAnnounce::Complete.as_str(), "complete");
1304 assert_eq!(TimerState::Running.as_str(), "running");
1305 assert_eq!(TimerState::Complete.as_str(), "complete");
1306 assert_eq!(TimerState::Invalid.as_str(), "invalid");
1307 }
1308
1309 #[test]
1310 fn formats_clock_unit_and_spoken_text_in_english() {
1311 let value = parts(0, 1, 2, 3);
1312
1313 assert_eq!(format_clock(&value, HMS), "01:02:03");
1314 assert_eq!(format_clock(&value, ALL), "01:02:03");
1315 assert_eq!(format_clock(&parts(2, 1, 2, 3), ALL), "02:01:02:03");
1316 assert_eq!(format_clock(&parts(0, 120, 2, 3), HMS), "120:02:03");
1317 assert_eq!(format_clock(&parts(0, 0, 0, 0), &[TimerUnit::Days]), "00");
1318 assert_eq!(format_units(&value, ALL), "1h 2m 3s");
1319 assert_eq!(format_units(&parts(0, 0, 0, 0), HMS), "0s");
1320 assert_eq!(
1321 format_spoken(&value, &[TimerUnit::Hours, TimerUnit::Minutes]),
1322 "1 hour, 2 minutes"
1323 );
1324 assert_eq!(
1325 format_spoken(
1326 &parts(1, 2, 3, 0),
1327 &[TimerUnit::Days, TimerUnit::Hours, TimerUnit::Minutes]
1328 ),
1329 "1 day, 2 hours, 3 minutes"
1330 );
1331 assert_eq!(format_spoken(&parts(0, 0, 0, 1), ALL), "1 second");
1332 assert_eq!(format_spoken(&parts(0, 0, 0, 0), ALL), "0 seconds");
1333 }
1334
1335 #[test]
1336 fn groups_large_unit_values_but_not_clock_digits() {
1337 let value = parts(1234, 0, 5, 0);
1338
1339 assert_eq!(format_units(&value, ALL), "1,234d 0h 5m 0s");
1340 assert_eq!(format_clock(&value, ALL), "1234:00:05:00");
1341 assert_eq!(
1342 format_spoken(&parts(100_000_000, 0, 0, 0), &[TimerUnit::Days]),
1343 "100,000,000 days"
1344 );
1345 assert_eq!(group_digits(0), "0");
1346 assert_eq!(group_digits(999), "999");
1347 assert_eq!(group_digits(1000), "1,000");
1348 assert_eq!(group_digits(1_000_000), "1,000,000");
1349 assert_eq!(group_digits(u64::MAX), "18,446,744,073,709,551,615");
1350 }
1351
1352 #[test]
1353 fn renders_a_countdown_its_completion_and_elapsed_time() {
1354 let config = countdown(START + 3_723_000);
1355 let running = timer_snapshot(&config, START);
1356
1357 assert_eq!(running.date_time.as_deref(), Some("PT1H2M3S"));
1358 assert_eq!(running.state, TimerState::Running);
1359 assert_eq!(running.text, "01:02:03");
1360
1361 let complete = timer_snapshot(&config, START + 3_723_000);
1362
1363 assert_eq!(complete.date_time.as_deref(), Some("PT0S"));
1364 assert_eq!(complete.state, TimerState::Complete);
1365 assert_eq!(complete.text, "00:00:00");
1366
1367 let elapsed = resolve_timer_config(
1368 TimerMode::Elapsed,
1369 TimerFormat::Units,
1370 TimerAnnounce::Off,
1371 None,
1372 Some(START),
1373 &[],
1374 );
1375
1376 let snapshot = timer_snapshot(&elapsed, START + 10 * 86_400_000);
1377
1378 assert_eq!(snapshot.date_time.as_deref(), Some("PT240H"));
1379 assert_eq!(snapshot.state, TimerState::Running);
1380 assert_eq!(snapshot.text, "240h 0m 0s");
1381 }
1382
1383 #[test]
1384 fn renders_the_placeholder_for_invalid_input() {
1385 let config = countdown(0);
1386 let invalid = TimerConfig {
1387 instant: parse_timer_instant("tomorrow"),
1388 ..config
1389 };
1390
1391 assert_eq!(
1392 timer_snapshot(&invalid, START),
1393 TimerSnapshot {
1394 date_time: None,
1395 minute: 0,
1396 seconds: 0,
1397 spoken_minute: TIMER_PLACEHOLDER.to_owned(),
1398 state: TimerState::Invalid,
1399 text: TIMER_PLACEHOLDER.to_owned(),
1400 }
1401 );
1402 assert_eq!(countdown(MAX_EPOCH_MS + 1).instant, None);
1403 }
1404
1405 #[test]
1406 fn resolves_config_defaults_and_labels() {
1407 let config = TimerConfig::default();
1408
1409 assert_eq!(config.announce, TimerAnnounce::Off);
1410 assert_eq!(config.complete_label, TIMER_DEFAULT_COMPLETE_LABEL);
1411 assert_eq!(config.format, TimerFormat::Clock);
1412 assert_eq!(config.instant, None);
1413 assert_eq!(config.mode, TimerMode::Countdown);
1414 assert_eq!(config.units, ALL);
1415
1416 let labelled = |label| {
1417 resolve_timer_config(
1418 TimerMode::Elapsed,
1419 TimerFormat::Units,
1420 TimerAnnounce::Complete,
1421 label,
1422 Some(START),
1423 &[TimerUnit::Seconds],
1424 )
1425 };
1426
1427 assert_eq!(
1428 labelled(Some(" Offer ended \n")).complete_label,
1429 "Offer ended"
1430 );
1431 assert_eq!(
1432 labelled(Some(" \u{feff} ")).complete_label,
1433 TIMER_DEFAULT_COMPLETE_LABEL
1434 );
1435 assert_eq!(labelled(None).complete_label, TIMER_DEFAULT_COMPLETE_LABEL);
1436 assert_eq!(labelled(None).units, [TimerUnit::Seconds]);
1437 assert_eq!(labelled(None).instant, Some(START));
1438 }
1439
1440 #[test]
1441 fn announcements_are_silent_on_the_first_render_and_while_off() {
1442 let config = TimerConfig {
1443 announce: TimerAnnounce::Minute,
1444 ..countdown(START + 180_000)
1445 };
1446 let at = |offset| timer_snapshot(&config, START + offset);
1447
1448 assert_eq!(timer_announcement(&config, None, &at(0)), None);
1449
1450 let off = TimerConfig {
1451 announce: TimerAnnounce::Off,
1452 ..config.clone()
1453 };
1454
1455 assert_eq!(timer_announcement(&off, Some(&at(0)), &at(61_000)), None);
1456 }
1457
1458 #[test]
1459 fn announces_at_most_once_per_minute_and_at_completion() {
1460 let config = TimerConfig {
1461 announce: TimerAnnounce::Minute,
1462 ..countdown(START + 180_000)
1463 };
1464 let at = |offset| timer_snapshot(&config, START + offset);
1465 let announce =
1466 |previous: i64, next: i64| timer_announcement(&config, Some(&at(previous)), &at(next));
1467
1468 assert_eq!(announce(0, 1000), None);
1469 assert_eq!(announce(59_000, 60_000).as_deref(), Some("2 minutes"));
1470 assert_eq!(announce(60_000, 61_000), None);
1471 assert_eq!(
1472 announce(179_000, 180_000).as_deref(),
1473 Some("Timer complete")
1474 );
1475 assert_eq!(announce(180_000, 181_000), None);
1476 }
1477
1478 #[test]
1479 fn complete_mode_only_speaks_the_completion_label() {
1480 let config = TimerConfig {
1481 announce: TimerAnnounce::Complete,
1482 complete_label: String::from("Offer ended"),
1483 ..countdown(START + 180_000)
1484 };
1485 let at = |offset| timer_snapshot(&config, START + offset);
1486
1487 assert_eq!(
1488 timer_announcement(&config, Some(&at(59_000)), &at(60_000)),
1489 None
1490 );
1491 assert_eq!(
1492 timer_announcement(&config, Some(&at(179_000)), &at(180_000)).as_deref(),
1493 Some("Offer ended")
1494 );
1495 }
1496
1497 #[test]
1498 fn counts_down_and_completes_once() {
1499 let config = resolve_timer_config(
1500 TimerMode::Countdown,
1501 TimerFormat::Clock,
1502 TimerAnnounce::Off,
1503 None,
1504 Some(START + 2500),
1505 &[TimerUnit::Minutes, TimerUnit::Seconds],
1506 );
1507 let first = timer_snapshot(&config, START);
1508
1509 assert_eq!(first.text, "00:03");
1510 assert_eq!(first.date_time.as_deref(), Some("PT3S"));
1511 assert_eq!(first.state, TimerState::Running);
1512 assert!(!is_timer_completion(None, &first));
1513 assert_eq!(timer_tick_delay(START + 2500, START), 500);
1514
1515 let second = timer_snapshot(&config, START + 500);
1516
1517 assert_eq!(second.text, "00:02");
1518
1519 let done = timer_snapshot(&config, START + 2500);
1520
1521 assert_eq!(done.text, "00:00");
1522 assert_eq!(done.state, TimerState::Complete);
1523 assert!(is_timer_completion(Some(&second), &done));
1524
1525 let later = timer_snapshot(&config, START + 12_500);
1526
1527 assert!(!is_timer_completion(Some(&done), &later));
1528 assert_eq!(later.state, TimerState::Complete);
1529 }
1530
1531 #[test]
1532 fn an_already_ended_countdown_does_not_complete() {
1533 let snapshot = timer_snapshot(&countdown(START - 1000), START);
1534
1535 assert_eq!(snapshot.state, TimerState::Complete);
1536 assert!(!is_timer_completion(None, &snapshot));
1537 }
1538
1539 #[test]
1540 fn completes_after_a_resync_past_zero() {
1541 let config = countdown(START + 5000);
1542 let hidden = timer_snapshot(&config, START);
1543 let visible = timer_snapshot(&config, START + 60_000);
1544
1545 assert_eq!(hidden.text, "00:00:05");
1546 assert_eq!(visible.text, "00:00:00");
1547 assert!(is_timer_completion(Some(&hidden), &visible));
1548 }
1549
1550 #[test]
1551 fn keeps_counting_elapsed_time_and_throttles_minute_announcements() {
1552 let config = resolve_timer_config(
1553 TimerMode::Elapsed,
1554 TimerFormat::Clock,
1555 TimerAnnounce::Minute,
1556 None,
1557 Some(START - 58_000),
1558 &[],
1559 );
1560 let at = |offset| timer_snapshot(&config, START + offset);
1561
1562 assert_eq!(at(0).text, "00:00:58");
1563 assert_eq!(
1564 timer_announcement(&config, Some(&at(0)), &at(2000)).as_deref(),
1565 Some("1 minute")
1566 );
1567 assert_eq!(
1568 timer_announcement(&config, Some(&at(2000)), &at(32_000)),
1569 None
1570 );
1571 assert_eq!(at(62_000).text, "00:02:00");
1572 assert_eq!(
1573 timer_announcement(&config, Some(&at(32_000)), &at(62_000)).as_deref(),
1574 Some("2 minutes")
1575 );
1576 }
1577
1578 #[test]
1579 fn invalid_input_renders_the_placeholder_and_stops() {
1580 let config = countdown(0);
1581 let invalid = TimerConfig {
1582 instant: parse_timer_instant("not a date"),
1583 ..config
1584 };
1585 let snapshot = timer_snapshot(&invalid, START);
1586
1587 assert_eq!(snapshot.text, TIMER_PLACEHOLDER);
1588 assert_eq!(snapshot.date_time, None);
1589 assert_eq!(snapshot.state, TimerState::Invalid);
1590 assert_eq!(
1591 timer_announcement(&invalid, Some(&snapshot), &snapshot),
1592 None
1593 );
1594 }
1595
1596 #[test]
1597 fn units_format_shows_minutes_and_seconds() {
1598 let config = TimerConfig {
1599 format: TimerFormat::Units,
1600 ..countdown(START + 65_000)
1601 };
1602
1603 assert_eq!(timer_snapshot(&config, START).text, "1m 5s");
1604 }
1605
1606 #[test]
1607 fn spoken_minutes_use_the_seconds_unit_when_it_is_the_only_one() {
1608 let config = TimerConfig {
1609 units: vec![TimerUnit::Seconds],
1610 ..countdown(START + 61_500)
1611 };
1612 let snapshot = timer_snapshot(&config, START);
1613
1614 assert_eq!(snapshot.text, "62");
1615 assert_eq!(snapshot.minute, 2);
1616 assert_eq!(snapshot.spoken_minute, "62 seconds");
1617 }
1618}