Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: impl Sub and SubAssign for bytesize #56

Merged
merged 2 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@
## Unreleased
- Use SI format by default with `Display`.
- Use "KiB" for SI unit.
- Implement `Sub<ByteSize>` for `ByteSize`.
- Implement `Sub<impl Into<u64>>` for `ByteSize`.
- Implement `SubAssign<ByteSize>` for `ByteSize`.
- Implement `SubAssign<impl Into<u64>>` for `ByteSize`.
49 changes: 48 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryFrom;

use std::fmt::{self, Debug, Display, Formatter};
use std::ops::{Add, AddAssign, Mul, MulAssign};
use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};

/// byte size for 1 byte
pub const B: u64 = 1;
Expand Down Expand Up @@ -284,6 +284,43 @@ where
}
}

impl Sub<ByteSize> for ByteSize {
type Output = ByteSize;

#[inline(always)]
fn sub(self, rhs: ByteSize) -> ByteSize {
ByteSize(self.0 - rhs.0)
}
}

impl SubAssign<ByteSize> for ByteSize {
#[inline(always)]
fn sub_assign(&mut self, rhs: ByteSize) {
self.0 -= rhs.0
}
}

impl<T> Sub<T> for ByteSize
where
T: Into<u64>,
{
type Output = ByteSize;
#[inline(always)]
fn sub(self, rhs: T) -> ByteSize {
ByteSize(self.0 - (rhs.into()))
}
}

impl<T> SubAssign<T> for ByteSize
where
T: Into<u64>,
{
#[inline(always)]
fn sub_assign(&mut self, rhs: T) {
self.0 -= rhs.into();
}
}

impl<T> Mul<T> for ByteSize
where
T: Into<u64>,
Expand Down Expand Up @@ -380,6 +417,8 @@ mod tests {

assert_eq!((x + y).as_u64(), 1_100_000u64);

assert_eq!((x - y).as_u64(), 900_000u64);

assert_eq!((x + (100 * 1000) as u64).as_u64(), 1_100_000);

assert_eq!((x * 2u64).as_u64(), 2_000_000);
Expand All @@ -403,6 +442,14 @@ mod tests {

assert_eq!((x + B as u8).as_u64(), 1_000_001);

assert_eq!((x - MB as u64).as_u64(), 0);

assert_eq!((x - MB as u32).as_u64(), 0);

assert_eq!((x - KB as u32).as_u64(), 999_000);

assert_eq!((x - B as u32).as_u64(), 999_999);

x += MB as u64;
x += MB as u32;
x += 10u16;
Expand Down