Skip to main content

stream_transfer_limit/
counter.rs

1use std::fmt;
2
3/// Integer type used to count cumulative transfer bytes.
4///
5/// The default counter is [`usize`]. Use [`u64`] or [`u128`] when a stream may
6/// legitimately contain more bytes than fit in a pointer-sized count.
7pub trait TransferCounter: Copy + Ord + fmt::Debug + fmt::Display {
8    /// Zero bytes.
9    const ZERO: Self;
10
11    /// Add a chunk length to the current count.
12    ///
13    /// Returns `None` when the new cumulative count cannot be represented by
14    /// this counter type.
15    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self>;
16}
17
18impl TransferCounter for usize {
19    const ZERO: Self = 0;
20
21    #[inline]
22    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self> {
23        self.checked_add(chunk_len)
24    }
25}
26
27impl TransferCounter for u64 {
28    const ZERO: Self = 0;
29
30    #[inline]
31    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self> {
32        self.checked_add(u64::try_from(chunk_len).ok()?)
33    }
34}
35
36impl TransferCounter for u128 {
37    const ZERO: Self = 0;
38
39    #[inline]
40    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self> {
41        self.checked_add(chunk_len as u128)
42    }
43}