vector_common/
json_size.rs1use std::{
2 fmt,
3 iter::Sum,
4 ops::{Add, AddAssign, Sub},
5};
6
7#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
11pub struct JsonSize(usize);
12
13impl fmt::Display for JsonSize {
14 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 write!(f, "{}", self.0)
16 }
17}
18
19impl Sub for JsonSize {
20 type Output = JsonSize;
21
22 #[inline]
23 fn sub(mut self, rhs: Self) -> Self::Output {
24 self.0 -= rhs.0;
25 self
26 }
27}
28
29impl Add for JsonSize {
30 type Output = JsonSize;
31
32 #[inline]
33 fn add(mut self, rhs: Self) -> Self::Output {
34 self.0 += rhs.0;
35 self
36 }
37}
38
39impl AddAssign for JsonSize {
40 #[inline]
41 fn add_assign(&mut self, rhs: Self) {
42 self.0 += rhs.0;
43 }
44}
45
46impl Sum for JsonSize {
47 #[inline]
48 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
49 let mut accum = 0;
50 for val in iter {
51 accum += val.get();
52 }
53
54 JsonSize::new(accum)
55 }
56}
57
58impl From<usize> for JsonSize {
59 #[inline]
60 fn from(value: usize) -> Self {
61 Self(value)
62 }
63}
64
65impl JsonSize {
66 #[must_use]
68 #[inline]
69 pub const fn new(size: usize) -> Self {
70 Self(size)
71 }
72
73 #[must_use]
75 #[inline]
76 pub const fn zero() -> Self {
77 Self(0)
78 }
79
80 #[must_use]
82 #[inline]
83 pub fn get(&self) -> usize {
84 self.0
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
89#[allow(clippy::module_name_repetitions)]
90pub struct NonZeroJsonSize(JsonSize);
91
92impl NonZeroJsonSize {
93 #[must_use]
94 #[inline]
95 pub fn new(size: JsonSize) -> Option<Self> {
96 (size.0 > 0).then_some(NonZeroJsonSize(size))
97 }
98}
99
100impl From<NonZeroJsonSize> for JsonSize {
101 #[inline]
102 fn from(value: NonZeroJsonSize) -> Self {
103 value.0
104 }
105}