#![warn(missing_docs)]
#![no_std]
#![deny(unsafe_code)]
macro_rules! crate_code_name { () => { "kib" }}
macro_rules! crate_version { () => { "7.1.1" }}
pub const NAME: &str = "KiB";
pub const CODE_NAME: &str = crate_code_name!();
pub const ID: &str = concat!(
"c8f97a99-2ba79d4a-0a355f69-9f387d8b-0c0cefe2-67b252af-f02c443d-76b31b5a-",
"e1afecef-f1ca8727-5231b155-99654c9f-9e48339a-f4a5896d-9ffef1ef-a7e7c9e9",
);
pub const VERSION: &str = crate_version!();
pub const RELEASE_DATE: (u16, u8, u8) = (2025, 6, 4);
pub const TAG: &str = concat!(crate_code_name!(), "::c8f97a99::", crate_version!());
extern crate alloc;
use {
core::ops::ControlFlow,
alloc::string::{String, ToString},
};
mod bytes;
mod int;
mod unit;
pub use self::{
bytes::*,
int::*,
unit::*,
};
pub mod version_info;
#[test]
fn test_crate_version() {
assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
}
pub const KIB: u64 = 1024;
pub const MIB: u64 = 1024 * KIB;
pub const GIB: u64 = 1024 * MIB;
pub const TIB: u64 = 1024 * GIB;
pub const PIB: u64 = 1024 * TIB;
pub const EIB: u64 = 1024 * PIB;
pub const ZIB: u128 = 1024 * EIB as u128;
pub const YIB: u128 = 1024 * ZIB;
pub fn fmt<B>(bytes: B) -> String where B: Into<Bytes> {
let (bytes, unit) = fmt_as_parts(bytes);
alloc::format!(concat!("{bytes}", ' ', "{unit}"), bytes=bytes, unit=unit)
}
pub fn fmt_as_parts<B>(bytes: B) -> (String, Unit) where B: Into<Bytes> {
const F1024: f64 = 1024.0;
let bytes = bytes.into();
if let Some(bytes) = bytes.as_u64() {
if bytes < KIB {
return (bytes.to_string(), match bytes { 1 => Unit::OneByte, _ => Unit::Bytes });
}
}
match bytes.as_f64_lossy() {
bytes => if bytes < F1024 {
return (alloc::format!("{bytes:.2}"), Unit::Bytes);
},
};
let (bytes, unit) = match [
Unit::KiB, Unit::MiB, Unit::GiB, Unit::TiB, Unit::PiB, Unit::EiB, Unit::ZiB, Unit::YiB,
].into_iter().try_fold((bytes.as_f64_lossy(), Unit::KiB), |(mut bytes, _), unit| {
bytes /= F1024;
if bytes < F1024 {
ControlFlow::Break((bytes, unit))
} else {
ControlFlow::Continue((bytes, unit))
}
}) {
ControlFlow::Break((bytes, unit)) => (bytes, unit),
ControlFlow::Continue((bytes, unit)) => (bytes, unit),
};
(
alloc::format!("{:.2}", bytes),
unit,
)
}