tokio_process_tools/output_stream/num_bytes.rs
1/// A wrapper type representing a number of bytes.
2///
3/// Use the [`NumBytesExt`] trait to conveniently create instances:
4/// ```
5/// use tokio_process_tools::NumBytesExt;
6/// let kb = 16.kilobytes();
7/// let mb = 2.megabytes();
8/// ```
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct NumBytes(pub(crate) usize);
11
12impl NumBytes {
13 /// The largest representable byte count (`usize::MAX`).
14 ///
15 /// Use this when an API requires an explicit byte limit but you don't actually want to cap
16 /// it — for example, line-parsing options that require a non-zero `max_line_length` but you
17 /// trust the source to produce reasonable lines.
18 pub const MAX: NumBytes = NumBytes(usize::MAX);
19
20 /// Creates a `NumBytes` value of zero.
21 #[must_use]
22 pub fn zero() -> Self {
23 Self(0)
24 }
25
26 pub(crate) fn assert_non_zero(self, parameter_name: &str) {
27 assert!(
28 self.0 > 0,
29 "{parameter_name} must be greater than zero bytes"
30 );
31 }
32
33 /// The amount of bytes represented by this instance.
34 #[must_use]
35 pub fn bytes(&self) -> usize {
36 self.0
37 }
38}
39
40/// Extension trait providing convenience constructors for [`NumBytes`].
41///
42/// Implemented for `usize`, so integer literals can be used directly:
43///
44/// ```
45/// use tokio_process_tools::{NumBytes, NumBytesExt};
46///
47/// let small: NumBytes = 512.bytes();
48/// let medium: NumBytes = 16.kilobytes();
49/// let large: NumBytes = 2.megabytes();
50///
51/// assert_eq!(small.bytes(), 512);
52/// assert_eq!(medium.bytes(), 16 * 1024);
53/// assert_eq!(large.bytes(), 2 * 1024 * 1024);
54/// ```
55pub trait NumBytesExt {
56 /// Interprets the value as literal bytes.
57 fn bytes(self) -> NumBytes;
58
59 /// Interprets the value as kilobytes (value * 1024).
60 fn kilobytes(self) -> NumBytes;
61
62 /// Interprets the value as megabytes (value * 1024 * 1024).
63 fn megabytes(self) -> NumBytes;
64}
65
66impl NumBytesExt for usize {
67 fn bytes(self) -> NumBytes {
68 NumBytes(self)
69 }
70
71 fn kilobytes(self) -> NumBytes {
72 NumBytes(self * 1024)
73 }
74
75 fn megabytes(self) -> NumBytes {
76 NumBytes(self * 1024 * 1024)
77 }
78}