humansize-2.1.3/.cargo_vcs_info.json0000644000000001120000000000100130340ustar { "git": { "sha1": "caa4cc5260cf7bece6e53aa60a94f8c8115464dd" } } humansize-2.1.3/.gitignore000064400000000000000000000000330072674642500136460ustar 00000000000000target Cargo.lock *.rs.bkhumansize-2.1.3/.travis.yml000064400000000000000000000005430072674642500137750ustar 00000000000000language: rust rust: - stable - beta - nightly - 1.56.1 sudo: false before_script: - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - cargo test notifications: email: on_success: never addons: apt: packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev humansize-2.1.3/Cargo.lock0000644000000005610000000000100110170ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "humansize" version = "2.1.3" dependencies = [ "libm", ] [[package]] name = "libm" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" humansize-2.1.3/Cargo.toml0000644000000021430000000000100110400ustar # 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] edition = "2021" rust-version = "1.56" name = "humansize" version = "2.1.3" authors = ["Leopold Arkham "] exclude = ["/feature-tests"] description = "A configurable crate to easily represent sizes in a human-readable format." homepage = "https://github.com/LeopoldArkham/humansize" documentation = "https://docs.rs/humansize" readme = "README.md" keywords = ["size", "formatting", "humanize", "file-size"] categories = ["value-formatting"] license = "MIT/Apache-2.0" repository = "https://github.com/LeopoldArkham/humansize" resolver = "2" [dependencies.libm] version = "0.2.5" [features] impl_style = [] no_alloc = [] humansize-2.1.3/Cargo.toml.orig000064400000000000000000000012200072674642500145440ustar 00000000000000[package] name = "humansize" version = "2.1.3" authors = ["Leopold Arkham "] edition = "2021" readme = "README.md" description = "A configurable crate to easily represent sizes in a human-readable format." repository = "https://github.com/LeopoldArkham/humansize" homepage = "https://github.com/LeopoldArkham/humansize" documentation = "https://docs.rs/humansize" keywords = ["size", "formatting", "humanize", "file-size"] categories = ["value-formatting"] license = "MIT/Apache-2.0" exclude = ["/feature-tests"] rust-version = "1.56" [features] no_alloc = [] impl_style = [] [dependencies] libm = "0.2.5" humansize-2.1.3/LICENSE-APACHE000064400000000000000000000254460072674642500136210ustar 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.humansize-2.1.3/LICENSE-MIT000064400000000000000000000020700072674642500133150ustar 00000000000000Copyright (c) 2014 Alex Crichton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.humansize-2.1.3/README.md000064400000000000000000000114540072674642500131460ustar 00000000000000# **Humansize** ![travis badge](https://travis-ci.org/LeopoldArkham/humansize.svg?branch=master) [![Actively Maintained](https://img.shields.io/badge/Maintenance%20Level-Actively%20Maintained-green.svg)](https://gist.github.com/cheerfulstoic/d107229326a01ff0f333a1d3476e068d) [Documentation](https://docs.rs/humansize/latest/humansize/) ## Features Humansize is a humanization library for information size that is: - Simple & convenient to use - Customizable - Supports byte or bit sizes - `no-std` - Optionally non-allocating - Optionally accepts signed values ## How to use it... Add humansize as a dependency to your project's `cargo.toml`: ```toml [dependencies] ... humansize = "2.1.3" ``` ### ... to easily format a size: 1. Import the `format_size` function as well as your preferred set of defaults: - `DECIMAL` (SI) - `BINARY` (IEC) - `WINDOWS` (IEC values but SI units) 2. Call `format_size` with an unsigned integer ```rust use humansize::{format_size, DECIMAL}; let size = 1_000_000u64; let res: String = format_size(size, DECIMAL); assert_eq!(&res, "1 MB"); ``` ### ... to format many sizes: To improve reusability, you can use `create_format`, which returns a formatter function akin to `format_size` but with the options argument curried so it doesn't need to be specified again: ```rust use humansize::{make_format, DECIMAL}; let formatter = make_format(DECIMAL); assert_eq!(formatter(1_000_000u64), "1 MB"); assert_eq!(formatter(1_000_000_000u64), "1 GB"); //... ``` ### ... to avoid allocation: Specify the `no_alloc` feature flag in your project's `cargo.toml`: ```toml [dependencies] ... humansize = { version = "2.0.0", features = ["no_alloc"] } ``` This excludes all allocating code from compilation. You may now use the library's internal `SizeFormatter` struct, which implements `core::fmt::display` so that you can `write!` it to a custom buffer of your choice: ```rust use humansize::{SizeFormatter, DECIMAL}; let formatter = SizeFormatter::new(1_000_000usize, DECIMAL); assert_eq!(format!("{}", formatter), "1 MB"); ``` ### ... with the `impl` style API: For stylistic reasons, you may prefer to use the impl-style API of earlier versions of the crate. To do so, specify the `impl-style` feature flag in your project's `cargo.toml`: ```toml [dependencies] ... humansize = { version = "2.0.0", features = ["impl_style"] } ``` Enabling this feature makes two methods available: - `format_size` on unsigned integers types - `format_size_i` on signed integer types. To use it, bring the FormatSize trait into scope and call its method on an integer type: ```ignore use humansize::{FormatSize, FormatSizeI DECIMAL}; assert_eq!(1_000_000u64.format_size(DECIMAL), "1 MB"); assert_eq!((-1_000_000).format_size_i(DECIMAL), "-1 MB"); ``` ### ... to further customize the output: Humansize exports three default option sets: * `Decimal`: kilo = 1000, unit format is `XB`. * `Binary`: kilo = 1024, unit format is `XiB`. * `WINDOWS` (Windows): kilo = 1024, unit format is `XB`. The formatting can be further customized by providing providing your own option set. See the documentation of the `FormatSizeOptions` struct to see all the addressable parameters, and [this example](examples/custom_options.rs) for its usage. ### ... to accept negative values: The solutions presented above only accept unsigned integer types as input (`usize`, `8`, `u16`, `u32` and `u64`). If however accepting negative values is correct for your application, a signed alternative exists for each of them that will accept signed integer types, and format them accordingly if negative: - `format_size` : `format_size_i` - `create_format` : `create_format_i` - `FormatSize` trait : `FormatSizeI` trait - `SizeFormatter` : `ISizeFormatter` ```rust use humansize::{format_size_i, make_format_i, ISizeFormatter, DECIMAL}; assert_eq!(&format_size_i(-1_000_000, DECIMAL), "-1 MB"); let signed_formatter = make_format_i(DECIMAL); assert_eq!(&signed_formatter(-1_000_000), "-1 MB"); // With the `impl-style` feature enabled: // use humansize::FormatSizeI; // assert_eq(-1_000_000.format_size(DECIMAL), "-1 MB"); let signed_size_formatter = ISizeFormatter::new(-1_000_000, DECIMAL); assert_eq!(format!("{}", signed_size_formatter), "-1 MB"); ``` ## License This project is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in humansize by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.humansize-2.1.3/changelog.md000064400000000000000000000006120072674642500141320ustar 00000000000000# Changelog Dates are DD-MM-YYYY ## [2.1.1] 16-11-2022 - Added changelog - `Impl` `ToF64` for `f32` and `f64` so they can be used as inputs to the signed variants of the crate's utilities - Manually implement the `Default` trait for enums to lower the Minimum Supported Rust Version to 1.56. Thanks @link2txt - Added MSRV to cargo.toml. Thanks @link2txt - Added maintenance level badgehumansize-2.1.3/examples/custom_options.rs000064400000000000000000000005270072674642500171370ustar 00000000000000extern crate humansize; use humansize::{format_size, FormatSizeOptions, DECIMAL}; fn main() { // Create a new FormatSizeOptions struct starting from one of the defaults let custom_options = FormatSizeOptions::from(DECIMAL).decimal_places(5); // Then use it println!("{}", format_size(3024usize, custom_options)); } humansize-2.1.3/examples/sizes.rs000064400000000000000000000011400072674642500151770ustar 00000000000000extern crate humansize; use humansize::{format_size, format_size_i, SizeFormatter, ISizeFormatter, BINARY, DECIMAL, WINDOWS}; fn main() { println!("{}", format_size(5456usize, BINARY)); println!("{}", format_size(1024usize, DECIMAL)); println!("{}", format_size(1000usize, WINDOWS)); println!("{}", format_size(1_023_654_123_654_u64, BINARY)); println!("{}", format_size(123456789usize, DECIMAL)); println!("{}", format_size_i(-123456789, WINDOWS)); println!("{}", SizeFormatter::new(1234u32, BINARY)); println!("{}", ISizeFormatter::new(1234, BINARY)); } humansize-2.1.3/src/allocating.rs000064400000000000000000000013410072674642500151330ustar 00000000000000use alloc::string::String; use crate::numeric_traits::*; use crate::options::FormatSizeOptions; use crate::ISizeFormatter; pub fn format_size_i(input: impl ToF64, options: impl AsRef) -> String { format!("{}", ISizeFormatter::new(input, options)) } pub fn format_size(input: impl ToF64 + Unsigned, options: impl AsRef) -> String { format_size_i(input, &options) } pub fn make_format_i(options: impl AsRef) -> impl Fn(T) -> String { move |val| -> String { format_size_i(val, &options) } } pub fn make_format( options: impl AsRef, ) -> impl Fn(T) -> String { make_format_i(options) } humansize-2.1.3/src/formatters.rs000064400000000000000000000064120072674642500152100ustar 00000000000000use libm::{fabs, modf}; use crate::{scales, utils::f64_eq, BaseUnit, FormatSizeOptions, Kilo, ToF64, Unsigned}; pub struct ISizeFormatter> { value: T, options: O, } impl> ISizeFormatter { pub fn new(value: V, options: O) -> Self { ISizeFormatter { value, options } } } impl> core::fmt::Display for ISizeFormatter { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { let opts = self.options.as_ref(); let divider = opts.kilo.value(); let mut size: f64 = self.value.to_f64(); let mut scale_idx = 0; if let Some(val) = opts.fixed_at { while scale_idx != val as usize { size /= divider; scale_idx += 1; } } else { while fabs(size) >= divider { size /= divider; scale_idx += 1; } } let mut scale = match (opts.units, opts.long_units, opts.base_unit) { (Kilo::Decimal, false, BaseUnit::Byte) => scales::SCALE_DECIMAL[scale_idx], (Kilo::Decimal, true, BaseUnit::Byte) => scales::SCALE_DECIMAL_LONG[scale_idx], (Kilo::Binary, false, BaseUnit::Byte) => scales::SCALE_BINARY[scale_idx], (Kilo::Binary, true, BaseUnit::Byte) => scales::SCALE_BINARY_LONG[scale_idx], (Kilo::Decimal, false, BaseUnit::Bit) => scales::SCALE_DECIMAL_BIT[scale_idx], (Kilo::Decimal, true, BaseUnit::Bit) => scales::SCALE_DECIMAL_BIT_LONG[scale_idx], (Kilo::Binary, false, BaseUnit::Bit) => scales::SCALE_BINARY_BIT[scale_idx], (Kilo::Binary, true, BaseUnit::Bit) => scales::SCALE_BINARY_BIT_LONG[scale_idx], }; // Remove "s" from the scale if the size is 1.x let (fpart, ipart) = modf(size); if f64_eq(ipart, 1.0) && (opts.long_units || (opts.base_unit == BaseUnit::Bit && scale_idx == 0)) { scale = &scale[0..scale.len() - 1]; } let places = if f64_eq(fpart, 0.0) { opts.decimal_zeroes } else { opts.decimal_places }; let space = if opts.space_after_value { " " } else { "" }; write!(f, "{:.*}{}{}{}", places, size, space, scale, opts.suffix) } } impl<'a, U: ToF64 + Unsigned + Copy, O: AsRef> From<&'a SizeFormatter> for ISizeFormatter { fn from(source: &'a SizeFormatter) -> Self { ISizeFormatter { value: source.value, options: &source.options, } } } pub struct SizeFormatter> { value: T, options: O, } impl> SizeFormatter { pub fn new(value: V, options: O) -> Self { SizeFormatter { value, options } } } impl + Copy> core::fmt::Display for SizeFormatter { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "{}", ISizeFormatter::from(self)) } } humansize-2.1.3/src/impl_style.rs000064400000000000000000000012600072674642500151770ustar 00000000000000use crate::{FormatSizeOptions, SizeFormatter, ISizeFormatter, Signed, ToF64, Unsigned}; use alloc::string::String; pub trait FormatSize { fn format_size(&self, opts: FormatSizeOptions) -> String; } pub trait FormatSizeI { fn format_size_i(&self, opts: FormatSizeOptions) -> String; } impl FormatSize for T { fn format_size(&self, opts: FormatSizeOptions) -> String { format!("{}", SizeFormatter::new(*self, opts)) } } impl FormatSizeI for T { fn format_size_i(&self, opts: FormatSizeOptions) -> String { format!("{}", ISizeFormatter::new(*self, opts)) } } humansize-2.1.3/src/lib.rs000064400000000000000000000111360072674642500135670ustar 00000000000000#![no_std] /*! # **Humansize** ## Features Humansize is a humanization library for information size that is: - Simple & convenient to use - Customizable - Supports byte or bit sizes - `no-std` - Optionally non-allocating - Optionally accepts signed values ## How to use it... Add humansize as a dependency to your project's `cargo.toml`: ```toml [dependencies] ... humansize = "2.0.0" ``` ### ... to easily format a size: 1. Import the `format_size` function as well as your preferred set of defaults: - `DECIMAL` (SI) - `BINARY` (IEC) - `WINDOWS` (IEC values but SI units) 2. Call `format_size` with an unsigned integer ```rust use humansize::{format_size, DECIMAL}; let size = 1_000_000u64; let res: String = format_size(size, DECIMAL); assert_eq!(&res, "1 MB"); ``` ### ... to format many sizes: To improve reusability, you can use `create_format`, which returns a formatter function akin to `format_size` but with the options argument curried so it doesn't need to be specified again: ```rust use humansize::{make_format, DECIMAL}; let formatter = make_format(DECIMAL); assert_eq!(formatter(1_000_000u64), "1 MB"); assert_eq!(formatter(1_000_000_000u64), "1 GB"); //... ``` ### ... to avoid allocation: Specify the `no_alloc` feature flag in your project's `cargo.toml`: ```toml [dependencies] ... humansize = { version = "2.0.0", features = ["no_alloc"] } ``` This excludes all allocating code from compilation. You may now use the library's internal `SizeFormatter` struct, which implements `core::fmt::display` so that you can `write!` it to a custom buffer of your choice: ```rust use humansize::{SizeFormatter, DECIMAL}; let formatter = SizeFormatter::new(1_000_000usize, DECIMAL); assert_eq!(format!("{}", formatter), "1 MB"); ``` ### ... with the `impl` style API: For stylistic reasons, you may prefer to use the impl-style API of earlier versions of the crate. To do so, specify the `impl-style` feature flag in your project's `cargo.toml`: ```toml [dependencies] ... humansize = { version = "2.0.0", features = ["impl_style"] } ``` Enabling this feature makes two methods available: - `format_size` on unsigned integers types - `format_size_i` on signed integer types. To use it, bring the FormatSize trait into scope and call its method on an integer type: ```ignore use humansize::{FormatSize, FormatSizeI DECIMAL}; assert_eq!(1_000_000u64.format_size(DECIMAL), "1 MB"); assert_eq!((-1_000_000).format_size_i(DECIMAL), "-1 MB"); ``` ### ... to further customize the output: Humansize exports three default option sets: * `Decimal`: kilo = 1000, unit format is `XB`. * `Binary`: kilo = 1024, unit format is `XiB`. * `WINDOWS` (Windows): kilo = 1024, unit format is `XB`. The formatting can be further customized by providing providing your own option set. See the documentation of the `FormatSizeOptions` struct to see all the addressable parameters, and [this example](examples/custom_options.rs) for its usage. ### ... to accept negative values: The solutions presented above only accept unsigned integer types as input (`usize`, `8`, `u16`, `u32` and `u64`). If however accepting negative values is correct for your application, a signed alternative exists for each of them that will accept signed integer types, and format them accordingly if negative: - `format_size` : `format_size_i` - `create_format` : `create_format_i` - `FormatSize` trait : `FormatSizeI` trait - `SizeFormatter` : `ISizeFormatter` ```rust use humansize::{format_size_i, make_format_i, ISizeFormatter, DECIMAL}; assert_eq!(&format_size_i(-1_000_000, DECIMAL), "-1 MB"); let signed_formatter = make_format_i(DECIMAL); assert_eq!(&signed_formatter(-1_000_000), "-1 MB"); // With the `impl-style` feature enabled: // use humansize::FormatSizeI; // assert_eq(-1_000_000.format_size(DECIMAL), "-1 MB"); let signed_size_formatter = ISizeFormatter::new(-1_000_000, DECIMAL); assert_eq!(format!("{}", signed_size_formatter), "-1 MB"); ``` */ #[macro_use] #[cfg(not(feature = "no_alloc"))] extern crate alloc; extern crate libm; mod options; pub use options::{BaseUnit, FixedAt, FormatSizeOptions, Kilo, BINARY, DECIMAL, WINDOWS}; mod numeric_traits; pub use numeric_traits::{Signed, ToF64, Unsigned}; mod scales; mod utils; #[cfg(not(feature = "no_alloc"))] mod allocating; #[cfg(not(feature = "no_alloc"))] pub use allocating::*; #[cfg(feature = "impl_style")] mod impl_style; #[cfg(feature = "impl_style")] pub use impl_style::{FormatSize, FormatSizeI}; mod formatters; pub use formatters::{SizeFormatter, ISizeFormatter}; humansize-2.1.3/src/numeric_traits.rs000064400000000000000000000011760072674642500160540ustar 00000000000000pub trait ToF64 { fn to_f64(&self) -> f64; } macro_rules! impl_to_f64 { (for $($t:ty)*) => ($( impl ToF64 for $t { fn to_f64(&self) -> f64 { *self as f64 } } )*) } impl_to_f64!(for usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64); pub trait Unsigned {} macro_rules! impl_unsigned { (for $($t:ty)*) => ($( impl Unsigned for $t {} )*) } impl_unsigned!(for usize u8 u16 u32 u64); pub trait Signed {} macro_rules! impl_unsigned { (for $($t:ty)*) => ($( impl Signed for $t {} )*) } impl_unsigned!(for isize i8 i16 i32 i64); humansize-2.1.3/src/options/defaults.rs000064400000000000000000000022260072674642500163230ustar 00000000000000use super::{BaseUnit, FormatSizeOptions, Kilo}; /// Options to display sizes in the SI format. pub const BINARY: FormatSizeOptions = FormatSizeOptions { base_unit: BaseUnit::Byte, kilo: Kilo::Binary, units: Kilo::Binary, decimal_places: 2, decimal_zeroes: 0, fixed_at: None, long_units: false, space_after_value: true, suffix: "", }; /// Options to display sizes in the SI (decimal) format. pub const DECIMAL: FormatSizeOptions = FormatSizeOptions { base_unit: BaseUnit::Byte, kilo: Kilo::Decimal, units: Kilo::Decimal, decimal_places: 2, decimal_zeroes: 0, fixed_at: None, long_units: false, space_after_value: true, suffix: "", }; /// Options to display sizes in the "WINDOWS" format. /// Uses 1024 as the value of the `Kilo`, but displays decimal-style units (`kB`, not `KiB`). pub const WINDOWS: FormatSizeOptions = FormatSizeOptions { base_unit: BaseUnit::Byte, kilo: Kilo::Binary, units: Kilo::Decimal, decimal_places: 2, decimal_zeroes: 0, fixed_at: None, long_units: false, space_after_value: true, suffix: "", }; humansize-2.1.3/src/options/mod.rs000064400000000000000000000112340072674642500152720ustar 00000000000000//! Describes the struct that holds the options needed by the formatting functions. //! The three most common formats are provided as constants to be used easily mod defaults; pub use self::defaults::*; #[derive(Debug, PartialEq, Eq, Copy, Clone)] /// Holds the standard to use when displaying the size. pub enum Kilo { /// The decimal scale and units. SI standard. Decimal, /// The binary scale and units. Binary, } impl Default for Kilo { fn default() -> Self { Self::Decimal } } impl Kilo { pub(crate) fn value(&self) -> f64 { match self { Kilo::Decimal => 1000.0, Kilo::Binary => 1024.0, } } } #[derive(Debug, Copy, Clone)] /// Forces a certain representation of the resulting file size. pub enum FixedAt { Base, Kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta, } #[derive(Debug, Copy, Clone, PartialEq)] pub enum BaseUnit { Bit, Byte, } impl Default for BaseUnit { fn default() -> Self { Self::Byte } } /// Holds the options for the `file_size` method. #[derive(Debug, Clone, Copy, Default)] #[non_exhaustive] pub struct FormatSizeOptionsBuilder { /// Whether the value being formatted represents an amount of bits or bytes. pub base_unit: BaseUnit, /// The scale (binary/decimal) to divide against. pub kilo: Kilo, /// The unit set to display. pub units: Kilo, /// The amount of decimal places to display if the decimal part is non-zero. pub decimal_places: usize, /// The amount of zeroes to display if the decimal part is zero. pub decimal_zeroes: usize, /// Whether to force a certain representation and if so, which one. pub fixed_at: Option, /// Whether to use the full unit (e.g. `Kilobyte`) or its abbreviation (`kB`). pub long_units: bool, /// Whether to place a space between value and units. pub space_after_value: bool, /// An optional suffix which will be appended after the unit. Useful to represent speeds (e.g. `1 kB/s) pub suffix: &'static str, } /// Holds the options for the `file_size` method. #[derive(Debug, Clone, Copy, Default)] #[non_exhaustive] pub struct FormatSizeOptions { /// Whether the value being formatted represents an amount of bits or bytes. pub base_unit: BaseUnit, /// The scale (binary/decimal) to divide against. pub kilo: Kilo, /// The unit set to display. pub units: Kilo, /// The amount of decimal places to display if the decimal part is non-zero. pub decimal_places: usize, /// The amount of zeroes to display if the decimal part is zero. pub decimal_zeroes: usize, /// Whether to force a certain representation and if so, which one. pub fixed_at: Option, /// Whether to use the full unit (e.g. `Kilobyte`) or its abbreviation (`kB`). pub long_units: bool, /// Whether to place a space between value and units. pub space_after_value: bool, /// An optional suffix which will be appended after the unit. Useful to represent speeds (e.g. `1 kB/s) pub suffix: &'static str, } impl FormatSizeOptions { pub fn from(from: FormatSizeOptions) -> FormatSizeOptions { FormatSizeOptions { ..from } } pub fn base_unit(mut self, base_unit: BaseUnit) -> FormatSizeOptions { self.base_unit = base_unit; self } pub fn kilo(mut self, kilo: Kilo) -> FormatSizeOptions { self.kilo = kilo; self } pub fn units(mut self, units: Kilo) -> FormatSizeOptions { self.units = units; self } pub fn decimal_places(mut self, decimal_places: usize) -> FormatSizeOptions { self.decimal_places = decimal_places; self } pub fn decimal_zeroes(mut self, decimal_zeroes: usize) -> FormatSizeOptions { self.decimal_zeroes = decimal_zeroes; self } pub fn fixed_at(mut self, fixed_at: Option) -> FormatSizeOptions { self.fixed_at = fixed_at; self } pub fn long_units(mut self, long_units: bool) -> FormatSizeOptions { self.long_units = long_units; self } pub fn space_after_value(mut self, insert_space: bool) -> FormatSizeOptions { self.space_after_value = insert_space; self } pub fn suffix(mut self, suffix: &'static str) -> FormatSizeOptions { self.suffix = suffix; self } } impl AsRef for FormatSizeOptions { fn as_ref(&self) -> &FormatSizeOptions { self } } humansize-2.1.3/src/scales.rs000064400000000000000000000024440072674642500142750ustar 00000000000000pub(crate) static SCALE_DECIMAL: [&str; 9] = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; pub(crate) static SCALE_DECIMAL_LONG: [&str; 9] = [ "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Petabytes", "Exabytes", "Zettabytes", "Yottabytes", ]; pub(crate) static SCALE_BINARY: [&str; 9] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; pub(crate) static SCALE_BINARY_LONG: [&str; 9] = [ "Bytes", "Kibibytes", "Mebibytes", "Gibibytes", "Tebibytes", "Pebibytes", "Exbibytes", "Zebibytes", "Yobibytes", ]; pub(crate) static SCALE_DECIMAL_BIT: [&str; 9] = [ "bits", "kbit", "Mbit", "Gbit", "Tbit", "Pbit", "Ebit", "Zbit", "Ybit", ]; pub(crate) static SCALE_DECIMAL_BIT_LONG: [&str; 9] = [ "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Petabits", "Exabits", "Zettabits", "Yottabits", ]; pub(crate) static SCALE_BINARY_BIT: [&str; 9] = [ "bits", "Kibit", "Mibit", "Gibit", "Tibit", "Pibit", "Eibit", "Zibit", "Yibit", ]; pub(crate) static SCALE_BINARY_BIT_LONG: [&str; 9] = [ "bits", "Kibibits", "Mebibits", "Gibibits", "Tebibits", "Pebibits", "Exbibits", "Zebibits", "Yobibits", ]; humansize-2.1.3/src/utils.rs000064400000000000000000000002060072674642500141550ustar 00000000000000use libm::fabs; pub(crate) fn f64_eq(left: f64, right: f64) -> bool { left == right || fabs(left - right) <= f64::EPSILON } humansize-2.1.3/tests/test.rs000064400000000000000000000075250072674642500143620ustar 00000000000000use humansize::{ format_size, format_size_i, BaseUnit, FixedAt, FormatSizeOptions, BINARY, DECIMAL, WINDOWS, }; #[test] fn test_sizes() { assert_eq!(format_size(0u32, BINARY), "0 B"); assert_eq!(format_size(999u32, BINARY), "999 B"); assert_eq!(format_size(1000u32, BINARY), "1000 B"); assert_eq!(format_size(1000u32, DECIMAL), "1 kB"); assert_eq!(format_size(1023u32, BINARY), "1023 B"); assert_eq!(format_size(1023u32, DECIMAL), "1.02 kB"); assert_eq!(format_size(1024u32, BINARY), "1 KiB"); assert_eq!(format_size(1024u32, WINDOWS), "1 kB"); assert_eq!(format_size_i(1000f32, DECIMAL), "1 kB"); assert_eq!(format_size_i(1000f64, DECIMAL), "1 kB"); let custom_options = FormatSizeOptions::from(DECIMAL).space_after_value(false); assert_eq!(format_size(1000u32, custom_options), "1kB"); let custom_options = FormatSizeOptions::from(BINARY).suffix("/s"); assert_eq!(format_size(999u32, custom_options), "999 B/s"); let custom_options = FormatSizeOptions::from(DECIMAL) .suffix("/day") .space_after_value(false); assert_eq!(format_size(1000u32, custom_options), "1kB/day"); let custom_options = FormatSizeOptions::from(BINARY).fixed_at(Some(FixedAt::Base)); assert_eq!(format_size(2048u32, custom_options), "2048 B"); let custom_options = FormatSizeOptions::from(BINARY) .fixed_at(Some(FixedAt::Base)) .long_units(true); assert_eq!(format_size(2048u32, custom_options), "2048 Bytes"); let custom_options = FormatSizeOptions::from(BINARY).fixed_at(Some(FixedAt::Kilo)); assert_eq!(format_size(16584975u32, custom_options), "16196.26 KiB"); assert_eq!(format_size_i(-16584975, custom_options), "-16196.26 KiB"); let custom_options = FormatSizeOptions::from(BINARY) .fixed_at(Some(FixedAt::Tera)) .decimal_places(10); assert_eq!(format_size(15284975u32, custom_options), "0.0000139016 TiB"); assert_eq!((format_size_i(-5500, DECIMAL)), "-5.50 kB"); assert_eq!((format_size(5500u32, DECIMAL)), "5.50 kB"); let custom_options = FormatSizeOptions::from(DECIMAL).base_unit(BaseUnit::Bit); assert_eq!((format_size(1usize, custom_options)), "1 bit"); assert_eq!((format_size(150usize, custom_options)), "150 bits"); assert_eq!((format_size(1000usize, custom_options)), "1 kbit"); } #[test] fn use_custom_option_struct_twice() { let options = FormatSizeOptions::from(DECIMAL).long_units(true); assert_eq!(format_size(1500u32, &options), "1.50 Kilobyte",); assert_eq!(format_size(2500u32, &options), "2.50 Kilobytes",); assert_eq!(format_size_i(-2500000, &options), "-2.50 Megabytes",); } #[test] fn pluralization_works() { let options = FormatSizeOptions::from(DECIMAL) .long_units(true) .decimal_zeroes(2); assert_eq!(format_size(1u32, &options), "1.00 Byte",); assert_eq!(format_size(1000u32, &options), "1.00 Kilobyte",); assert_eq!(format_size(1000000u32, &options), "1.00 Megabyte",); assert_eq!(format_size(1000000000u32, &options), "1.00 Gigabyte",); assert_eq!(format_size_i(1000000000000_i64, &options), "1.00 Terabyte",); assert_eq!( format_size_i(1000000000000000_i64, &options), "1.00 Petabyte", ); assert_eq!( format_size_i(1000000000000000000_i64, &options), "1.00 Exabyte", ); } #[test] fn max_value_decimal() { let options = FormatSizeOptions::from(DECIMAL) .decimal_places(7) .long_units(true); assert_eq!(format_size(core::u64::MAX, &options), "18.4467441 Exabytes",); } #[test] fn max_value_binary() { let options = FormatSizeOptions::from(BINARY) .decimal_places(7) .long_units(true); assert_eq!(format_size(core::u64::MAX, &options), "16 Exbibytes",); }