Skip to content

Commit 9eefdcd

Browse files
authored
feat: impl Sub and SubAssign for bytesize (#56)
1 parent 3a9a14b commit 9eefdcd

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,7 @@
33
## Unreleased
44
- Use SI format by default with `Display`.
55
- Use "KiB" for SI unit.
6+
- Implement `Sub<ByteSize>` for `ByteSize`.
7+
- Implement `Sub<impl Into<u64>>` for `ByteSize`.
8+
- Implement `SubAssign<ByteSize>` for `ByteSize`.
9+
- Implement `SubAssign<impl Into<u64>>` for `ByteSize`.

src/lib.rs

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
3939
use std::convert::TryFrom;
4040

4141
use std::fmt::{self, Debug, Display, Formatter};
42-
use std::ops::{Add, AddAssign, Mul, MulAssign};
42+
use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
4343

4444
/// byte size for 1 byte
4545
pub const B: u64 = 1;
@@ -284,6 +284,43 @@ where
284284
}
285285
}
286286

287+
impl Sub<ByteSize> for ByteSize {
288+
type Output = ByteSize;
289+
290+
#[inline(always)]
291+
fn sub(self, rhs: ByteSize) -> ByteSize {
292+
ByteSize(self.0 - rhs.0)
293+
}
294+
}
295+
296+
impl SubAssign<ByteSize> for ByteSize {
297+
#[inline(always)]
298+
fn sub_assign(&mut self, rhs: ByteSize) {
299+
self.0 -= rhs.0
300+
}
301+
}
302+
303+
impl<T> Sub<T> for ByteSize
304+
where
305+
T: Into<u64>,
306+
{
307+
type Output = ByteSize;
308+
#[inline(always)]
309+
fn sub(self, rhs: T) -> ByteSize {
310+
ByteSize(self.0 - (rhs.into()))
311+
}
312+
}
313+
314+
impl<T> SubAssign<T> for ByteSize
315+
where
316+
T: Into<u64>,
317+
{
318+
#[inline(always)]
319+
fn sub_assign(&mut self, rhs: T) {
320+
self.0 -= rhs.into();
321+
}
322+
}
323+
287324
impl<T> Mul<T> for ByteSize
288325
where
289326
T: Into<u64>,
@@ -380,6 +417,8 @@ mod tests {
380417

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

420+
assert_eq!((x - y).as_u64(), 900_000u64);
421+
383422
assert_eq!((x + (100 * 1000) as u64).as_u64(), 1_100_000);
384423

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

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

445+
assert_eq!((x - MB as u64).as_u64(), 0);
446+
447+
assert_eq!((x - MB as u32).as_u64(), 0);
448+
449+
assert_eq!((x - KB as u32).as_u64(), 999_000);
450+
451+
assert_eq!((x - B as u32).as_u64(), 999_999);
452+
406453
x += MB as u64;
407454
x += MB as u32;
408455
x += 10u16;

0 commit comments

Comments
 (0)