bytesize-1.3.0/.cargo_vcs_info.json0000644000000001360000000000100126730ustar { "git": { "sha1": "f0607486402472bb36a5fc395b3dd79520b29d62" }, "path_in_vcs": "" }bytesize-1.3.0/.github/workflows/rust.yml000064400000000000000000000004741046102023000166050ustar 00000000000000name: Rust on: push: branches: [ master ] pull_request: branches: [ master ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose bytesize-1.3.0/.gitignore000064400000000000000000000000401046102023000134450ustar 00000000000000Cargo.lock target .idea .vscode bytesize-1.3.0/.travis.yml000064400000000000000000000002551046102023000135760ustar 00000000000000language: rust before_script: - rustup component add rustfmt-preview script: - cargo fmt --all -- --check - cargo build --verbose --all - cargo test --verbose --all bytesize-1.3.0/Cargo.toml0000644000000022410000000000100106700ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "bytesize" version = "1.3.0" authors = ["Hyunsik Choi "] description = "an utility for human-readable bytes representations" homepage = "https://github.com/hyunsik/bytesize/" documentation = "https://docs.rs/bytesize/" readme = "README.md" keywords = [ "byte", "byte-size", "utility", "human-readable", "format", ] license = "Apache-2.0" repository = "https://github.com/hyunsik/bytesize/" [dependencies.serde] version = "1.0.185" optional = true [dev-dependencies.serde] version = "1.0.185" features = ["derive"] [dev-dependencies.serde_json] version = "1.0.105" [dev-dependencies.toml] version = "0.7.6" [features] default = [] serde = ["dep:serde"] bytesize-1.3.0/Cargo.toml.orig000064400000000000000000000012161046102023000143520ustar 00000000000000[package] name = "bytesize" description = "an utility for human-readable bytes representations" version = "1.3.0" authors = ["Hyunsik Choi "] homepage = "https://github.com/hyunsik/bytesize/" documentation = "https://docs.rs/bytesize/" repository = "https://github.com/hyunsik/bytesize/" readme = "README.md" keywords = ["byte", "byte-size", "utility", "human-readable", "format"] license = "Apache-2.0" [dependencies] serde = { version = "1.0.185", optional = true } [dev-dependencies] serde = { version = "1.0.185", features = ["derive"] } serde_json = "1.0.105" toml = "0.7.6" [features] default = [] serde = ["dep:serde"] bytesize-1.3.0/LICENSE000064400000000000000000000261361046102023000125000ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bytesize-1.3.0/README.md000064400000000000000000000100641046102023000127430ustar 00000000000000## ByteSize [![Build Status](https://travis-ci.org/hyunsik/bytesize.svg?branch=master)](https://travis-ci.org/hyunsik/bytesize) [![Crates.io Version](https://img.shields.io/crates/v/bytesize.svg)](https://crates.io/crates/bytesize) ByteSize is an utility for human-readable byte count representation. Features: * Pre-defined constants for various size units (e.g., B, Kb, kib, Mb, Mib, Gb, Gib, ... PB) * `ByteSize` type which presents size units convertible to different size units. * Artimetic operations for `ByteSize` * FromStr impl for `ByteSize`, allowing to parse from string size representations like 1.5KiB and 521TiB. * Serde support for binary and human-readable deserializers like JSON [API Documentation](https://docs.rs/bytesize/) ## Usage Add this to your Cargo.toml: ```toml [dependencies] bytesize = {version = "1.2.0", features = ["serde"]} ``` and this to your crate root: ```rust extern crate bytesize; ``` ## Example ### Human readable representations (SI unit and Binary unit) ```rust #[allow(dead_code)] fn assert_display(expected: &str, b: ByteSize) { assert_eq!(expected, format!("{}", b)); } #[test] fn test_display() { assert_display("215 B", ByteSize(215)); assert_display("215 B", ByteSize::b(215)); assert_display("1.0 KB", ByteSize::kb(1)); assert_display("301.0 KB", ByteSize::kb(301)); assert_display("419.0 MB", ByteSize::mb(419)); assert_display("518.0 GB", ByteSize::gb(518)); assert_display("815.0 TB", ByteSize::tb(815)); assert_display("609.0 PB", ByteSize::pb(609)); } fn assert_to_string(expected: &str, b: ByteSize, si: bool) { assert_eq!(expected.to_string(), b.to_string_as(si)); } #[test] fn test_to_string() { assert_to_string("215 B", ByteSize(215), true); assert_to_string("215 B", ByteSize(215), false); assert_to_string("215 B", ByteSize::b(215), true); assert_to_string("215 B", ByteSize::b(215), false); assert_to_string("1.0 kiB", ByteSize::kib(1), true); assert_to_string("1.0 KB", ByteSize::kib(1), false); assert_to_string("293.9 kiB", ByteSize::kb(301), true); assert_to_string("301.0 KB", ByteSize::kb(301), false); assert_to_string("1.0 MiB", ByteSize::mib(1), true); assert_to_string("1048.6 KB", ByteSize::mib(1), false); assert_to_string("399.6 MiB", ByteSize::mb(419), true); assert_to_string("419.0 MB", ByteSize::mb(419), false); assert_to_string("482.4 GiB", ByteSize::gb(518), true); assert_to_string("518.0 GB", ByteSize::gb(518), false); assert_to_string("741.2 TiB", ByteSize::tb(815), true); assert_to_string("815.0 TB", ByteSize::tb(815), false); assert_to_string("540.9 PiB", ByteSize::pb(609), true); assert_to_string("609.0 PB", ByteSize::pb(609), false); } #[test] fn test_parsing_from_str() { // shortcut for writing test cases fn parse(s: &str) -> u64 { s.parse::().unwrap().0 } assert_eq!("0".parse::().unwrap().0, 0); assert_eq!(parse("0"), 0); assert_eq!(parse("500"), 500); assert_eq!(parse("1K"), Unit::KiloByte * 1); assert_eq!(parse("1Ki"), Unit::KibiByte * 1); assert_eq!(parse("1.5Ki"), (1.5 * Unit::KibiByte) as u64); assert_eq!(parse("1KiB"), 1 * Unit::KibiByte); assert_eq!(parse("1.5KiB"), (1.5 * Unit::KibiByte) as u64); assert_eq!(parse("3 MB"), Unit::MegaByte * 3); assert_eq!(parse("4 MiB"), Unit::MebiByte * 4); assert_eq!(parse("6 GB"), 6 * Unit::GigaByte); assert_eq!(parse("4 GiB"), 4 * Unit::GibiByte); assert_eq!(parse("88TB"), 88 * Unit::TeraByte); assert_eq!(parse("521TiB"), 521 * Unit::TebiByte); assert_eq!(parse("8 PB"), 8 * Unit::PetaByte); assert_eq!(parse("8P"), 8 * Unit::PetaByte); assert_eq!(parse("12 PiB"), 12 * Unit::PebiByte); } ``` ### Arithmetic operations ```rust extern crate bytesize; use bytesize::ByteSize; fn byte_arithmetic_operator() { let x = ByteSize::mb(1); let y = ByteSize::kb(100); let plus = x + y; print!("{}", plus); let minus = ByteSize::tb(100) + ByteSize::gb(4); print!("{}", minus); } ``` bytesize-1.3.0/src/lib.rs000064400000000000000000000317301046102023000133720ustar 00000000000000//! ByteSize is an utility that easily makes bytes size representation //! and helps its arithmetic operations. //! //! ## Example //! //! ```ignore //! extern crate bytesize; //! //! use bytesize::ByteSize; //! //! fn byte_arithmetic_operator() { //! let x = ByteSize::mb(1); //! let y = ByteSize::kb(100); //! //! let plus = x + y; //! print!("{} bytes", plus.as_u64()); //! //! let minus = ByteSize::tb(100) - ByteSize::gb(4); //! print!("{} bytes", minus.as_u64()); //! } //! ``` //! //! It also provides its human readable string as follows: //! //! ```ignore= //! assert_eq!("482 GiB".to_string(), ByteSize::gb(518).to_string(true)); //! assert_eq!("518 GB".to_string(), ByteSize::gb(518).to_string(false)); //! ``` mod parse; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "serde")] use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "serde")] use std::convert::TryFrom; use std::fmt::{self, Debug, Display, Formatter}; use std::ops::{Add, AddAssign, Mul, MulAssign}; /// byte size for 1 byte pub const B: u64 = 1; /// bytes size for 1 kilobyte pub const KB: u64 = 1_000; /// bytes size for 1 megabyte pub const MB: u64 = 1_000_000; /// bytes size for 1 gigabyte pub const GB: u64 = 1_000_000_000; /// bytes size for 1 terabyte pub const TB: u64 = 1_000_000_000_000; /// bytes size for 1 petabyte pub const PB: u64 = 1_000_000_000_000_000; /// bytes size for 1 kibibyte pub const KIB: u64 = 1_024; /// bytes size for 1 mebibyte pub const MIB: u64 = 1_048_576; /// bytes size for 1 gibibyte pub const GIB: u64 = 1_073_741_824; /// bytes size for 1 tebibyte pub const TIB: u64 = 1_099_511_627_776; /// bytes size for 1 pebibyte pub const PIB: u64 = 1_125_899_906_842_624; static UNITS: &str = "KMGTPE"; static UNITS_SI: &str = "kMGTPE"; static LN_KB: f64 = 6.931471806; // ln 1024 static LN_KIB: f64 = 6.907755279; // ln 1000 pub fn kb>(size: V) -> u64 { size.into() * KB } pub fn kib>(size: V) -> u64 { size.into() * KIB } pub fn mb>(size: V) -> u64 { size.into() * MB } pub fn mib>(size: V) -> u64 { size.into() * MIB } pub fn gb>(size: V) -> u64 { size.into() * GB } pub fn gib>(size: V) -> u64 { size.into() * GIB } pub fn tb>(size: V) -> u64 { size.into() * TB } pub fn tib>(size: V) -> u64 { size.into() * TIB } pub fn pb>(size: V) -> u64 { size.into() * PB } pub fn pib>(size: V) -> u64 { size.into() * PIB } /// Byte size representation #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)] pub struct ByteSize(pub u64); impl ByteSize { #[inline(always)] pub const fn b(size: u64) -> ByteSize { ByteSize(size) } #[inline(always)] pub const fn kb(size: u64) -> ByteSize { ByteSize(size * KB) } #[inline(always)] pub const fn kib(size: u64) -> ByteSize { ByteSize(size * KIB) } #[inline(always)] pub const fn mb(size: u64) -> ByteSize { ByteSize(size * MB) } #[inline(always)] pub const fn mib(size: u64) -> ByteSize { ByteSize(size * MIB) } #[inline(always)] pub const fn gb(size: u64) -> ByteSize { ByteSize(size * GB) } #[inline(always)] pub const fn gib(size: u64) -> ByteSize { ByteSize(size * GIB) } #[inline(always)] pub const fn tb(size: u64) -> ByteSize { ByteSize(size * TB) } #[inline(always)] pub const fn tib(size: u64) -> ByteSize { ByteSize(size * TIB) } #[inline(always)] pub const fn pb(size: u64) -> ByteSize { ByteSize(size * PB) } #[inline(always)] pub const fn pib(size: u64) -> ByteSize { ByteSize(size * PIB) } #[inline(always)] pub const fn as_u64(&self) -> u64 { self.0 } #[inline(always)] pub fn to_string_as(&self, si_unit: bool) -> String { to_string(self.0, si_unit) } } pub fn to_string(bytes: u64, si_prefix: bool) -> String { let unit = if si_prefix { KIB } else { KB }; let unit_base = if si_prefix { LN_KIB } else { LN_KB }; let unit_prefix = if si_prefix { UNITS_SI.as_bytes() } else { UNITS.as_bytes() }; let unit_suffix = if si_prefix { "iB" } else { "B" }; if bytes < unit { format!("{} B", bytes) } else { let size = bytes as f64; let exp = match (size.ln() / unit_base) as usize { e if e == 0 => 1, e => e, }; format!( "{:.1} {}{}", (size / unit.pow(exp as u32) as f64), unit_prefix[exp - 1] as char, unit_suffix ) } } impl Display for ByteSize { fn fmt(&self, f: &mut Formatter) ->fmt::Result { f.pad(&to_string(self.0, false)) } } impl Debug for ByteSize { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self) } } macro_rules! commutative_op { ($t:ty) => { impl Add for $t { type Output = ByteSize; #[inline(always)] fn add(self, rhs: ByteSize) -> ByteSize { ByteSize(rhs.0 + (self as u64)) } } impl Mul for $t { type Output = ByteSize; #[inline(always)] fn mul(self, rhs: ByteSize) -> ByteSize { ByteSize(rhs.0 * (self as u64)) } } }; } commutative_op!(u64); commutative_op!(u32); commutative_op!(u16); commutative_op!(u8); impl Add for ByteSize { type Output = ByteSize; #[inline(always)] fn add(self, rhs: ByteSize) -> ByteSize { ByteSize(self.0 + rhs.0) } } impl AddAssign for ByteSize { #[inline(always)] fn add_assign(&mut self, rhs: ByteSize) { self.0 += rhs.0 } } impl Add for ByteSize where T: Into { type Output = ByteSize; #[inline(always)] fn add(self, rhs: T) -> ByteSize { ByteSize(self.0 + (rhs.into() as u64)) } } impl AddAssign for ByteSize where T: Into { #[inline(always)] fn add_assign(&mut self, rhs: T) { self.0 += rhs.into() as u64; } } impl Mul for ByteSize where T: Into { type Output = ByteSize; #[inline(always)] fn mul(self, rhs: T) -> ByteSize { ByteSize(self.0 * (rhs.into() as u64)) } } impl MulAssign for ByteSize where T: Into { #[inline(always)] fn mul_assign(&mut self, rhs: T) { self.0 *= rhs.into() as u64; } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for ByteSize { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct ByteSizeVistor; impl<'de> de::Visitor<'de> for ByteSizeVistor { type Value = ByteSize; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("an integer or string") } fn visit_i64(self, value: i64) -> Result { if let Ok(val) = u64::try_from(value) { Ok(ByteSize(val)) } else { Err(E::invalid_value( de::Unexpected::Signed(value), &"integer overflow", )) } } fn visit_u64(self, value: u64) -> Result { Ok(ByteSize(value)) } fn visit_str(self, value: &str) -> Result { if let Ok(val) = value.parse() { Ok(val) } else { Err(E::invalid_value( de::Unexpected::Str(value), &"parsable string", )) } } } if deserializer.is_human_readable() { deserializer.deserialize_any(ByteSizeVistor) } else { deserializer.deserialize_u64(ByteSizeVistor) } } } #[cfg(feature = "serde")] impl Serialize for ByteSize { fn serialize(&self, serializer: S) -> Result where S: Serializer, { if serializer.is_human_readable() { ::serialize(self.to_string().as_str(), serializer) } else { self.0.serialize(serializer) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_arithmetic_op() { let mut x = ByteSize::mb(1); let y = ByteSize::kb(100); assert_eq!((x + y).as_u64(), 1_100_000u64); assert_eq!((x + (100 * 1000) as u64).as_u64(), 1_100_000); assert_eq!((x * 2u64).as_u64(), 2_000_000); x += y; assert_eq!(x.as_u64(), 1_100_000); x *= 2u64; assert_eq!(x.as_u64(), 2_200_000); } #[test] fn test_arithmetic_primitives() { let mut x = ByteSize::mb(1); assert_eq!((x + MB as u64).as_u64(), 2_000_000); assert_eq!((x + MB as u32).as_u64(), 2_000_000); assert_eq!((x + KB as u16).as_u64(), 1_001_000); assert_eq!((x + B as u8).as_u64(), 1_000_001); x += MB as u64; x += MB as u32; x += 10u16; x += 1u8; assert_eq!(x.as_u64(), 3_000_011); } #[test] fn test_comparison() { assert!(ByteSize::mb(1) == ByteSize::kb(1000)); assert!(ByteSize::mib(1) == ByteSize::kib(1024)); assert!(ByteSize::mb(1) != ByteSize::kib(1024)); assert!(ByteSize::mb(1) < ByteSize::kib(1024)); assert!(ByteSize::b(0) < ByteSize::tib(1)); } fn assert_display(expected: &str, b: ByteSize) { assert_eq!(expected, format!("{}", b)); } #[test] fn test_display() { assert_display("215 B", ByteSize::b(215)); assert_display("1.0 KB", ByteSize::kb(1)); assert_display("301.0 KB", ByteSize::kb(301)); assert_display("419.0 MB", ByteSize::mb(419)); assert_display("518.0 GB", ByteSize::gb(518)); assert_display("815.0 TB", ByteSize::tb(815)); assert_display("609.0 PB", ByteSize::pb(609)); } #[test] fn test_display_alignment() { assert_eq!("|357 B |", format!("|{:10}|", ByteSize(357))); assert_eq!("| 357 B|", format!("|{:>10}|", ByteSize(357))); assert_eq!("|357 B |", format!("|{:<10}|", ByteSize(357))); assert_eq!("| 357 B |", format!("|{:^10}|", ByteSize(357))); assert_eq!("|-----357 B|", format!("|{:->10}|", ByteSize(357))); assert_eq!("|357 B-----|", format!("|{:-<10}|", ByteSize(357))); assert_eq!("|--357 B---|", format!("|{:-^10}|", ByteSize(357))); } fn assert_to_string(expected: &str, b: ByteSize, si: bool) { assert_eq!(expected.to_string(), b.to_string_as(si)); } #[test] fn test_to_string_as() { assert_to_string("215 B", ByteSize::b(215), true); assert_to_string("215 B", ByteSize::b(215), false); assert_to_string("1.0 kiB", ByteSize::kib(1), true); assert_to_string("1.0 KB", ByteSize::kib(1), false); assert_to_string("293.9 kiB", ByteSize::kb(301), true); assert_to_string("301.0 KB", ByteSize::kb(301), false); assert_to_string("1.0 MiB", ByteSize::mib(1), true); assert_to_string("1048.6 KB", ByteSize::mib(1), false); // a bug case: https://github.com/flang-project/bytesize/issues/8 assert_to_string("1.9 GiB", ByteSize::mib(1907), true); assert_to_string("2.0 GB", ByteSize::mib(1908), false); assert_to_string("399.6 MiB", ByteSize::mb(419), true); assert_to_string("419.0 MB", ByteSize::mb(419), false); assert_to_string("482.4 GiB", ByteSize::gb(518), true); assert_to_string("518.0 GB", ByteSize::gb(518), false); assert_to_string("741.2 TiB", ByteSize::tb(815), true); assert_to_string("815.0 TB", ByteSize::tb(815), false); assert_to_string("540.9 PiB", ByteSize::pb(609), true); assert_to_string("609.0 PB", ByteSize::pb(609), false); } #[test] fn test_default() { assert_eq!(ByteSize::b(0), ByteSize::default()); } #[test] fn test_to_string() { assert_to_string("609.0 PB", ByteSize::pb(609), false); } #[cfg(feature = "serde")] #[test] fn test_serde() { #[derive(Serialize, Deserialize)] struct S { x: ByteSize, } let s: S = serde_json::from_str(r#"{ "x": "5 B" }"#).unwrap(); assert_eq!(s.x, ByteSize(5)); let s: S = serde_json::from_str(r#"{ "x": 1048576 }"#).unwrap(); assert_eq!(s.x, "1 MiB".parse::().unwrap()); let s: S = toml::from_str(r#"x = "2.5 MiB""#).unwrap(); assert_eq!(s.x, "2.5 MiB".parse::().unwrap()); // i64 MAX let s: S = toml::from_str(r#"x = "9223372036854775807""#).unwrap(); assert_eq!(s.x, "9223372036854775807".parse::().unwrap()); } } bytesize-1.3.0/src/parse.rs000064400000000000000000000142211046102023000137320ustar 00000000000000use super::ByteSize; impl std::str::FromStr for ByteSize { type Err = String; fn from_str(value: &str) -> Result { if let Ok(v) = value.parse::() { return Ok(Self(v)); } let number = take_while(value, |c| c.is_ascii_digit() || c == '.'); match number.parse::() { Ok(v) => { let suffix = skip_while(value, |c| { c.is_whitespace() || c.is_ascii_digit() || c == '.' }); match suffix.parse::() { Ok(u) => Ok(Self((v * u) as u64)), Err(error) => Err(format!( "couldn't parse {:?} into a known SI unit, {}", suffix, error )), } } Err(error) => Err(format!( "couldn't parse {:?} into a ByteSize, {}", value, error )), } } } fn take_while

(s: &str, mut predicate: P) -> &str where P: FnMut(char) -> bool, { let offset = s .chars() .take_while(|ch| predicate(*ch)) .map(|ch| ch.len_utf8()) .sum(); &s[..offset] } fn skip_while

(s: &str, mut predicate: P) -> &str where P: FnMut(char) -> bool, { let offset: usize = s .chars() .skip_while(|ch| predicate(*ch)) .map(|ch| ch.len_utf8()) .sum(); &s[(s.len() - offset)..] } enum Unit { Byte, // power of tens KiloByte, MegaByte, GigaByte, TeraByte, PetaByte, // power of twos KibiByte, MebiByte, GibiByte, TebiByte, PebiByte, } impl Unit { fn factor(&self) -> u64 { match self { Self::Byte => super::B, // power of tens Self::KiloByte => super::KB, Self::MegaByte => super::MB, Self::GigaByte => super::GB, Self::TeraByte => super::TB, Self::PetaByte => super::PB, // power of twos Self::KibiByte => super::KIB, Self::MebiByte => super::MIB, Self::GibiByte => super::GIB, Self::TebiByte => super::TIB, Self::PebiByte => super::PIB, } } } mod impl_ops { use super::Unit; use std::ops; impl ops::Add for Unit { type Output = u64; fn add(self, other: u64) -> Self::Output { self.factor() + other } } impl ops::Add for u64 { type Output = u64; fn add(self, other: Unit) -> Self::Output { self + other.factor() } } impl ops::Mul for Unit { type Output = u64; fn mul(self, other: u64) -> Self::Output { self.factor() * other } } impl ops::Mul for u64 { type Output = u64; fn mul(self, other: Unit) -> Self::Output { self * other.factor() } } impl ops::Add for Unit { type Output = f64; fn add(self, other: f64) -> Self::Output { self.factor() as f64 + other } } impl ops::Add for f64 { type Output = f64; fn add(self, other: Unit) -> Self::Output { other.factor() as f64 + self } } impl ops::Mul for Unit { type Output = f64; fn mul(self, other: f64) -> Self::Output { self.factor() as f64 * other } } impl ops::Mul for f64 { type Output = f64; fn mul(self, other: Unit) -> Self::Output { other.factor() as f64 * self } } } impl std::str::FromStr for Unit { type Err = String; fn from_str(unit: &str) -> Result { match unit.to_lowercase().as_str() { "b" => Ok(Self::Byte), // power of tens "k" | "kb" => Ok(Self::KiloByte), "m" | "mb" => Ok(Self::MegaByte), "g" | "gb" => Ok(Self::GigaByte), "t" | "tb" => Ok(Self::TeraByte), "p" | "pb" => Ok(Self::PetaByte), // power of twos "ki" | "kib" => Ok(Self::KibiByte), "mi" | "mib" => Ok(Self::MebiByte), "gi" | "gib" => Ok(Self::GibiByte), "ti" | "tib" => Ok(Self::TebiByte), "pi" | "pib" => Ok(Self::PebiByte), _ => Err(format!("couldn't parse unit of {:?}", unit)), } } } #[cfg(test)] mod tests { use super::*; #[test] fn when_ok() { // shortcut for writing test cases fn parse(s: &str) -> u64 { s.parse::().unwrap().0 } assert_eq!("0".parse::().unwrap().0, 0); assert_eq!(parse("0"), 0); assert_eq!(parse("500"), 500); assert_eq!(parse("1K"), Unit::KiloByte * 1); assert_eq!(parse("1Ki"), Unit::KibiByte * 1); assert_eq!(parse("1.5Ki"), (1.5 * Unit::KibiByte) as u64); assert_eq!(parse("1KiB"), 1 * Unit::KibiByte); assert_eq!(parse("1.5KiB"), (1.5 * Unit::KibiByte) as u64); assert_eq!(parse("3 MB"), Unit::MegaByte * 3); assert_eq!(parse("4 MiB"), Unit::MebiByte * 4); assert_eq!(parse("6 GB"), 6 * Unit::GigaByte); assert_eq!(parse("4 GiB"), 4 * Unit::GibiByte); assert_eq!(parse("88TB"), 88 * Unit::TeraByte); assert_eq!(parse("521TiB"), 521 * Unit::TebiByte); assert_eq!(parse("8 PB"), 8 * Unit::PetaByte); assert_eq!(parse("8P"), 8 * Unit::PetaByte); assert_eq!(parse("12 PiB"), 12 * Unit::PebiByte); } #[test] fn when_err() { // shortcut for writing test cases fn parse(s: &str) -> Result { s.parse::() } assert!(parse("").is_err()); assert!(parse("a124GB").is_err()); } #[test] fn to_and_from_str() { // shortcut for writing test cases fn parse(s: &str) -> u64 { s.parse::().unwrap().0 } assert_eq!(parse(&format!("{}", parse("128GB"))), 128 * Unit::GigaByte); assert_eq!( parse(&crate::to_string(parse("128.000 GiB"), true)), 128 * Unit::GibiByte ); } }