use core::cmp::Ordering;
use alloc::fmt::{self, Display, Formatter};
use alloc::string::String;
use crate::{get_bytes, Byte, ByteUnit};
#[derive(Debug, Clone, Copy)]
pub struct AdjustedByte {
pub(crate) value: f64,
pub(crate) unit: ByteUnit,
}
impl AdjustedByte {
#[inline]
pub fn format(&self, fractional_digits: usize) -> String {
if self.unit == ByteUnit::B {
format!("{:.0} B", self.value)
} else {
format!("{:.*} {}", fractional_digits, self.value, self.unit)
}
}
#[inline]
pub fn get_value(&self) -> f64 {
self.value
}
#[inline]
pub fn get_unit(&self) -> ByteUnit {
self.unit
}
#[inline]
pub fn get_byte(&self) -> Byte {
let bytes = get_bytes(self.value, self.unit);
Byte::from_bytes(bytes)
}
}
impl Display for AdjustedByte {
#[inline]
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
if self.unit == ByteUnit::B {
f.write_fmt(format_args!("{:.0} B", self.value))
} else {
f.write_fmt(format_args!("{:.2} ", self.value))?;
Display::fmt(&self.unit, f)
}
}
}
impl PartialEq for AdjustedByte {
#[inline]
fn eq(&self, other: &AdjustedByte) -> bool {
let s = self.get_byte();
let o = other.get_byte();
s.eq(&o)
}
}
impl Eq for AdjustedByte {}
impl PartialOrd for AdjustedByte {
#[inline]
fn partial_cmp(&self, other: &AdjustedByte) -> Option<Ordering> {
let s = self.get_byte();
let o = other.get_byte();
s.partial_cmp(&o)
}
}
impl Ord for AdjustedByte {
#[inline]
fn cmp(&self, other: &AdjustedByte) -> Ordering {
let s = self.get_byte();
let o = other.get_byte();
s.cmp(&o)
}
}