stream-transfer-limit 0.1.0

Byte-count transfer limits for fallible futures streams
Documentation
use std::fmt;

/// Integer type used to count cumulative transfer bytes.
///
/// The default counter is [`usize`]. Use [`u64`] or [`u128`] when a stream may
/// legitimately contain more bytes than fit in a pointer-sized count.
pub trait TransferCounter: Copy + Ord + fmt::Debug + fmt::Display {
    /// Zero bytes.
    const ZERO: Self;

    /// Add a chunk length to the current count.
    ///
    /// Returns `None` when the new cumulative count cannot be represented by
    /// this counter type.
    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self>;
}

impl TransferCounter for usize {
    const ZERO: Self = 0;

    #[inline]
    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self> {
        self.checked_add(chunk_len)
    }
}

impl TransferCounter for u64 {
    const ZERO: Self = 0;

    #[inline]
    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self> {
        self.checked_add(u64::try_from(chunk_len).ok()?)
    }
}

impl TransferCounter for u128 {
    const ZERO: Self = 0;

    #[inline]
    fn checked_add_chunk(self, chunk_len: usize) -> Option<Self> {
        self.checked_add(chunk_len as u128)
    }
}