use core::{convert::TryFrom, fmt};
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ByteCount(u64);
impl ByteCount {
pub const ZERO: Self = Self(0);
pub const MAX: Self = Self(u64::MAX);
#[must_use]
pub const fn new(bytes: u64) -> Self {
Self(bytes)
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
#[must_use]
pub const fn is_zero(self) -> bool {
self.0 == 0
}
#[must_use]
pub const fn checked_add(self, other: Self) -> Option<Self> {
match self.0.checked_add(other.0) {
Some(bytes) => Some(Self(bytes)),
None => None,
}
}
#[must_use]
pub const fn checked_sub(self, other: Self) -> Option<Self> {
match self.0.checked_sub(other.0) {
Some(bytes) => Some(Self(bytes)),
None => None,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ByteCountOverflow;
impl fmt::Display for ByteCountOverflow {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("byte count does not fit the target integer type")
}
}
impl core::error::Error for ByteCountOverflow {}
impl From<u32> for ByteCount {
fn from(bytes: u32) -> Self {
Self(u64::from(bytes))
}
}
impl From<u64> for ByteCount {
fn from(bytes: u64) -> Self {
Self(bytes)
}
}
impl From<ByteCount> for u64 {
fn from(count: ByteCount) -> Self {
count.0
}
}
impl TryFrom<usize> for ByteCount {
type Error = ByteCountOverflow;
fn try_from(bytes: usize) -> Result<Self, Self::Error> {
match u64::try_from(bytes) {
Ok(bytes) => Ok(Self(bytes)),
Err(_) => Err(ByteCountOverflow),
}
}
}
impl TryFrom<ByteCount> for usize {
type Error = ByteCountOverflow;
fn try_from(count: ByteCount) -> Result<Self, Self::Error> {
usize::try_from(count.0).map_err(|_| ByteCountOverflow)
}
}