1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#![warn(missing_docs)]
#![no_std]
#![deny(unsafe_code)]
macro_rules! crate_code_name { () => { "kib" }}
macro_rules! crate_version { () => { "7.0.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) = (2022, 11, 23);
pub const TAG: &str = concat!(crate_code_name!(), "::c8f97a99::", crate_version!());
extern crate alloc;
use {
alloc::string::{String, ToString},
core::ops::ControlFlow,
};
mod bytes;
mod unit;
pub use self::{
bytes::*,
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 });
}
}
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,
)
}