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 use serde::de::value::F64Deserializer;
779
780 const SECOND: Duration = Duration::from_secs(1);
781 const MINUTE: Duration = Duration::from_secs(60);
782 const HOUR: Duration = Duration::from_secs(60 * 60);
783 const DAY: Duration = Duration::from_secs(24 * 60 * 60);
784
785 #[test]
786 fn parses_the_same_as_go() {
787 for (input, expected) in [
789 ("0", Duration::ZERO),
790 ("5s", 5 * SECOND),
791 ("30s", 30 * SECOND),
792 ("1478s", 1478 * SECOND),
793 ("100ns", Duration::from_nanos(100)),
794 ("11us", Duration::from_micros(11)),
795 ("11\u{00b5}s", Duration::from_micros(11)),
796 ("11\u{03bc}s", Duration::from_micros(11)),
797 ("1ms", Duration::from_millis(1)),
798 ("5.s", 5 * SECOND),
800 (".5s", Duration::from_millis(500)),
801 ("1h", HOUR),
802 ("1m", MINUTE),
803 ("3h30m", 3 * HOUR + 30 * MINUTE),
804 (
805 "10.5s4m",
806 4 * MINUTE + 10 * SECOND + Duration::from_millis(500),
807 ),
808 (
809 "1h2m3s4ms5us6ns",
810 HOUR + 2 * MINUTE
811 + 3 * SECOND
812 + Duration::from_millis(4)
813 + Duration::from_micros(5)
814 + Duration::from_nanos(6),
815 ),
816 (
817 "39h9m14.425s",
818 39 * HOUR + 9 * MINUTE + 14 * SECOND + Duration::from_millis(425),
819 ),
820 ("0.3333333333333333333h", 20 * MINUTE),
821 ] {
822 assert_eq!(
823 input.parse::<ConfigDuration>().unwrap(),
824 ConfigDuration(expected),
825 "parsing {input:?}"
826 );
827 }
828 }
829
830 #[test]
831 fn parses_days() {
832 assert_eq!(
833 "30d".parse::<ConfigDuration>().unwrap(),
834 ConfigDuration::from_days(30)
835 );
836 assert_eq!(
837 "1d12h".parse::<ConfigDuration>().unwrap(),
838 ConfigDuration(DAY + 12 * HOUR)
839 );
840 }
841
842 #[test]
843 fn rejects_bad_input() {
844 for input in [
845 "",
847 "+",
848 "++1s",
849 "-1s", "10",
851 "1s0",
852 "1h30", "10y",
854 "5sec",
855 "abc",
856 "1 s",
857 "5s ",
858 "1..2s",
859 "99999999999999999999999999s",
861 "184467440737095516160s",
862 "9223372036854775807d",
863 "1000000000000000000000d",
864 ] {
865 assert!(
866 input.parse::<ConfigDuration>().is_err(),
867 "{input:?} should not parse, got {:?}",
868 input.parse::<ConfigDuration>()
869 );
870 }
871 }
872
873 #[test]
876 fn a_unit_with_no_number_says_so() {
877 for (input, expected) in [
878 ("s", "`s` in duration `s` has no number in front of it"),
879 ("ms", "`ms` in duration `ms` has no number in front of it"),
880 ("forever", "unknown unit `forever`"),
881 ("1h ms", "unknown unit `h ms`"),
884 ] {
885 let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
886 assert!(
887 message.contains(expected),
888 "parsing {input:?} reported {message:?}"
889 );
890 }
891 }
892
893 #[test]
896 fn rejection_messages_quote_the_input() {
897 for (input, expected) in [
898 ("-1s", "duration `-1s` cannot be negative"),
899 ("10", "`10` in duration `10` carries no unit"),
900 ("5sec", "unknown unit `sec` in duration `5sec`"),
901 ("1 s", "unknown unit ` s` in duration `1 s`"),
903 ("99999999999999999999999999s", "is too large"),
904 ("", "empty duration"),
905 ] {
906 let message = input.parse::<ConfigDuration>().unwrap_err().to_string();
907 assert!(
908 message.contains(expected),
909 "parsing {input:?} reported {message:?}, which omits {expected:?}"
910 );
911 }
912 }
913
914 #[test]
918 fn accepts_the_largest_representable_duration() {
919 let max = format!("{}s999999999ns", u64::MAX);
920 let parsed: ConfigDuration = max.parse().unwrap();
921 assert_eq!(parsed, ConfigDuration::from(Duration::MAX));
922 assert_eq!(
923 parsed.to_string().parse::<ConfigDuration>().unwrap(),
924 parsed
925 );
926 let over = format!("{}s1000000000ns", u64::MAX);
927 assert!(matches!(
928 over.parse::<ConfigDuration>(),
929 Err(ParseError::Overflow { .. })
930 ));
931 }
932
933 #[test]
942 fn a_superseded_spelling_reads_any_whole_number() {
943 #[derive(Debug, serde::Deserialize)]
944 struct Config {
945 #[serde(default, alias = "nap_secs", deserialize_with = "duration_nap")]
946 nap: Option<ConfigDuration>,
947 }
948 crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
949
950 for json in [
951 r#"{"nap_secs": 10}"#,
952 r#"{"nap_secs": 10.0}"#,
953 r#"{"nap_secs": 1e1}"#,
954 ] {
955 let config: Config = serde_json::from_str(json).unwrap();
956 assert_eq!(
957 config.nap,
958 Some(ConfigDuration::from_secs(10)),
959 "parsing {json}"
960 );
961 }
962 let config: Config = serde_json::from_str(r#"{"nap_secs": 18446744073709551615}"#).unwrap();
965 assert!(config.nap.is_some());
966 for json in [
967 r#"{"nap_secs": 18446744073709551616}"#,
968 r#"{"nap_secs": 18446744073709551617}"#,
969 r#"{"nap_secs": 1.8446744073709552e19}"#,
970 ] {
971 let error = serde_json::from_str::<Config>(json)
972 .unwrap_err()
973 .to_string();
974 assert!(
975 error.contains("is neither"),
976 "parsing {json} reported {error}"
977 );
978 }
979
980 let whole = duration_nap(F64Deserializer::<de::value::Error>::new(10.0)).unwrap();
981 assert_eq!(whole, Some(ConfigDuration::from_secs(10)));
982
983 for (bad, quoted) in [
984 (r#"{"nap_secs": 10.5}"#, "`10.5`"),
985 (r#"{"nap_secs": -5}"#, "cannot be negative"),
986 (r#"{"nap_secs": {}}"#, "`{}`"),
987 (r#"{"nap_secs": 10.50}"#, "`10.50`"),
989 (r#"{"nap_secs": {"secs": 1}}"#, "`an object`"),
990 ] {
991 let error = serde_json::from_str::<Config>(bad).unwrap_err().to_string();
992 assert!(error.contains(quoted), "parsing {bad} reported {error}");
993 assert!(
994 !error.contains("invalid type: map"),
995 "parsing {bad} reported {error}"
996 );
997 }
998 let error = duration_nap(F64Deserializer::<de::value::Error>::new(10.5))
999 .unwrap_err()
1000 .to_string();
1001 assert!(error.contains("`10.5`"), "{error}");
1002 }
1003
1004 #[test]
1007 fn from_days_saturates() {
1008 assert_eq!(
1009 ConfigDuration::from_days(2),
1010 ConfigDuration::from_secs(2 * 86_400)
1011 );
1012 assert_eq!(
1013 ConfigDuration::from_days(u64::MAX),
1014 ConfigDuration::from_secs(u64::MAX)
1015 );
1016 }
1017
1018 #[test]
1023 fn the_no_limit_value_is_read_without_a_warning() {
1024 use std::sync::atomic::{AtomicBool, Ordering};
1025 let warned = AtomicBool::new(false);
1026 let max = duration_from_legacy_number::<serde_json::Error>(
1027 &warned,
1028 "max_output_buffer_time",
1029 LegacyUnit::Millis,
1030 u64::MAX,
1031 )
1032 .unwrap();
1033 assert_eq!(max, ConfigDuration::from_millis(u64::MAX));
1034 assert!(!warned.load(Ordering::Relaxed));
1035
1036 duration_from_legacy_number::<serde_json::Error>(
1037 &warned,
1038 "max_output_buffer_time",
1039 LegacyUnit::Millis,
1040 500,
1041 )
1042 .unwrap();
1043 assert!(warned.load(Ordering::Relaxed));
1044 }
1045
1046 #[test]
1050 fn fractions_scale_exactly() {
1051 const DAY_NANOS: u128 = 24 * 60 * 60 * 1_000_000_000;
1052 let digits = "718656392856533598";
1053 let exact = (DAY_NANOS * digits.parse::<u128>().unwrap()
1054 + 10u128.pow(digits.len() as u32) / 2)
1055 / 10u128.pow(digits.len() as u32);
1056 assert_eq!(exact, 62_091_912_342_805);
1057
1058 let parsed: ConfigDuration = format!("0.{digits}d").parse().unwrap();
1059 assert_eq!(Duration::from(parsed).as_nanos(), exact);
1060
1061 assert_eq!(
1063 "0.5s".parse::<ConfigDuration>().unwrap(),
1064 ConfigDuration::from_millis(500)
1065 );
1066 assert_eq!(
1067 "1.5s".parse::<ConfigDuration>().unwrap(),
1068 ConfigDuration::from_millis(1500)
1069 );
1070 assert_eq!(
1071 "0.0000000005s".parse::<ConfigDuration>().unwrap(),
1072 ConfigDuration::from_nanos(1)
1073 );
1074 }
1075
1076 #[test]
1080 fn writing_both_spellings_is_rejected() {
1081 #[derive(Debug, serde::Deserialize)]
1082 struct Config {
1083 #[serde(
1084 default,
1085 alias = "nap_secs",
1086 deserialize_with = "duration_nap",
1087 skip_serializing_if = "Option::is_none"
1088 )]
1089 nap: Option<ConfigDuration>,
1090 }
1091 crate::duration_setting!(duration_nap, "nap", LegacyUnit::Secs);
1092
1093 assert_eq!(
1094 serde_json::from_str::<Config>(r#"{"nap": "30s"}"#)
1095 .unwrap()
1096 .nap,
1097 Some(ConfigDuration::from_secs(30))
1098 );
1099 assert_eq!(
1100 serde_json::from_str::<Config>(r#"{"nap_secs": 30}"#)
1101 .unwrap()
1102 .nap,
1103 Some(ConfigDuration::from_secs(30))
1104 );
1105 let error = serde_json::from_str::<Config>(r#"{"nap": "30s", "nap_secs": 30}"#)
1106 .unwrap_err()
1107 .to_string();
1108 assert!(error.contains("duplicate field `nap`"), "{error}");
1109 }
1110
1111 #[test]
1117 fn large_values_round_trip_exactly() {
1118 let written = "128644735584426d23h5m38s";
1119 let parsed: ConfigDuration = written.parse().unwrap();
1120 assert_eq!(parsed.to_string(), written);
1121 assert_eq!(
1122 parsed.as_secs(),
1123 128_644_735_584_426 * 24 * 60 * 60 + 23 * 60 * 60 + 5 * 60 + 38
1124 );
1125 assert_eq!(
1126 "11114905154494489538s".parse::<ConfigDuration>().unwrap(),
1127 parsed
1128 );
1129 }
1130
1131 #[test]
1132 fn displays_in_decomposed_units() {
1133 for (duration, expected) in [
1134 (ConfigDuration::ZERO, "0s"),
1135 (ConfigDuration::from_days(30), "30d"),
1136 (ConfigDuration::from_secs(3600), "1h"),
1137 (ConfigDuration::from_secs(100), "1m40s"),
1138 (ConfigDuration::from_millis(500), "500ms"),
1139 (ConfigDuration::from_micros(1_000_000), "1s"),
1140 (ConfigDuration::from_nanos(1), "1ns"),
1141 (ConfigDuration(HOUR + 30 * MINUTE + 10 * SECOND), "1h30m10s"),
1142 ] {
1143 assert_eq!(duration.to_string(), expected);
1144 }
1145 }
1146
1147 #[test]
1148 fn round_trips_through_json() {
1149 for text in [
1150 "0s", "30d", "1h", "1m30s", "500ms", "1ns", "1h30m10s", "1d12h",
1151 ] {
1152 let json = format!("\"{text}\"");
1153 let duration: ConfigDuration = serde_json::from_str(&json).unwrap();
1154 assert_eq!(serde_json::to_string(&duration).unwrap(), json);
1155 }
1156 }
1157
1158 mod properties {
1165 use super::*;
1166 use proptest::prelude::*;
1167
1168 const UNITS: [(&str, u64); 7] = [
1170 ("ns", 1),
1171 ("us", 1_000),
1172 ("ms", 1_000_000),
1173 ("s", 1_000_000_000),
1174 ("m", 60 * 1_000_000_000),
1175 ("h", 60 * 60 * 1_000_000_000),
1176 ("d", 24 * 60 * 60 * 1_000_000_000),
1177 ];
1178
1179 fn seconds_and_nanos() -> impl Strategy<Value = (u64, u32)> {
1188 let seconds = prop_oneof![
1189 1 => Just(0u64),
1190 1 => Just(u64::MAX),
1191 1 => Just(11_114_905_154_334_422_338u64),
1192 2 => 0u64..1_000,
1193 2 => (1u64 << 53)..u64::MAX,
1194 5 => any::<u64>(),
1195 ];
1196 (
1197 seconds,
1198 prop_oneof![1 => Just(0u32), 3 => 0u32..1_000_000_000],
1199 )
1200 }
1201
1202 fn nanos() -> impl Strategy<Value = u64> {
1209 const DAY_NS: u64 = 24 * 60 * 60 * 1_000_000_000;
1210 prop_oneof![
1211 1 => Just(0u64),
1212 1 => Just(1u64),
1213 1 => Just(u64::MAX),
1214 1 => Just(DAY_NS),
1215 2 => 0u64..1_000,
1216 2 => 0u64..1_000_000_000,
1217 2 => 0u64..DAY_NS,
1218 6 => any::<u64>(),
1219 ]
1220 }
1221
1222 fn duration_like_text() -> impl Strategy<Value = String> {
1230 prop_oneof![
1231 2 => any::<String>(),
1232 3 => "[-+0-9. nsumhd\u{00b5}\u{03bc}]{0,40}",
1233 3 => "[0-9]{1,40}(ns|us|\u{00b5}s|\u{03bc}s|ms|s|m|h|d)",
1234 2 => "[0-9]{1,25}\\.[0-9]{1,25}(ns|ms|s|h|d)",
1235 2 => "[+-]?[0-9]{0,8}[a-z]{0,4}([0-9]{0,8}[a-z]{0,4}){0,3}",
1236 ]
1237 }
1238
1239 fn terms() -> impl Strategy<Value = Vec<(u32, usize)>> {
1244 prop::collection::vec((0u32..1_000, 0usize..UNITS.len()), 1..6)
1245 }
1246
1247 proptest! {
1248 #![proptest_config(ProptestConfig::with_cases(256))]
1249
1250 #[test]
1254 fn display_round_trips(nanos in nanos()) {
1255 let duration = ConfigDuration::from_nanos(nanos);
1256 let text = duration.to_string();
1257 prop_assert_eq!(
1258 text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1259 Ok(duration),
1260 "formatted as {:?}",
1261 text
1262 );
1263 }
1264
1265 #[test]
1270 fn display_round_trips_across_the_whole_range(
1271 (seconds, nanos) in seconds_and_nanos()
1272 ) {
1273 let duration = ConfigDuration::from(Duration::new(seconds, nanos));
1274 let text = duration.to_string();
1275 prop_assert_eq!(
1276 text.parse::<ConfigDuration>().map_err(|e| e.to_string()),
1277 Ok(duration),
1278 "formatted as {:?}",
1279 text
1280 );
1281 }
1282
1283 #[test]
1287 fn serde_agrees_with_from_str(nanos in nanos()) {
1288 let duration = ConfigDuration::from_nanos(nanos);
1289 let json = serde_json::to_string(&duration).unwrap();
1290 prop_assert_eq!(&json, &format!("\"{duration}\""));
1291 prop_assert_eq!(serde_json::from_str::<ConfigDuration>(&json).unwrap(), duration);
1292 prop_assert_eq!(
1293 json.trim_matches('"').parse::<ConfigDuration>().unwrap(),
1294 duration
1295 );
1296 }
1297
1298 #[test]
1303 fn parsing_never_panics(text in duration_like_text()) {
1304 let parsed = text.parse::<ConfigDuration>();
1305 if let Err(error) = parsed {
1309 prop_assert!(!error.to_string().is_empty());
1310 }
1311 }
1312
1313 #[test]
1316 fn terms_sum(terms in terms()) {
1317 let mut written = String::new();
1318 let mut sum = ConfigDuration::ZERO;
1319 for (value, unit) in &terms {
1320 let (unit, _) = UNITS[*unit];
1321 let term = format!("{value}{unit}");
1322 let term_duration: Duration = term.parse::<ConfigDuration>().unwrap().into();
1323 sum = ConfigDuration::from(Duration::from(sum) + term_duration);
1324 written.push_str(&term);
1325 }
1326 prop_assert_eq!(written.parse::<ConfigDuration>().unwrap(), sum);
1327 }
1328
1329 #[test]
1332 fn units_are_equivalent(count in 0u64..1_000_000) {
1333 let same = |smaller: String, larger: String| -> Result<(), TestCaseError> {
1334 prop_assert_eq!(
1335 smaller.parse::<ConfigDuration>().unwrap(),
1336 larger.parse::<ConfigDuration>().unwrap(),
1337 "{} and {} differ",
1338 smaller,
1339 larger
1340 );
1341 Ok(())
1342 };
1343 same(format!("{}ns", count * 1_000), format!("{count}us"))?;
1344 same(format!("{}us", count * 1_000), format!("{count}ms"))?;
1345 same(format!("{}ms", count * 1_000), format!("{count}s"))?;
1346 same(format!("{}s", count * 60), format!("{count}m"))?;
1347 same(format!("{}m", count * 60), format!("{count}h"))?;
1348 same(format!("{}h", count * 24), format!("{count}d"))?;
1349 same(format!("{count}us"), format!("{count}\u{00b5}s"))?;
1351 same(format!("{count}us"), format!("{count}\u{03bc}s"))?;
1352 }
1353
1354 #[test]
1357 fn ordering_follows_nanoseconds(left in nanos(), right in nanos()) {
1358 let parse = |nanos: u64| {
1359 ConfigDuration::from_nanos(nanos)
1360 .to_string()
1361 .parse::<ConfigDuration>()
1362 .unwrap()
1363 };
1364 prop_assert_eq!(parse(left).cmp(&parse(right)), left.cmp(&right));
1365 }
1366
1367 #[test]
1371 fn signs_behave(nanos in nanos()) {
1372 let text = ConfigDuration::from_nanos(nanos).to_string();
1373 prop_assert_eq!(
1374 format!("+{text}").parse::<ConfigDuration>().unwrap(),
1375 text.parse::<ConfigDuration>().unwrap()
1376 );
1377 prop_assert_eq!(
1378 format!("-{text}").parse::<ConfigDuration>().unwrap_err(),
1379 ParseError::Negative { input: format!("-{text}") }
1380 );
1381 }
1382
1383 #[test]
1388 fn fractional_terms_round(micros in 0u64..1_000_000, fraction in 0u64..10_000) {
1389 let text = format!("{micros}.{fraction:04}us");
1390 let expected = ConfigDuration::from_nanos(micros * 1_000 + (fraction + 5) / 10);
1391 prop_assert_eq!(text.parse::<ConfigDuration>().unwrap(), expected);
1392 }
1393 }
1394 }
1395}