1use std::{fmt, str::FromStr};
16
17use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
18
19#[derive(Copy, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
27pub struct ConfigSize(u64);
28
29const EXPECTED_UNITS: &str = "expected one of 'k', 'M', 'G', 'T', 'P', 'E', 'Ki', 'Mi', 'Gi', \
32 'Ti', 'Pi', 'Ei', each with or without a trailing 'B'";
33
34#[derive(Debug, thiserror::Error, Eq, PartialEq)]
39#[non_exhaustive]
40pub enum ParseError {
41 #[error("empty size: write a number of bytes, or a number and a unit such as `512Mi`")]
43 Empty,
44
45 #[error("unknown unit `{unit}` in size `{input}`: {EXPECTED_UNITS}")]
47 InvalidUnit { unit: String, input: String },
48
49 #[error("`{unit}` in size `{input}` has no number in front of it")]
51 MissingNumber { unit: String, input: String },
52 #[error("size `{input}` has no digits")]
54 NoDigits { input: String },
55
56 #[error("size `{input}` cannot be negative")]
59 Negative { input: String },
60
61 #[error("size `{input}` is too large: at most {} bytes", u64::MAX)]
63 Overflow { input: String },
64}
65
66impl ConfigSize {
67 pub const ZERO: ConfigSize = ConfigSize(0);
68
69 pub const MAX: ConfigSize = ConfigSize(u64::MAX);
71
72 pub const fn from_bytes(bytes: u64) -> Self {
73 Self(bytes)
74 }
75
76 pub const fn from_kib(kib: u64) -> Self {
78 Self(kib.saturating_mul(1 << 10))
79 }
80
81 pub const fn from_mib(mib: u64) -> Self {
83 Self(mib.saturating_mul(1 << 20))
84 }
85
86 pub const fn from_gib(gib: u64) -> Self {
88 Self(gib.saturating_mul(1 << 30))
89 }
90
91 pub const fn from_mb(mb: u64) -> Self {
93 Self(mb.saturating_mul(1_000_000))
94 }
95
96 pub const fn as_bytes(self) -> u64 {
97 self.0
98 }
99
100 pub const fn as_usize(self) -> usize {
103 if self.0 > usize::MAX as u64 {
104 usize::MAX
105 } else {
106 self.0 as usize
107 }
108 }
109
110 pub const fn is_zero(self) -> bool {
111 self.0 == 0
112 }
113
114 pub const fn saturating_sub(self, other: Self) -> Self {
115 Self(self.0.saturating_sub(other.0))
116 }
117}
118
119impl From<u64> for ConfigSize {
120 fn from(bytes: u64) -> Self {
121 Self(bytes)
122 }
123}
124
125impl From<ConfigSize> for u64 {
126 fn from(ConfigSize(bytes): ConfigSize) -> Self {
127 bytes
128 }
129}
130
131impl PartialEq<u64> for ConfigSize {
132 fn eq(&self, other: &u64) -> bool {
133 self.0 == *other
134 }
135}
136
137impl PartialOrd<u64> for ConfigSize {
138 fn partial_cmp(&self, other: &u64) -> Option<std::cmp::Ordering> {
139 self.0.partial_cmp(other)
140 }
141}
142
143const UNITS: [(&str, u128); 13] = [
146 ("Ki", 1 << 10),
147 ("Mi", 1 << 20),
148 ("Gi", 1 << 30),
149 ("Ti", 1 << 40),
150 ("Pi", 1 << 50),
151 ("Ei", 1 << 60),
152 ("k", 1_000),
153 ("K", 1_000),
156 ("M", 1_000_000),
157 ("G", 1_000_000_000),
158 ("T", 1_000_000_000_000),
159 ("P", 1_000_000_000_000_000),
160 ("E", 1_000_000_000_000_000_000),
161];
162
163const MAX_FRACTION_DIGITS: usize = 18;
170
171impl FromStr for ConfigSize {
172 type Err = ParseError;
173
174 fn from_str(s: &str) -> Result<Self, Self::Err> {
175 Self::from_str_with_unit(s).map(|(size, _has_unit)| size)
176 }
177}
178
179impl ConfigSize {
180 pub fn from_str_with_unit(s: &str) -> Result<(Self, bool), ParseError> {
188 let input = s;
189 let overflow = || ParseError::Overflow {
190 input: input.to_string(),
191 };
192
193 if input.starts_with('-') {
194 return Err(ParseError::Negative {
195 input: input.to_string(),
196 });
197 }
198 let body = input.strip_prefix('+').unwrap_or(input);
200 if body.is_empty() {
201 return Err(ParseError::Empty);
202 }
203
204 let whole_end = body
206 .bytes()
207 .position(|b| !b.is_ascii_digit())
208 .unwrap_or(body.len());
209 let (whole, mut rest) = body.split_at(whole_end);
210 let mut fraction = "";
211 if let Some(after_point) = rest.strip_prefix('.') {
212 let fraction_end = after_point
213 .bytes()
214 .position(|b| !b.is_ascii_digit())
215 .unwrap_or(after_point.len());
216 (fraction, rest) = after_point.split_at(fraction_end);
217 }
218 let unit = rest;
219
220 if whole.is_empty() && fraction.is_empty() {
221 return Err(if unit.is_empty() {
225 ParseError::NoDigits {
226 input: input.to_string(),
227 }
228 } else if unit_bytes(unit).is_some() {
229 ParseError::MissingNumber {
230 unit: unit.to_string(),
231 input: input.to_string(),
232 }
233 } else {
234 ParseError::InvalidUnit {
235 unit: unit.to_string(),
236 input: input.to_string(),
237 }
238 });
239 }
240 let Some(bytes_per_unit) = unit_bytes(unit) else {
241 return Err(ParseError::InvalidUnit {
242 unit: unit.to_string(),
243 input: input.to_string(),
244 });
245 };
246
247 let whole: u128 = if whole.is_empty() {
249 0
250 } else {
251 whole.parse().map_err(|_| overflow())?
252 };
253 let mut total = whole.checked_mul(bytes_per_unit).ok_or_else(overflow)?;
254
255 if !fraction.is_empty() {
256 let kept = fraction.len().min(MAX_FRACTION_DIGITS);
260 let numerator: u128 = fraction[..kept].parse().map_err(|_| overflow())?;
261 let denominator = 10u128.pow(kept as u32);
262 let scaled = bytes_per_unit.checked_mul(numerator).ok_or_else(overflow)?;
263 let rounded = (scaled + denominator / 2) / denominator;
264 total = total.checked_add(rounded).ok_or_else(overflow)?;
265 }
266
267 let size = u64::try_from(total)
268 .map(ConfigSize)
269 .map_err(|_| overflow())?;
270 Ok((size, !unit.is_empty()))
271 }
272}
273
274fn unit_bytes(unit: &str) -> Option<u128> {
277 let unit = unit.strip_suffix('B').unwrap_or(unit);
278 if unit.is_empty() {
279 return Some(1);
280 }
281 UNITS
282 .iter()
283 .find(|(name, _)| *name == unit)
284 .map(|&(_, bytes)| bytes)
285}
286
287impl fmt::Display for ConfigSize {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 let bytes = u128::from(self.0);
293 if bytes == 0 {
294 return f.write_str("0");
295 }
296 let mut best: (u128, &str) = (bytes, "");
297 for &(unit, base) in UNITS.iter().filter(|(name, _)| *name != "K") {
299 if bytes % base == 0 && bytes / base < best.0 {
300 best = (bytes / base, unit);
301 }
302 }
303 write!(f, "{}{}", best.0, best.1)
304 }
305}
306
307impl fmt::Debug for ConfigSize {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 fmt::Display::fmt(self, f)
310 }
311}
312
313impl Serialize for ConfigSize {
314 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
319 let text = self.to_string();
320 if text.bytes().all(|b| b.is_ascii_digit()) {
321 serializer.collect_str(&format_args!("{text}B"))
322 } else {
323 serializer.serialize_str(&text)
324 }
325 }
326}
327
328impl<'de> Deserialize<'de> for ConfigSize {
329 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
330 struct Visitor;
331
332 impl de::Visitor<'_> for Visitor {
333 type Value = ConfigSize;
334
335 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 f.write_str("a size such as \"500M\", \"512Mi\" or \"4096\"")
337 }
338
339 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
340 value.parse::<ConfigSize>().map_err(de::Error::custom)
341 }
342 }
343
344 deserializer.deserialize_str(Visitor)
345 }
346}
347
348#[derive(Clone, Copy, Debug, Eq, PartialEq)]
358pub enum LegacySizeUnit {
359 Bytes,
360 Megabytes,
362 Mebibytes,
364}
365
366impl LegacySizeUnit {
367 pub const fn bytes(self) -> u64 {
369 match self {
370 LegacySizeUnit::Bytes => 1,
371 LegacySizeUnit::Megabytes => 1_000_000,
372 LegacySizeUnit::Mebibytes => 1 << 20,
373 }
374 }
375}
376
377pub fn size_from_legacy_number<E: de::Error>(
387 warned: &std::sync::atomic::AtomicBool,
388 field: &str,
389 unit: LegacySizeUnit,
390 value: u64,
391) -> Result<ConfigSize, E> {
392 let size = ConfigSize(value.saturating_mul(unit.bytes()));
393 if value != u64::MAX && !warned.swap(true, std::sync::atomic::Ordering::Relaxed) {
397 log::warn!(
398 "configuration field `{field}` was given the bare number {value}, which is \
399 deprecated and is removed no earlier than release 0.369.0; write \
400 `\"{size}\"` instead"
401 );
402 }
403 Ok(size)
404}
405
406fn whole_number(value: f64) -> Option<u64> {
409 const TWO_TO_THE_64: f64 = 18_446_744_073_709_551_616.0;
412 (value.is_finite() && value >= 0.0 && value.fract() == 0.0 && value < TWO_TO_THE_64)
413 .then_some(value as u64)
414}
415
416pub fn size_or_legacy_number<'de, D>(
427 deserializer: D,
428 warned: &std::sync::atomic::AtomicBool,
429 field: &'static str,
430 unit: LegacySizeUnit,
431) -> Result<Option<ConfigSize>, D::Error>
432where
433 D: Deserializer<'de>,
434{
435 struct Visitor<'a> {
436 warned: &'a std::sync::atomic::AtomicBool,
437 field: &'static str,
438 unit: LegacySizeUnit,
439 }
440
441 impl Visitor<'_> {
442 fn not_a_number<E: de::Error>(field: &str, value: &str) -> E {
444 de::Error::custom(format!(
445 "`{field}` expects a size such as \"512Mi\", or a whole number of the unit \
446 its earlier spelling took; `{value}` is neither"
447 ))
448 }
449 }
450
451 impl<'de> de::Visitor<'de> for Visitor<'_> {
452 type Value = Option<ConfigSize>;
453
454 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455 f.write_str("a size such as \"500M\", \"512Mi\" or \"4096\"")
456 }
457
458 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
459 let (size, has_unit) =
460 ConfigSize::from_str_with_unit(value).map_err(de::Error::custom)?;
461 if !has_unit && self.unit != LegacySizeUnit::Bytes {
462 let unit = match self.unit {
463 LegacySizeUnit::Bytes => "",
464 LegacySizeUnit::Megabytes => "M",
465 LegacySizeUnit::Mebibytes => "Mi",
466 };
467 return Err(de::Error::custom(format!(
468 "`{}` expects a size with a unit, such as \"{value}{unit}\"; \"{value}\" \
469 has none, and a bare number counts {} only as the number {value}, \
470 without quotes",
471 self.field,
472 match self.unit {
473 LegacySizeUnit::Bytes => "bytes",
474 LegacySizeUnit::Megabytes => "megabytes",
475 LegacySizeUnit::Mebibytes => "mebibytes",
476 }
477 )));
478 }
479 Ok(Some(size))
480 }
481
482 fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
483 size_from_legacy_number(self.warned, self.field, self.unit, value).map(Some)
484 }
485
486 fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
487 let value = u64::try_from(value)
488 .map_err(|_| de::Error::custom(format!("`{}` cannot be negative", self.field)))?;
489 self.visit_u64(value)
490 }
491
492 fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
493 match whole_number(value) {
494 Some(whole) => self.visit_u64(whole),
495 None => Err(Self::not_a_number(self.field, &value.to_string())),
496 }
497 }
498
499 fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
503 const NUMBER: &str = "$serde_json::private::Number";
504
505 let Some(key) = map.next_key::<String>()? else {
506 return Err(Self::not_a_number(self.field, "{}"));
507 };
508 if key != NUMBER {
509 return Err(Self::not_a_number(self.field, "an object"));
510 }
511 let text = map.next_value::<String>()?;
514 match text.parse::<f64>().ok().and_then(whole_number) {
515 Some(whole) => self.visit_u64(whole),
516 None if text
518 .parse::<f64>()
519 .is_ok_and(|v| v >= 18_446_744_073_709_551_616.0) =>
520 {
521 Err(de::Error::custom(format!(
522 "`{}` is too large: at most {} of its unit",
523 self.field,
524 u64::MAX
525 )))
526 }
527 None => Err(Self::not_a_number(self.field, &text)),
528 }
529 }
530
531 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
533 Ok(None)
534 }
535 }
536
537 deserializer.deserialize_any(Visitor {
538 warned,
539 field,
540 unit,
541 })
542}
543
544pub fn required_size_or_legacy_number<'de, D>(
547 deserializer: D,
548 warned: &std::sync::atomic::AtomicBool,
549 field: &'static str,
550 unit: LegacySizeUnit,
551) -> Result<ConfigSize, D::Error>
552where
553 D: Deserializer<'de>,
554{
555 size_or_legacy_number(deserializer, warned, field, unit)?
556 .ok_or_else(|| de::Error::custom(format!("`{field}` cannot be null")))
557}
558
559#[doc(hidden)]
566#[macro_export]
567macro_rules! size_setting {
568 ($name:ident, $field:literal, $unit:expr) => {
569 fn $name<'de, D>(
570 deserializer: D,
571 ) -> ::std::result::Result<Option<$crate::size::ConfigSize>, D::Error>
572 where
573 D: ::serde::Deserializer<'de>,
574 {
575 static WARNED: ::std::sync::atomic::AtomicBool =
576 ::std::sync::atomic::AtomicBool::new(false);
577 $crate::size::size_or_legacy_number(deserializer, &WARNED, $field, $unit)
578 }
579 };
580}
581
582#[doc(hidden)]
584#[macro_export]
585macro_rules! required_size_setting {
586 ($name:ident, $field:literal, $unit:expr) => {
587 fn $name<'de, D>(
588 deserializer: D,
589 ) -> ::std::result::Result<$crate::size::ConfigSize, D::Error>
590 where
591 D: ::serde::Deserializer<'de>,
592 {
593 static WARNED: ::std::sync::atomic::AtomicBool =
594 ::std::sync::atomic::AtomicBool::new(false);
595 $crate::size::required_size_or_legacy_number(deserializer, &WARNED, $field, $unit)
596 }
597 };
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603
604 const KIB: u64 = 1 << 10;
605 const MIB: u64 = 1 << 20;
606 const GIB: u64 = 1 << 30;
607
608 #[test]
609 fn parses_kubernetes_quantities() {
610 for (input, expected) in [
611 ("0", 0),
612 ("4096", 4096),
613 ("4096B", 4096),
614 ("+4096", 4096),
615 ("1k", 1_000),
616 ("1K", 1_000),
617 ("1kB", 1_000),
618 ("1Ki", KIB),
619 ("1KiB", KIB),
620 ("500M", 500_000_000),
621 ("512Mi", 512 * MIB),
622 ("512MiB", 512 * MIB),
623 ("1G", 1_000_000_000),
624 ("1Gi", GIB),
625 ("1T", 1_000_000_000_000),
626 ("1Ti", 1 << 40),
627 ("1P", 1_000_000_000_000_000),
628 ("1Pi", 1 << 50),
629 ("1E", 1_000_000_000_000_000_000),
630 ("1Ei", 1 << 60),
631 ("15Ei", 15 << 60),
632 ("18446744073709551615", u64::MAX),
633 ] {
634 assert_eq!(
635 input.parse::<ConfigSize>().map(ConfigSize::as_bytes),
636 Ok(expected),
637 "parsing {input}"
638 );
639 }
640 }
641
642 #[test]
643 fn fractions_scale_exactly() {
644 for (input, expected) in [
645 ("1.5Gi", GIB + GIB / 2),
646 ("0.5Mi", MIB / 2),
647 ("2.5k", 2_500),
648 ("1.Gi", GIB),
649 (".5Gi", GIB / 2),
650 ("0.5", 1),
652 ("0.4", 0),
653 ("1.0005k", 1_001),
654 ("1.0004k", 1_000),
655 ("0.0000000000000000001Ei", 0),
657 ("1.000000000000000001Ei", (1 << 60) + 1),
658 ] {
659 assert_eq!(
660 input.parse::<ConfigSize>().map(ConfigSize::as_bytes),
661 Ok(expected),
662 "parsing {input}"
663 );
664 }
665 }
666
667 #[test]
668 fn rejects_bad_input() {
669 use ParseError::*;
670 let input = |s: &str| s.to_string();
671 for (text, expected) in [
672 ("", Empty),
673 ("+", Empty),
674 (
675 "-1Gi",
676 Negative {
677 input: input("-1Gi"),
678 },
679 ),
680 (
681 "--1",
682 Negative {
683 input: input("--1"),
684 },
685 ),
686 (
687 "++1",
688 InvalidUnit {
689 unit: input("+1"),
690 input: input("++1"),
691 },
692 ),
693 (
694 "1m",
695 InvalidUnit {
696 unit: input("m"),
697 input: input("1m"),
698 },
699 ),
700 (
701 "1g",
702 InvalidUnit {
703 unit: input("g"),
704 input: input("1g"),
705 },
706 ),
707 (
708 "1b",
709 InvalidUnit {
710 unit: input("b"),
711 input: input("1b"),
712 },
713 ),
714 (
715 "1MB ",
716 InvalidUnit {
717 unit: input("MB "),
718 input: input("1MB "),
719 },
720 ),
721 (
722 "1 Mi",
723 InvalidUnit {
724 unit: input(" Mi"),
725 input: input("1 Mi"),
726 },
727 ),
728 (
729 "1Gi512Mi",
730 InvalidUnit {
731 unit: input("Gi512Mi"),
732 input: input("1Gi512Mi"),
733 },
734 ),
735 (
736 "1e3",
737 InvalidUnit {
738 unit: input("e3"),
739 input: input("1e3"),
740 },
741 ),
742 (
743 "1..2",
744 InvalidUnit {
745 unit: input(".2"),
746 input: input("1..2"),
747 },
748 ),
749 (
750 "lots",
751 InvalidUnit {
752 unit: input("lots"),
753 input: input("lots"),
754 },
755 ),
756 (
757 "Mi",
758 MissingNumber {
759 unit: input("Mi"),
760 input: input("Mi"),
761 },
762 ),
763 (
764 "B",
765 MissingNumber {
766 unit: input("B"),
767 input: input("B"),
768 },
769 ),
770 (".", NoDigits { input: input(".") }),
771 (
772 "18446744073709551616",
773 Overflow {
774 input: input("18446744073709551616"),
775 },
776 ),
777 (
778 "16Ei",
779 Overflow {
780 input: input("16Ei"),
781 },
782 ),
783 (
784 "19E",
785 Overflow {
786 input: input("19E"),
787 },
788 ),
789 (
790 "1000000000000000000000000000000000000000000Ei",
791 Overflow {
792 input: input("1000000000000000000000000000000000000000000Ei"),
793 },
794 ),
795 ] {
796 assert_eq!(
797 text.parse::<ConfigSize>(),
798 Err(expected),
799 "parsing {text:?}"
800 );
801 }
802 }
803
804 #[test]
805 fn rejection_messages_quote_the_input() {
806 let error = "1g".parse::<ConfigSize>().unwrap_err().to_string();
807 assert!(error.contains("`g`") && error.contains("`1g`"), "{error}");
808 assert!(error.contains("'Gi'") && error.contains("'B'"), "{error}");
809 let error = "Mi".parse::<ConfigSize>().unwrap_err().to_string();
810 assert!(error.contains("no number in front"), "{error}");
811 let error = "16Ei".parse::<ConfigSize>().unwrap_err().to_string();
812 assert!(error.contains("too large"), "{error}");
813 }
814
815 #[test]
818 fn units_are_listed_in_messages() {
819 for (unit, _) in UNITS.iter().filter(|(name, _)| *name != "K") {
820 assert!(EXPECTED_UNITS.contains(&format!("'{unit}'")), "{unit}");
821 }
822 }
823
824 #[test]
825 fn displays_in_the_largest_exact_unit() {
826 for (bytes, expected) in [
827 (0, "0"),
828 (1, "1"),
829 (999, "999"),
830 (1_000, "1k"),
831 (1_024, "1Ki"),
832 (1_500, "1500"),
833 (1_000_000, "1M"),
834 (MIB, "1Mi"),
835 (MIB + MIB / 2, "1536Ki"),
836 (500_000_000, "500M"),
837 (GIB, "1Gi"),
838 (1_024_000_000, "1024M"),
840 (1 << 60, "1Ei"),
841 (1_000_000_000_000_000_000, "1E"),
842 (u64::MAX, "18446744073709551615"),
843 ] {
844 assert_eq!(
845 ConfigSize::from_bytes(bytes).to_string(),
846 expected,
847 "{bytes} bytes"
848 );
849 }
850 }
851
852 #[test]
853 fn round_trips_through_json() {
854 for (text, written) in [
855 ("0", "0B"),
856 ("0B", "0B"),
857 ("4095", "4095B"),
858 ("1.1Gi", "1181116006B"),
859 ("1k", "1k"),
860 ("512Mi", "512Mi"),
861 ("1Gi", "1Gi"),
862 ("1536Ki", "1536Ki"),
863 ("1024M", "1024M"),
864 ("1Ei", "1Ei"),
865 ] {
866 let size: ConfigSize = serde_json::from_str(&format!("\"{text}\"")).unwrap();
867 let json = serde_json::to_string(&size).unwrap();
868 assert_eq!(json, format!("\"{written}\""), "{text}");
869 assert_eq!(serde_json::from_str::<ConfigSize>(&json).unwrap(), size);
870 }
871 let error = serde_json::from_str::<ConfigSize>("4096")
873 .unwrap_err()
874 .to_string();
875 assert!(error.contains("a size such as"), "{error}");
876 }
877
878 #[test]
879 fn constructors_saturate() {
880 assert_eq!(ConfigSize::from_mib(u64::MAX), ConfigSize::MAX);
881 assert_eq!(ConfigSize::from_mb(u64::MAX), ConfigSize::MAX);
882 assert_eq!(ConfigSize::from_gib(3).as_bytes(), 3 * GIB);
883 assert_eq!(ConfigSize::from_mb(16_000).as_bytes(), 16_000_000_000);
884 assert_eq!(ConfigSize::from_mib(256).as_bytes(), 256 << 20);
885 assert_eq!(ConfigSize::MAX.as_usize(), usize::MAX);
886 }
887
888 #[test]
894 fn a_superseded_spelling_reads_any_whole_number() {
895 #[derive(Debug, serde::Deserialize)]
896 struct Config {
897 #[serde(default, alias = "cap_mb", deserialize_with = "size_cap")]
898 cap: Option<ConfigSize>,
899 }
900 crate::size_setting!(size_cap, "cap", LegacySizeUnit::Megabytes);
901
902 for json in [
903 r#"{"cap_mb": 10}"#,
904 r#"{"cap_mb": 10.0}"#,
905 r#"{"cap_mb": 1e1}"#,
906 r#"{"cap": "10M"}"#,
907 r#"{"cap": "10000k"}"#,
908 r#"{"cap": 10}"#,
910 ] {
911 let config: Config = serde_json::from_str(json).unwrap();
912 assert_eq!(config.cap, Some(ConfigSize::from_mb(10)), "parsing {json}");
913 }
914 assert_eq!(serde_json::from_str::<Config>("{}").unwrap().cap, None);
915 assert_eq!(
916 serde_json::from_str::<Config>(r#"{"cap": null}"#)
917 .unwrap()
918 .cap,
919 None
920 );
921 let config: Config = serde_json::from_str(r#"{"cap_mb": 18446744073709551615}"#).unwrap();
923 assert_eq!(config.cap, Some(ConfigSize::MAX));
924
925 for (bad, quoted) in [
926 (r#"{"cap_mb": 10.5}"#, "`10.5`"),
927 (r#"{"cap_mb": -5}"#, "cannot be negative"),
928 (r#"{"cap_mb": {}}"#, "`{}`"),
929 (r#"{"cap_mb": 10.50}"#, "`10.50`"),
930 (r#"{"cap_mb": {"bytes": 1}}"#, "`an object`"),
931 (r#"{"cap": "10m"}"#, "unknown unit `m`"),
932 ] {
933 let error = serde_json::from_str::<Config>(bad).unwrap_err().to_string();
934 assert!(error.contains(quoted), "parsing {bad} reported {error}");
935 }
936 }
937
938 #[test]
942 fn the_parser_says_whether_a_unit_was_written() {
943 for (text, has_unit) in [
944 ("16G", true),
945 ("4096B", true),
946 ("1.5Gi", true),
947 ("16000", false),
948 ("+16000", false),
949 ("1.5", false),
950 (".5", false),
951 ("0", false),
952 ] {
953 let (size, written) = ConfigSize::from_str_with_unit(text).unwrap();
954 assert_eq!(written, has_unit, "{text}");
955 assert_eq!(size, text.parse::<ConfigSize>().unwrap(), "{text}");
956 }
957 assert!(ConfigSize::from_str_with_unit("1.2.3").is_err());
958 }
959
960 #[test]
961 fn a_unitless_string_needs_a_unit_unless_the_setting_counts_bytes() {
962 #[derive(Debug, serde::Deserialize)]
963 struct Config {
964 #[serde(default, alias = "cap_mb", deserialize_with = "size_cap")]
965 cap: Option<ConfigSize>,
966 #[serde(default, alias = "buffer_bytes", deserialize_with = "size_buffer")]
967 buffer: Option<ConfigSize>,
968 }
969 crate::size_setting!(size_cap, "cap", LegacySizeUnit::Megabytes);
970 crate::size_setting!(size_buffer, "buffer", LegacySizeUnit::Bytes);
971
972 for json in [
973 r#"{"cap": "16000"}"#,
974 r#"{"cap_mb": "16000"}"#,
975 r#"{"cap": "+1.5"}"#,
976 ] {
977 let error = serde_json::from_str::<Config>(json)
978 .unwrap_err()
979 .to_string();
980 assert!(
981 error.contains("expects a size with a unit"),
982 "{json}: {error}"
983 );
984 assert!(error.contains("`cap`"), "{json}: {error}");
985 }
986 let error = serde_json::from_str::<Config>(r#"{"cap": "16000"}"#)
987 .unwrap_err()
988 .to_string();
989 assert!(error.contains("\"16000M\""), "{error}");
990 for (json, expected) in [
991 (r#"{"cap": "16000M"}"#, ConfigSize::from_mb(16_000)),
992 (r#"{"cap": "16000B"}"#, ConfigSize::from_bytes(16_000)),
993 (r#"{"cap": 16000}"#, ConfigSize::from_mb(16_000)),
994 (r#"{"buffer": "4096"}"#, ConfigSize::from_bytes(4096)),
995 (r#"{"buffer": 4096}"#, ConfigSize::from_bytes(4096)),
996 (r#"{"buffer_bytes": 4096}"#, ConfigSize::from_bytes(4096)),
997 ] {
998 let config: Config = serde_json::from_str(json).unwrap();
999 assert_eq!(
1000 config.cap.or(config.buffer),
1001 Some(expected),
1002 "parsing {json}"
1003 );
1004 }
1005 }
1006
1007 #[test]
1009 fn writing_both_spellings_is_rejected() {
1010 #[derive(Debug, serde::Deserialize)]
1011 struct Config {
1012 #[serde(default, alias = "cap_mb", deserialize_with = "size_cap")]
1013 cap: Option<ConfigSize>,
1014 }
1015 crate::size_setting!(size_cap, "cap", LegacySizeUnit::Megabytes);
1016
1017 let one: Config = serde_json::from_str(r#"{"cap": "30M"}"#).unwrap();
1018 assert_eq!(one.cap, Some(ConfigSize::from_mb(30)));
1019 let error = serde_json::from_str::<Config>(r#"{"cap": "30M", "cap_mb": 30}"#)
1020 .unwrap_err()
1021 .to_string();
1022 assert!(error.contains("duplicate field `cap`"), "{error}");
1023 }
1024
1025 #[test]
1028 fn a_required_setting_refuses_null() {
1029 #[derive(Debug, serde::Deserialize)]
1030 struct Config {
1031 #[serde(
1032 default = "default_buffer",
1033 alias = "buffer_bytes",
1034 deserialize_with = "size_buffer"
1035 )]
1036 buffer: ConfigSize,
1037 }
1038 fn default_buffer() -> ConfigSize {
1039 ConfigSize::from_mib(1)
1040 }
1041 crate::required_size_setting!(size_buffer, "buffer", LegacySizeUnit::Bytes);
1042
1043 assert_eq!(
1044 serde_json::from_str::<Config>("{}").unwrap().buffer,
1045 ConfigSize::from_mib(1)
1046 );
1047 assert_eq!(
1048 serde_json::from_str::<Config>(r#"{"buffer_bytes": 2048}"#)
1049 .unwrap()
1050 .buffer,
1051 ConfigSize::from_kib(2)
1052 );
1053 assert_eq!(
1054 serde_json::from_str::<Config>(r#"{"buffer": "2Ki"}"#)
1055 .unwrap()
1056 .buffer,
1057 ConfigSize::from_kib(2)
1058 );
1059 let error = serde_json::from_str::<Config>(r#"{"buffer": null}"#)
1060 .unwrap_err()
1061 .to_string();
1062 assert!(error.contains("`buffer` cannot be null"), "{error}");
1063 }
1064
1065 #[test]
1069 fn the_no_limit_value_is_read_without_a_warning() {
1070 let warned = std::sync::atomic::AtomicBool::new(false);
1071 let size: ConfigSize = size_from_legacy_number::<serde_json::Error>(
1072 &warned,
1073 "cap",
1074 LegacySizeUnit::Bytes,
1075 u64::MAX,
1076 )
1077 .unwrap();
1078 assert_eq!(size, ConfigSize::MAX);
1079 assert!(!warned.load(std::sync::atomic::Ordering::Relaxed));
1080 let _ = size_from_legacy_number::<serde_json::Error>(
1081 &warned,
1082 "cap",
1083 LegacySizeUnit::Mebibytes,
1084 3,
1085 );
1086 assert!(warned.load(std::sync::atomic::Ordering::Relaxed));
1087 }
1088
1089 mod properties {
1092 use super::*;
1093 use proptest::prelude::*;
1094
1095 fn bytes() -> impl Strategy<Value = u64> {
1098 prop_oneof![
1099 1 => Just(0u64),
1100 1 => Just(1u64),
1101 1 => Just(u64::MAX),
1102 1 => Just(1u64 << 60),
1103 1 => Just(1_000_000_000_000_000_000u64),
1104 2 => 0u64..1_000,
1105 2 => (0u64..1_000).prop_map(|k| k << 20),
1106 2 => (0u64..1_000).prop_map(|m| m * 1_000_000),
1107 6 => any::<u64>(),
1108 ]
1109 }
1110
1111 fn size_like_text() -> impl Strategy<Value = String> {
1113 prop_oneof![
1114 2 => any::<String>(),
1115 3 => "[-+0-9. kKMGTPEiB]{0,40}",
1116 3 => "[0-9]{1,40}(k|K|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)B?",
1117 2 => "[0-9]{1,25}\\.[0-9]{1,25}(k|M|Gi|Ei)",
1118 ]
1119 }
1120
1121 proptest! {
1122 #![proptest_config(ProptestConfig::with_cases(256))]
1123
1124 #[test]
1127 fn display_round_trips(bytes in bytes()) {
1128 let size = ConfigSize::from_bytes(bytes);
1129 let text = size.to_string();
1130 prop_assert_eq!(
1131 text.parse::<ConfigSize>().map_err(|e| e.to_string()),
1132 Ok(size),
1133 "formatted as {:?}",
1134 text
1135 );
1136 }
1137
1138 #[test]
1141 fn serde_agrees_with_from_str(bytes in bytes()) {
1142 let size = ConfigSize::from_bytes(bytes);
1143 let json = serde_json::to_string(&size).unwrap();
1144 let text = size.to_string();
1145 let written = if text.bytes().all(|b| b.is_ascii_digit()) {
1146 format!("\"{text}B\"")
1147 } else {
1148 format!("\"{text}\"")
1149 };
1150 prop_assert_eq!(&json, &written);
1151 prop_assert_eq!(serde_json::from_str::<ConfigSize>(&json).unwrap(), size);
1152 prop_assert_eq!(json.trim_matches('"').parse::<ConfigSize>().unwrap(), size);
1153 }
1154
1155 #[test]
1157 fn parsing_never_panics(text in size_like_text()) {
1158 let _ = text.parse::<ConfigSize>();
1159 }
1160
1161 #[test]
1163 fn whole_units_multiply(count in 0u64..1_000_000, unit in 0usize..UNITS.len()) {
1164 let (name, bytes) = UNITS[unit];
1165 let expected = u128::from(count) * bytes;
1166 let parsed = format!("{count}{name}").parse::<ConfigSize>();
1167 if let Ok(expected) = u64::try_from(expected) {
1168 prop_assert_eq!(parsed.map(ConfigSize::as_bytes), Ok(expected));
1169 } else {
1170 let overflowed = matches!(parsed, Err(ParseError::Overflow { .. }));
1171 prop_assert!(overflowed, "parsed {:?}", parsed);
1172 }
1173 }
1174 }
1175 }
1176}