1use std::{cmp::Ordering, fmt, str::FromStr, time::Duration};
16
17use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
18
19#[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
26pub struct ConfigDuration(Duration);
27
28const EXPECTED_UNITS: &str = match str::from_utf8(&EXPECTED_UNITS_BYTES) {
32 Ok(text) => text,
33 Err(_) => panic!("unit names are UTF-8"),
34};
35
36const EXPECTED_UNITS_BYTES: [u8; EXPECTED_UNITS_LEN] = {
37 let mut buf = [0u8; EXPECTED_UNITS_LEN];
38 render_expected_units(&mut buf);
39 buf
40};
41
42const EXPECTED_UNITS_LEN: usize = render_expected_units(&mut []);
43
44const fn render_expected_units(buf: &mut [u8]) -> usize {
47 let mut i = 0;
48 while i < UNITS.len() {
49 i += 1;
50 }
51
52 let mut at = put(buf, 0, "expected one of ");
53 let mut i = 0;
54 while i < UNITS.len() {
55 let (name, _) = UNITS[i];
56 i += 1;
57 if i > 1 {
58 at = put(buf, at, ", ");
59 }
60 at = put(buf, at, "'");
61 at = put(buf, at, name);
62 at = put(buf, at, "'");
63 }
64 at
65}
66
67const fn put(buf: &mut [u8], at: usize, text: &str) -> usize {
70 let bytes = text.as_bytes();
71 if !buf.is_empty() {
72 let mut i = 0;
73 while i < bytes.len() {
74 buf[at + i] = bytes[i];
75 i += 1;
76 }
77 }
78 at + bytes.len()
79}
80
81#[derive(Debug, thiserror::Error, Eq, PartialEq)]
86#[non_exhaustive]
87pub enum ParseError {
88 #[error("empty duration: write `0`, or a number and a unit such as `500ms`")]
90 Empty,
91
92 #[error("unknown unit `{unit}` in duration `{input}`: {EXPECTED_UNITS}")]
94 InvalidUnit { unit: String, input: String },
95
96 #[error("`{unit}` in duration `{input}` has no number in front of it")]
98 MissingNumber { unit: String, input: String },
99
100 #[error("`{number}` in duration `{input}` carries no unit: {EXPECTED_UNITS}")]
102 NoUnit { number: String, input: String },
103
104 #[error("duration `{input}` cannot be negative")]
107 Negative { input: String },
108
109 #[error("duration `{input}` is too large: at most {} days", u64::MAX / (24 * 60 * 60))]
111 Overflow { input: String },
112}
113
114const NANOS_PER_SECOND: u128 = 1_000_000_000;
115
116impl ConfigDuration {
117 pub const ZERO: ConfigDuration = ConfigDuration(Duration::ZERO);
118
119 pub const fn from_nanos(nanos: u64) -> Self {
120 Self(Duration::from_nanos(nanos))
121 }
122
123 pub const fn from_micros(micros: u64) -> Self {
124 Self(Duration::from_micros(micros))
125 }
126
127 pub const fn from_millis(millis: u64) -> Self {
128 Self(Duration::from_millis(millis))
129 }
130
131 pub const fn from_secs(secs: u64) -> Self {
132 Self(Duration::from_secs(secs))
133 }
134
135 pub const fn from_days(days: u64) -> Self {
138 Self(Duration::from_secs(days.saturating_mul(24 * 60 * 60)))
139 }
140
141 pub const fn as_micros(self) -> u128 {
142 self.0.as_micros()
143 }
144
145 pub const fn as_millis(self) -> u128 {
146 self.0.as_millis()
147 }
148
149 pub const fn as_secs(self) -> u64 {
150 self.0.as_secs()
151 }
152
153 pub fn as_secs_f64(self) -> f64 {
154 self.0.as_secs_f64()
155 }
156
157 pub const fn is_zero(self) -> bool {
158 self.0.is_zero()
159 }
160}
161
162impl From<Duration> for ConfigDuration {
163 fn from(duration: Duration) -> Self {
164 Self(duration)
165 }
166}
167
168impl From<ConfigDuration> for Duration {
169 fn from(ConfigDuration(duration): ConfigDuration) -> Self {
170 duration
171 }
172}
173
174impl PartialEq<Duration> for ConfigDuration {
175 fn eq(&self, other: &Duration) -> bool {
176 self.0 == *other
177 }
178}
179
180impl PartialOrd for ConfigDuration {
181 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
182 Some(self.cmp(other))
183 }
184}
185
186impl Ord for ConfigDuration {
187 fn cmp(&self, other: &Self) -> Ordering {
188 self.0.cmp(&other.0)
189 }
190}
191
192impl PartialOrd<Duration> for ConfigDuration {
193 fn partial_cmp(&self, other: &Duration) -> Option<Ordering> {
194 self.0.partial_cmp(other)
195 }
196}
197
198const UNITS: [(&str, u128); 9] = [
203 ("ns", 1),
204 ("us", 1_000),
205 ("\u{00b5}s", 1_000),
208 ("\u{03bc}s", 1_000),
209 ("ms", 1_000_000),
210 ("s", NANOS_PER_SECOND),
211 ("m", 60 * NANOS_PER_SECOND),
212 ("h", 60 * 60 * NANOS_PER_SECOND),
213 ("d", 24 * 60 * 60 * NANOS_PER_SECOND),
214];
215
216const MAX_FRACTION_DIGITS: usize = 18;
223
224fn digits_to_u128(digits: &str) -> Option<u128> {
226 digits.bytes().try_fold(0u128, |acc, byte| {
227 acc.checked_mul(10)?.checked_add(u128::from(byte - b'0'))
228 })
229}
230
231impl FromStr for ConfigDuration {
232 type Err = ParseError;
233
234 fn from_str(s: &str) -> Result<Self, Self::Err> {
242 let input = s;
243 let overflow = || ParseError::Overflow {
244 input: input.to_string(),
245 };
246
247 if input.starts_with('-') {
248 return Err(ParseError::Negative {
249 input: input.to_string(),
250 });
251 }
252 let body = input.strip_prefix('+').unwrap_or(input);
254 if body.is_empty() {
255 return Err(ParseError::Empty);
256 }
257 if body == "0" {
259 return Ok(ConfigDuration::ZERO);
260 }
261
262 let bytes = body.as_bytes();
263 let mut at = 0;
264 let mut total: u128 = 0;
265
266 while at < bytes.len() {
267 let number_at = at;
268
269 let whole_at = at;
271 while at < bytes.len() && bytes[at].is_ascii_digit() {
272 at += 1;
273 }
274 let whole = &body[whole_at..at];
275
276 let mut fraction = "";
277 let has_point = at < bytes.len() && bytes[at] == b'.';
278 if has_point {
279 at += 1;
280 let fraction_at = at;
281 while at < bytes.len() && bytes[at].is_ascii_digit() {
282 at += 1;
283 }
284 fraction = &body[fraction_at..at];
285 }
286 let number = &body[number_at..at];
287
288 let unit_at = at;
291 while at < bytes.len() && !bytes[at].is_ascii_digit() && bytes[at] != b'.' {
292 at += 1;
293 }
294 let unit = &body[unit_at..at];
295
296 if whole.is_empty() && fraction.is_empty() {
297 let known = UNITS.iter().any(|(name, _)| *name == unit);
301 return Err(if known {
302 ParseError::MissingNumber {
303 unit: unit.to_string(),
304 input: input.to_string(),
305 }
306 } else {
307 ParseError::InvalidUnit {
308 unit: unit.to_string(),
309 input: input.to_string(),
310 }
311 });
312 }
313 if unit.is_empty() {
317 return Err(ParseError::NoUnit {
318 number: number.to_string(),
319 input: input.to_string(),
320 });
321 }
322 let Some(&(_, unit_nanos)) = UNITS.iter().find(|(name, _)| *name == unit) else {
323 return Err(ParseError::InvalidUnit {
324 unit: unit.to_string(),
325 input: input.to_string(),
326 });
327 };
328
329 let mut term = digits_to_u128(whole)
330 .ok_or_else(overflow)?
331 .checked_mul(unit_nanos)
332 .ok_or_else(overflow)?;
333
334 if !fraction.is_empty() {
335 let kept = fraction.len().min(MAX_FRACTION_DIGITS);
339 let numerator = digits_to_u128(&fraction[..kept]).ok_or_else(overflow)?;
340 let denominator = 10u128.pow(kept as u32);
341 let scaled = unit_nanos.checked_mul(numerator).ok_or_else(overflow)?;
342 let rounded = (scaled + denominator / 2) / denominator;
343 term = term.checked_add(rounded).ok_or_else(overflow)?;
344 }
345
346 total = total.checked_add(term).ok_or_else(overflow)?;
347 }
348
349 let seconds = u64::try_from(total / NANOS_PER_SECOND).map_err(|_| overflow())?;
350 Ok(ConfigDuration(Duration::new(
351 seconds,
352 (total % NANOS_PER_SECOND) as u32,
353 )))
354 }
355}
356
357impl fmt::Display for ConfigDuration {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 let mut remain = self.0.as_nanos();
362 if remain == 0 {
363 return f.write_str("0s");
364 }
365
366 for &(unit, base) in UNITS.iter().rev().filter(|(name, _)| name.is_ascii()) {
369 let unit_mult = remain / base;
370 if unit_mult != 0 {
371 remain %= base;
372 write!(f, "{unit_mult}{unit}")?;
373 }
374 }
375 Ok(())
376 }
377}
378
379impl fmt::Debug for ConfigDuration {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 fmt::Display::fmt(self, f)
382 }
383}
384
385impl Serialize for ConfigDuration {
386 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
387 serializer.collect_str(self)
388 }
389}
390
391impl<'de> Deserialize<'de> for ConfigDuration {
392 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
393 struct Visitor;
394
395 impl de::Visitor<'_> for Visitor {
396 type Value = ConfigDuration;
397
398 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399 f.write_str("a duration such as \"500ms\", \"30s\", \"1h30m\" or \"30d\"")
400 }
401
402 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
403 value.parse::<ConfigDuration>().map_err(de::Error::custom)
404 }
405 }
406
407 deserializer.deserialize_str(Visitor)
408 }
409}
410
411#[derive(Clone, Copy, Debug, Eq, PartialEq)]
426pub enum LegacyUnit {
427 Micros,
428 Millis,
429 Secs,
430 Days,
431}
432
433impl LegacyUnit {
434 pub const fn nanos(self) -> u64 {
436 match self {
437 LegacyUnit::Micros => 1_000,
438 LegacyUnit::Millis => 1_000_000,
439 LegacyUnit::Secs => 1_000_000_000,
440 LegacyUnit::Days => 24 * 60 * 60 * 1_000_000_000,
441 }
442 }
443}
444
445fn duration_from_nanos_saturating(nanos: u128) -> ConfigDuration {
453 const NANOS_PER_SECOND_U128: u128 = NANOS_PER_SECOND;
454 match u64::try_from(nanos / NANOS_PER_SECOND_U128) {
455 Ok(seconds) => ConfigDuration(Duration::new(
456 seconds,
457 (nanos % NANOS_PER_SECOND_U128) as u32,
458 )),
459 Err(_) => ConfigDuration(Duration::MAX),
460 }
461}
462
463pub fn duration_from_legacy_number<E: de::Error>(
474 warned: &std::sync::atomic::AtomicBool,
475 field: &str,
476 unit: LegacyUnit,
477 value: u64,
478) -> Result<ConfigDuration, E> {
479 let duration = duration_from_nanos_saturating(u128::from(value) * u128::from(unit.nanos()));
480 if value != u64::MAX && !warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
485 log::warn!(
486 "configuration field `{field}` was given the bare number {value}, which is \
487 deprecated and is removed no earlier than release 0.368.0; write \
488 `\"{duration}\"` instead"
489 );
490 }
491 Ok(duration)
492}
493
494fn whole_number(value: f64) -> Option<u64> {
499 const TWO_TO_THE_64: f64 = 18_446_744_073_709_551_616.0;
502 (value.is_finite() && value >= 0.0 && value.fract() == 0.0 && value < TWO_TO_THE_64)
503 .then_some(value as u64)
504}
505
506pub fn duration_or_legacy_number<'de, D>(
513 deserializer: D,
514 warned: &std::sync::atomic::AtomicBool,
515 field: &'static str,
516 unit: LegacyUnit,
517) -> Result<Option<ConfigDuration>, D::Error>
518where
519 D: Deserializer<'de>,
520{
521 struct Visitor<'a> {
522 warned: &'a std::sync::atomic::AtomicBool,
523 field: &'static str,
524 unit: LegacyUnit,
525 }
526
527 impl Visitor<'_> {
528 fn not_a_number<E: de::Error>(field: &str, value: &str) -> E {
530 de::Error::custom(format!(
531 "`{field}` expects a duration such as \"30s\", or a whole number of the unit \
532 its earlier spelling took; `{value}` is neither"
533 ))
534 }
535 }
536
537 impl<'de> de::Visitor<'de> for Visitor<'_> {
538 type Value = Option<ConfigDuration>;
539
540 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541 f.write_str("a duration such as \"500ms\", \"30s\" or \"1h30m\"")
542 }
543
544 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
545 value
546 .parse::<ConfigDuration>()
547 .map(Some)
548 .map_err(de::Error::custom)
549 }
550
551 fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
552 duration_from_legacy_number(self.warned, self.field, self.unit, value).map(Some)
553 }
554
555 fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
556 let value = u64::try_from(value)
557 .map_err(|_| de::Error::custom(format!("`{}` cannot be negative", self.field)))?;
558 self.visit_u64(value)
559 }
560
561 fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
562 match whole_number(value) {
563 Some(whole) => self.visit_u64(whole),
564 None => Err(Self::not_a_number(self.field, &value.to_string())),
565 }
566 }
567
568 fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
576 const NUMBER: &str = "$serde_json::private::Number";
577
578 let Some(key) = map.next_key::<String>()? else {
579 return Err(Self::not_a_number(self.field, "{}"));
580 };
581 if key != NUMBER {
582 return Err(Self::not_a_number(self.field, "an object"));
583 }
584 let text = map.next_value::<String>()?;
587 match text.parse::<f64>().ok().and_then(whole_number) {
588 Some(whole) => self.visit_u64(whole),
589 None => Err(Self::not_a_number(self.field, &text)),
590 }
591 }
592
593 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
597 Ok(None)
598 }
599 }
600
601 deserializer.deserialize_any(Visitor {
602 warned,
603 field,
604 unit,
605 })
606}
607
608pub fn duration_or_legacy_struct<'de, D>(
613 deserializer: D,
614 warned: &std::sync::atomic::AtomicBool,
615 field: &'static str,
616) -> Result<Option<ConfigDuration>, D::Error>
617where
618 D: Deserializer<'de>,
619{
620 struct Visitor<'a> {
621 warned: &'a std::sync::atomic::AtomicBool,
622 field: &'static str,
623 }
624
625 impl<'de> de::Visitor<'de> for Visitor<'_> {
626 type Value = Option<ConfigDuration>;
627
628 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.write_str("a duration such as \"30s\", or a {secs, nanos} object")
633 }
634
635 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
636 value
637 .parse::<ConfigDuration>()
638 .map(Some)
639 .map_err(de::Error::custom)
640 }
641
642 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
643 Ok(None)
644 }
645
646 fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
652 const NUMBER: &str = "$serde_json::private::Number";
653
654 let (mut secs, mut nanos) = (0u64, 0u32);
655 let mut saw_field = false;
656 while let Some(key) = map.next_key::<String>()? {
657 match key.as_str() {
658 "secs" => {
659 secs = map.next_value()?;
660 saw_field = true;
661 }
662 "nanos" => {
663 nanos = map.next_value()?;
664 saw_field = true;
665 }
666 NUMBER => {
667 let text = map.next_value::<String>()?;
668 return Err(de::Error::invalid_type(
669 de::Unexpected::Other(&format!("the number {text}")),
670 &self,
671 ));
672 }
673 other => {
674 return Err(de::Error::unknown_field(other, &["secs", "nanos"]));
675 }
676 }
677 }
678 if !saw_field {
679 return Err(de::Error::invalid_type(de::Unexpected::Map, &self));
680 }
681
682 let duration = duration_from_nanos_saturating(
683 u128::from(secs) * NANOS_PER_SECOND + u128::from(nanos),
684 );
685 if !self.warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
686 log::warn!(
687 "configuration field `{}` was given a `{{secs, nanos}}` object, which is \
688 deprecated and is removed no earlier than release 0.368.0; write \
689 `\"{duration}\"` instead",
690 self.field
691 );
692 }
693 Ok(Some(duration))
694 }
695 }
696
697 deserializer.deserialize_any(Visitor { warned, field })
703}
704
705#[doc(hidden)]
708#[macro_export]
709macro_rules! duration_struct_setting {
710 ($name:ident, $field:literal) => {
711 fn $name<'de, D>(
712 deserializer: D,
713 ) -> ::std::result::Result<Option<$crate::duration::ConfigDuration>, D::Error>
714 where
715 D: ::serde::Deserializer<'de>,
716 {
717 static WARNED: ::std::sync::atomic::AtomicBool =
718 ::std::sync::atomic::AtomicBool::new(false);
719 $crate::duration::duration_or_legacy_struct(deserializer, &WARNED, $field)
720 }
721 };
722}
723
724#[doc(hidden)]
734#[macro_export]
735macro_rules! duration_setting {
736 ($name:ident, $field:literal, $unit:expr) => {
737 fn $name<'de, D>(
738 deserializer: D,
739 ) -> ::std::result::Result<Option<$crate::duration::ConfigDuration>, D::Error>
740 where
741 D: ::serde::Deserializer<'de>,
742 {
743 static WARNED: ::std::sync::atomic::AtomicBool =
744 ::std::sync::atomic::AtomicBool::new(false);
745 $crate::duration::duration_or_legacy_number(deserializer, &WARNED, $field, $unit)
746 }
747 };
748}
749
750#[doc(hidden)]
758#[macro_export]
759macro_rules! nullable_duration_setting {
760 ($name:ident, $field:literal, $unit:expr) => {
761 fn $name<'de, D>(
762 deserializer: D,
763 ) -> ::std::result::Result<Option<Option<$crate::duration::ConfigDuration>>, D::Error>
764 where
765 D: ::serde::Deserializer<'de>,
766 {
767 static WARNED: ::std::sync::atomic::AtomicBool =
768 ::std::sync::atomic::AtomicBool::new(false);
769 $crate::duration::duration_or_legacy_number(deserializer, &WARNED, $field, $unit)
770 .map(Some)
771 }
772 };
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778
779 const SECOND: Duration = Duration::from_secs(1);
780 const MINUTE: Duration = Duration::from_secs(60);
781 const HOUR: Duration = Duration::from_secs(60 * 60);
782 const DAY: Duration = Duration::from_secs(24 * 60 * 60);
783
784 #[test]
785 fn parses_the_same_as_go() {
786 for (input, expected) in [
788 ("0", Duration::ZERO),
789 ("5s", 5 * SECOND),
790 ("30s", 30 * SECOND),
791 ("1478s", 1478 * SECOND),
792 ("100ns", Duration::from_nanos(100)),
793 ("11us", Duration::from_micros(11)),
794 ("11\u{00b5}s", Duration::from_micros(11)),
795 ("11\u{03bc}s", Duration::from_micros(11)),
796 ("1ms", Duration::from_millis(1)),
797 ("5.s", 5 * SECOND),
799 (".5s", Duration::from_millis(500)),
800 ("1h", HOUR),
801 ("1m", MINUTE),
802 ("3h30m", 3 * HOUR + 30 * MINUTE),
803 (
804 "10.5s4m",
805 4 * MINUTE + 10 * SECOND + Duration::from_millis(500),
806 ),
807 (
808 "1h2m3s4ms5us6ns",
809 HOUR + 2 * MINUTE
810 + 3 * SECOND
811 + Duration::from_millis(4)
812 + Duration::from_micros(5)
813 + Duration::from_nanos(6),
814 ),
815 (
816 "39h9m14.425s",
817 39 * HOUR + 9 * MINUTE + 14 * SECOND + Duration::from_millis(425),
818 ),
819 ("0.3333333333333333333h", 20 * MINUTE),
820 ] {
821 assert_eq!(
822 input.parse::<ConfigDuration>().unwrap(),
823 ConfigDuration(expected),
824 "parsing {input:?}"
825 );
826 }
827 }
828
829 #[test]
830 fn parses_days() {
831 assert_eq!(
832 "30d".parse::<ConfigDuration>().unwrap(),
833 ConfigDuration::from_days(30)
834 );
835 assert_eq!(
836 "1d12h".parse::<ConfigDuration>().unwrap(),
837 ConfigDuration(DAY + 12 * HOUR)
838 );
839 }
840
841 #[test]
842 fn rejects_bad_input() {
843 for input in [
844 "",
846 "+",
847 "++1s",
848 "-1s", "10",
850 "1s0",
851 "1h30", "10y",
853 "5sec",
854 "abc",
855 "1 s",
856 "5s ",
857 "1..2s",
858 "99999999999999999999999999s",
860 "184467440737095516160s",
861 "9223372036854775807d",
862 "1000000000000000000000d",
863 ] {
864 assert!(
865 input.parse::<ConfigDuration>().is_err(),
866 "{input:?} should not parse, got {:?}",
867 input.parse::<ConfigDuration>()
868 );
869 }
870 }
871
872 #[test]
875 fn a_unit_with_no_number_says_so() {
876 for (input, expected) in [
877 ("s", "`s` in duration `s` has no number in front of it"),
878 ("ms", "`ms` in duration `ms` has no number in front of it"),
879 ("forever", "unknown unit `forever`"),
880 ("1h ms", "unknown unit `h ms`"),
883 ] {
884 let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
885 assert!(
886 message.contains(expected),
887 "parsing {input:?} reported {message:?}"
888 );
889 }
890 }
891
892 #[test]
895 fn rejection_messages_quote_the_input() {
896 for (input, expected) in [
897 ("-1s", "duration `-1s` cannot be negative"),
898 ("10", "`10` in duration `10` carries no unit"),
899 ("5sec", "unknown unit `sec` in duration `5sec`"),
900 ("1 s", "unknown unit ` s` in duration `1 s`"),
902 ("99999999999999999999999999s", "is too large"),
903 ("", "empty duration"),
904 ] {
905 let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
906 assert!(
907 message.contains(expected),
908 "parsing {input:?} reported {message:?}, which omits {expected:?}"
909 );
910 }
911 }
912
913 #[test]
917 fn accepts_the_largest_representable_duration() {
918 let max = format!("{}s999999999ns", u64::MAX);
919 let parsed: ConfigDuration = max.parse().unwrap();
920 assert_eq!(parsed, ConfigDuration::from(Duration::MAX));
921 assert_eq!(
922 parsed.to_string().parse::<ConfigDuration>().unwrap(),
923 parsed
924 );
925 let over = format!("{}s1000000000ns", u64::MAX);
926 assert!(matches!(
927 over.parse::<ConfigDuration>(),
928 Err(ParseError::Overflow { .. })
929 ));
930 }
931
932 #[test]
941 fn a_superseded_spelling_reads_any_whole_number() {
942 #[derive(Debug, serde::Deserialize)]
943 struct Config {
944 #[serde(default, alias = "nap_secs", deserialize_with = "duration_nap")]
945 nap: Option<ConfigDuration>,
946 }
947 crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
948
949 for json in [
950 r#"{"nap_secs": 10}"#,
951 r#"{"nap_secs": 10.0}"#,
952 r#"{"nap_secs": 1e1}"#,
953 ] {
954 let config: Config = serde_json::from_str(json).unwrap();
955 assert_eq!(
956 config.nap,
957 Some(ConfigDuration::from_secs(10)),
958 "parsing {json}"
959 );
960 }
961 let config: Config = serde_json::from_str(r#"{"nap_secs": 18446744073709551615}"#).unwrap();
964 assert!(config.nap.is_some());
965 for json in [
966 r#"{"nap_secs": 18446744073709551616}"#,
967 r#"{"nap_secs": 18446744073709551617}"#,
968 r#"{"nap_secs": 1.8446744073709552e19}"#,
969 ] {
970 let error = serde_json::from_str::<Config>(json)
971 .unwrap_err()
972 .to_string();
973 assert!(
974 error.contains("is neither"),
975 "parsing {json} reported {error}"
976 );
977 }
978
979 let yaml: Config = serde_yaml::from_str("nap_secs: 10.0").unwrap();
980 assert_eq!(yaml.nap, Some(ConfigDuration::from_secs(10)));
981
982 for (bad, quoted) in [
983 (r#"{"nap_secs": 10.5}"#, "`10.5`"),
984 (r#"{"nap_secs": -5}"#, "cannot be negative"),
985 (r#"{"nap_secs": {}}"#, "`{}`"),
986 (r#"{"nap_secs": 10.50}"#, "`10.50`"),
988 (r#"{"nap_secs": {"secs": 1}}"#, "`an object`"),
989 ] {
990 let error = serde_json::from_str::<Config>(bad).unwrap_err().to_string();
991 assert!(error.contains(quoted), "parsing {bad} reported {error}");
992 assert!(
993 !error.contains("invalid type: map"),
994 "parsing {bad} reported {error}"
995 );
996 }
997 let error = serde_yaml::from_str::<Config>("nap_secs: 10.5")
998 .unwrap_err()
999 .to_string();
1000 assert!(error.contains("`10.5`"), "{error}");
1001 }
1002
1003 #[test]
1006 fn from_days_saturates() {
1007 assert_eq!(
1008 ConfigDuration::from_days(2),
1009 ConfigDuration::from_secs(2 * 86_400)
1010 );
1011 assert_eq!(
1012 ConfigDuration::from_days(u64::MAX),
1013 ConfigDuration::from_secs(u64::MAX)
1014 );
1015 }
1016
1017 #[test]
1022 fn the_no_limit_value_is_read_without_a_warning() {
1023 use std::sync::atomic::{AtomicBool, Ordering};
1024 let warned = AtomicBool::new(false);
1025 let max = duration_from_legacy_number::<serde_json::Error>(
1026 &warned,
1027 "max_output_buffer_time",
1028 LegacyUnit::Millis,
1029 u64::MAX,
1030 )
1031 .unwrap();
1032 assert_eq!(max, ConfigDuration::from_millis(u64::MAX));
1033 assert!(!warned.load(Ordering::Relaxed));
1034
1035 duration_from_legacy_number::<serde_json::Error>(
1036 &warned,
1037 "max_output_buffer_time",
1038 LegacyUnit::Millis,
1039 500,
1040 )
1041 .unwrap();
1042 assert!(warned.load(Ordering::Relaxed));
1043 }
1044
1045 #[test]
1049 fn fractions_scale_exactly() {
1050 const DAY_NANOS: u128 = 24 * 60 * 60 * 1_000_000_000;
1051 let digits = "718656392856533598";
1052 let exact = (DAY_NANOS * digits.parse::<u128>().unwrap()
1053 + 10u128.pow(digits.len() as u32) / 2)
1054 / 10u128.pow(digits.len() as u32);
1055 assert_eq!(exact, 62_091_912_342_805);
1056
1057 let parsed: ConfigDuration = format!("0.{digits}d").parse().unwrap();
1058 assert_eq!(Duration::from(parsed).as_nanos(), exact);
1059
1060 assert_eq!(
1062 "0.5s".parse::<ConfigDuration>().unwrap(),
1063 ConfigDuration::from_millis(500)
1064 );
1065 assert_eq!(
1066 "1.5s".parse::<ConfigDuration>().unwrap(),
1067 ConfigDuration::from_millis(1500)
1068 );
1069 assert_eq!(
1070 "0.0000000005s".parse::<ConfigDuration>().unwrap(),
1071 ConfigDuration::from_nanos(1)
1072 );
1073 }
1074
1075 #[test]
1079 fn writing_both_spellings_is_rejected() {
1080 #[derive(Debug, serde::Deserialize)]
1081 struct Config {
1082 #[serde(
1083 default,
1084 alias = "nap_secs",
1085 deserialize_with = "duration_nap",
1086 skip_serializing_if = "Option::is_none"
1087 )]
1088 nap: Option<ConfigDuration>,
1089 }
1090 crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
1091
1092 assert_eq!(
1093 serde_json::from_str::<Config>(r#"{"nap": "30s"}"#)
1094 .unwrap()
1095 .nap,
1096 Some(ConfigDuration::from_secs(30))
1097 );
1098 assert_eq!(
1099 serde_json::from_str::<Config>(r#"{"nap_secs": 30}"#)
1100 .unwrap()
1101 .nap,
1102 Some(ConfigDuration::from_secs(30))
1103 );
1104 let error = serde_json::from_str::<Config>(r#"{"nap": "30s", "nap_secs": 30}"#)
1105 .unwrap_err()
1106 .to_string();
1107 assert!(error.contains("duplicate field `nap`"), "{error}");
1108 }
1109
1110 #[test]
1116 fn large_values_round_trip_exactly() {
1117 let written = "128644735584426d23h5m38s";
1118 let parsed: ConfigDuration = written.parse().unwrap();
1119 assert_eq!(parsed.to_string(), written);
1120 assert_eq!(
1121 parsed.as_secs(),
1122 128_644_735_584_426 * 24 * 60 * 60 + 23 * 60 * 60 + 5 * 60 + 38
1123 );
1124 assert_eq!(
1125 "11114905154494489538s".parse::<ConfigDuration>().unwrap(),
1126 parsed
1127 );
1128 }
1129
1130 #[test]
1131 fn displays_in_decomposed_units() {
1132 for (duration, expected) in [
1133 (ConfigDuration::ZERO, "0s"),
1134 (ConfigDuration::from_days(30), "30d"),
1135 (ConfigDuration::from_secs(3600), "1h"),
1136 (ConfigDuration::from_secs(100), "1m40s"),
1137 (ConfigDuration::from_millis(500), "500ms"),
1138 (ConfigDuration::from_micros(1_000_000), "1s"),
1139 (ConfigDuration::from_nanos(1), "1ns"),
1140 (ConfigDuration(HOUR + 30 * MINUTE + 10 * SECOND), "1h30m10s"),
1141 ] {
1142 assert_eq!(duration.to_string(), expected);
1143 }
1144 }
1145
1146 #[test]
1147 fn round_trips_through_json() {
1148 for text in [
1149 "0s", "30d", "1h", "1m30s", "500ms", "1ns", "1h30m10s", "1d12h",
1150 ] {
1151 let json = format!("\"{text}\"");
1152 let duration: ConfigDuration = serde_json::from_str(&json).unwrap();
1153 assert_eq!(serde_json::to_string(&duration).unwrap(), json);
1154 }
1155 }
1156
1157 mod properties {
1164 use super::*;
1165 use proptest::prelude::*;
1166
1167 const UNITS: [(&str, u64); 7] = [
1169 ("ns", 1),
1170 ("us", 1_000),
1171 ("ms", 1_000_000),
1172 ("s", 1_000_000_000),
1173 ("m", 60 * 1_000_000_000),
1174 ("h", 60 * 60 * 1_000_000_000),
1175 ("d", 24 * 60 * 60 * 1_000_000_000),
1176 ];
1177
1178 fn seconds_and_nanos() -> impl Strategy<Value = (u64, u32)> {
1187 let seconds = prop_oneof![
1188 1 => Just(0u64),
1189 1 => Just(u64::MAX),
1190 1 => Just(11_114_905_154_334_422_338u64),
1191 2 => 0u64..1_000,
1192 2 => (1u64 << 53)..u64::MAX,
1193 5 => any::<u64>(),
1194 ];
1195 (
1196 seconds,
1197 prop_oneof![1 => Just(0u32), 3 => 0u32..1_000_000_000],
1198 )
1199 }
1200
1201 fn nanos() -> impl Strategy<Value = u64> {
1208 const DAY_NS: u64 = 24 * 60 * 60 * 1_000_000_000;
1209 prop_oneof![
1210 1 => Just(0u64),
1211 1 => Just(1u64),
1212 1 => Just(u64::MAX),
1213 1 => Just(DAY_NS),
1214 2 => 0u64..1_000,
1215 2 => 0u64..1_000_000_000,
1216 2 => 0u64..DAY_NS,
1217 6 => any::<u64>(),
1218 ]
1219 }
1220
1221 fn duration_like_text() -> impl Strategy<Value = String> {
1229 prop_oneof![
1230 2 => any::<String>(),
1231 3 => "[-+0-9. nsumhd\u{00b5}\u{03bc}]{0,40}",
1232 3 => "[0-9]{1,40}(ns|us|\u{00b5}s|\u{03bc}s|ms|s|m|h|d)",
1233 2 => "[0-9]{1,25}\\.[0-9]{1,25}(ns|ms|s|h|d)",
1234 2 => "[+-]?[0-9]{0,8}[a-z]{0,4}([0-9]{0,8}[a-z]{0,4}){0,3}",
1235 ]
1236 }
1237
1238 fn terms() -> impl Strategy<Value = Vec<(u32, usize)>> {
1243 prop::collection::vec((0u32..1_000, 0usize..UNITS.len()), 1..6)
1244 }
1245
1246 proptest! {
1247 #![proptest_config(ProptestConfig::with_cases(256))]
1248
1249 #[test]
1253 fn display_round_trips(nanos in nanos()) {
1254 let duration = ConfigDuration::from_nanos(nanos);
1255 let text = duration.to_string();
1256 prop_assert_eq!(
1257 text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1258 Ok(duration),
1259 "formatted as {:?}",
1260 text
1261 );
1262 }
1263
1264 #[test]
1269 fn display_round_trips_across_the_whole_range(
1270 (seconds, nanos) in seconds_and_nanos()
1271 ) {
1272 let duration = ConfigDuration::from(Duration::new(seconds, nanos));
1273 let text = duration.to_string();
1274 prop_assert_eq!(
1275 text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1276 Ok(duration),
1277 "formatted as {:?}",
1278 text
1279 );
1280 }
1281
1282 #[test]
1286 fn serde_agrees_with_from_str(nanos in nanos()) {
1287 let duration = ConfigDuration::from_nanos(nanos);
1288 let json = serde_json::to_string(&duration).unwrap();
1289 prop_assert_eq!(&json, &format!("\"{duration}\""));
1290 prop_assert_eq!(serde_json::from_str::<ConfigDuration>(&json).unwrap(), duration);
1291 prop_assert_eq!(
1292 json.trim_matches('"').parse::<ConfigDuration>().unwrap(),
1293 duration
1294 );
1295 }
1296
1297 #[test]
1302 fn parsing_never_panics(text in duration_like_text()) {
1303 let parsed = text.parse::<ConfigDuration>();
1304 if let Err(error) = parsed {
1308 prop_assert!(!error.to_string().is_empty());
1309 }
1310 }
1311
1312 #[test]
1315 fn terms_sum(terms in terms()) {
1316 let mut written = String::new();
1317 let mut sum = ConfigDuration::ZERO;
1318 for (value, unit) in &terms {
1319 let (unit, _) = UNITS[*unit];
1320 let term = format!("{value}{unit}");
1321 let term_duration: Duration = term.parse::<ConfigDuration>().unwrap().into();
1322 sum = ConfigDuration::from(Duration::from(sum) + term_duration);
1323 written.push_str(&term);
1324 }
1325 prop_assert_eq!(written.parse::<ConfigDuration>().unwrap(), sum);
1326 }
1327
1328 #[test]
1331 fn units_are_equivalent(count in 0u64..1_000_000) {
1332 let same = |smaller: String, larger: String| -> Result<(), TestCaseError> {
1333 prop_assert_eq!(
1334 smaller.parse::<ConfigDuration>().unwrap(),
1335 larger.parse::<ConfigDuration>().unwrap(),
1336 "{} and {} differ",
1337 smaller,
1338 larger
1339 );
1340 Ok(())
1341 };
1342 same(format!("{}ns", count * 1_000), format!("{count}us"))?;
1343 same(format!("{}us", count * 1_000), format!("{count}ms"))?;
1344 same(format!("{}ms", count * 1_000), format!("{count}s"))?;
1345 same(format!("{}s", count * 60), format!("{count}m"))?;
1346 same(format!("{}m", count * 60), format!("{count}h"))?;
1347 same(format!("{}h", count * 24), format!("{count}d"))?;
1348 same(format!("{count}us"), format!("{count}\u{00b5}s"))?;
1350 same(format!("{count}us"), format!("{count}\u{03bc}s"))?;
1351 }
1352
1353 #[test]
1356 fn ordering_follows_nanoseconds(left in nanos(), right in nanos()) {
1357 let parse = |nanos: u64| {
1358 ConfigDuration::from_nanos(nanos)
1359 .to_string()
1360 .parse::<ConfigDuration>()
1361 .unwrap()
1362 };
1363 prop_assert_eq!(parse(left).cmp(&parse(right)), left.cmp(&right));
1364 }
1365
1366 #[test]
1370 fn signs_behave(nanos in nanos()) {
1371 let text = ConfigDuration::from_nanos(nanos).to_string();
1372 prop_assert_eq!(
1373 format!("+{text}").parse::<ConfigDuration>().unwrap(),
1374 text.parse::<ConfigDuration>().unwrap()
1375 );
1376 prop_assert_eq!(
1377 format!("-{text}").parse::<ConfigDuration>().unwrap_err(),
1378 ParseError::Negative { input: format!("-{text}") }
1379 );
1380 }
1381
1382 #[test]
1387 fn fractional_terms_round(micros in 0u64..1_000_000, fraction in 0u64..10_000) {
1388 let text = format!("{micros}.{fraction:04}us");
1389 let expected = ConfigDuration::from_nanos(micros * 1_000 + (fraction + 5) / 10);
1390 prop_assert_eq!(text.parse::<ConfigDuration>().unwrap(), expected);
1391 }
1392 }
1393 }
1394}