Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Add `ByteSize::as_*()` methods to return equivalent sizes in KB, GiB, etc.

## 2.1.0

- Support parsing and formatting exabytes (EB) & exbibytes (EiB).
Expand Down
82 changes: 82 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,78 @@ impl ByteSize {
self.0
}

/// Returns byte count as kilobytes.
#[inline(always)]
pub fn as_kb(&self) -> f64 {
self.0 as f64 / KB as f64
}

/// Returns byte count as kibibytes.
#[inline(always)]
pub fn as_kib(&self) -> f64 {
self.0 as f64 / KIB as f64
}

/// Returns byte count as megabytes.
#[inline(always)]
pub fn as_mb(&self) -> f64 {
self.0 as f64 / MB as f64
}

/// Returns byte count as mebibytes.
#[inline(always)]
pub fn as_mib(&self) -> f64 {
self.0 as f64 / MIB as f64
}

/// Returns byte count as gigabytes.
#[inline(always)]
pub fn as_gb(&self) -> f64 {
self.0 as f64 / GB as f64
}

/// Returns byte count as gibibytes.
#[inline(always)]
pub fn as_gib(&self) -> f64 {
self.0 as f64 / GIB as f64
}

/// Returns byte count as terabytes.
#[inline(always)]
pub fn as_tb(&self) -> f64 {
self.0 as f64 / TB as f64
}

/// Returns byte count as tebibytes.
#[inline(always)]
pub fn as_tib(&self) -> f64 {
self.0 as f64 / TIB as f64
}

/// Returns byte count as petabytes.
#[inline(always)]
pub fn as_pb(&self) -> f64 {
self.0 as f64 / PB as f64
}

/// Returns byte count as pebibytes.
#[inline(always)]
pub fn as_pib(&self) -> f64 {
self.0 as f64 / PIB as f64
}

/// Returns byte count as exabytes.
#[inline(always)]
pub fn as_eb(&self) -> f64 {
self.0 as f64 / EB as f64
}

/// Returns byte count as exbibytes.
#[inline(always)]
pub fn as_eib(&self) -> f64 {
self.0 as f64 / EIB as f64
}

/// Returns a formatting display wrapper.
pub fn display(&self) -> Display {
Display {
Expand Down Expand Up @@ -488,6 +560,16 @@ mod tests {
assert!(ByteSize::pib(1) < ByteSize::eb(1));
}

#[test]
fn as_unit_conversions() {
assert_eq!(ByteSize::gb(43).as_kib(), 41992187.5_f64);
assert_eq!(ByteSize::mib(27).as_gb(), 0.028311552_f64);
assert_eq!(ByteSize::tib(39).as_pib(), 0.042880953483264_f64);
assert_eq!(ByteSize::kib(938948).as_mb(), 961.482752_f64);
assert_eq!(ByteSize::pb(4837).as_eib(), 4.195428726649908_f64);
assert_eq!(ByteSize::b(2873872874893).as_tib(), 2.613772153284117_f64);
}

#[track_caller]
fn assert_display(expected: &str, b: ByteSize) {
assert_eq!(expected, format!("{b}"));
Expand Down
Loading