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
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

KiB

Copyright (C) 2016-2017, 2019-2020, 2022  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2016-2017".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # KiB
//!
//! ## Project
//!
//! - Repository: <https://bitbucket.org/de-marco/kib>
//! - License: GNU Lesser General Public License, either version 3, or (at your option) any later version.
//! - _This project follows [Semantic Versioning 2.0.0]_
//!
//! ## Features
//!
//! This crate helps format bytes to KiB, MiB...
//!
//! ## Notes
//!
//! Documentation is built with all features. Some of them are optional. If you see components from other crates, you can view source to see
//! what features are required.
//!
//! [Semantic Versioning 2.0.0]: https://semver.org/spec/v2.0.0.html

#![warn(missing_docs)]
#![no_std]
#![deny(unsafe_code)]

// ╔═════════════════╗
// ║   IDENTIFIERS   ║
// ╚═════════════════╝

macro_rules! crate_code_name    { () => { "kib" }}
macro_rules! crate_version      { () => { "7.0.1" }}

/// # Crate name
pub const NAME: &str = "KiB";

/// # Crate code name
pub const CODE_NAME: &str = crate_code_name!();

/// # ID of this crate
pub const ID: &str = concat!(
    "c8f97a99-2ba79d4a-0a355f69-9f387d8b-0c0cefe2-67b252af-f02c443d-76b31b5a-",
    "e1afecef-f1ca8727-5231b155-99654c9f-9e48339a-f4a5896d-9ffef1ef-a7e7c9e9",
);

/// # Crate version
pub const VERSION: &str = crate_version!();

/// # Crate release date (year/month/day)
pub const RELEASE_DATE: (u16, u8, u8) = (2022, 11, 23);

/// Tag, which can be used for logging...
pub const TAG: &str = concat!(crate_code_name!(), "::c8f97a99::", crate_version!());

// ╔════════════════════╗
// ║   IMPLEMENTATION   ║
// ╚════════════════════╝

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"));
}

/// One KiB in bytes.
pub const KIB: u64 = 1024;

/// One MiB in bytes.
pub const MIB: u64 = 1024 * KIB;

/// One GiB in bytes.
pub const GIB: u64 = 1024 * MIB;

/// One TiB in bytes.
pub const TIB: u64 = 1024 * GIB;

/// One PiB in bytes.
pub const PIB: u64 = 1024 * TIB;

/// One EiB in bytes.
pub const EIB: u64 = 1024 * PIB;

/// One ZiB in bytes.
pub const ZIB: u128 = 1024 * EIB as u128;

/// One YiB in bytes.
pub const YIB: u128 = 1024 * ZIB;

/// # Formats bytes into string.
///
/// The result is a human-readable string, e.g: `1.9 KiB`, `9.9 TiB`...
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)
}

/// # Formats bytes into size and 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,
    )
}