size_format-1.0.2/.gitignore010064400017500001750000000000361335516301500142460ustar0000000000000000/target **/*.rs.bk Cargo.lock size_format-1.0.2/Cargo.toml.orig010064400017500001750000000006601335643714600151620ustar0000000000000000[package] name = "size_format" version = "1.0.2" authors = ["aticu <15schnic@gmail.com>"] license = "MIT OR Apache-2.0" description = "Allows for easier formatting of sizes." repository = "https://github.com/aticu/size_format" keywords = ["size", "prefix", "unit", "format", "no_std"] categories = ["value-formatting"] readme = "README.md" [dependencies] num = { version = "0.2", default-features = false } generic-array = "0.12.0"size_format-1.0.2/Cargo.toml0000644000000017150000000000000114170ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "size_format" version = "1.0.2" authors = ["aticu <15schnic@gmail.com>"] description = "Allows for easier formatting of sizes." readme = "README.md" keywords = ["size", "prefix", "unit", "format", "no_std"] categories = ["value-formatting"] license = "MIT OR Apache-2.0" repository = "https://github.com/aticu/size_format" [dependencies.generic-array] version = "0.12.0" [dependencies.num] version = "0.2" default-features = false size_format-1.0.2/LICENSE-APACHE010064400017500001750000000251371335642143300142150ustar0000000000000000 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. size_format-1.0.2/LICENSE-MIT010064400017500001750000000020571335642142400137210ustar0000000000000000The MIT License (MIT) Copyright (c) 2018 aticu 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.size_format-1.0.2/README.md010064400017500001750000000050621335641652100135450ustar0000000000000000# size_format This is a rust crate providing formatting for sizes using prefixes. For example 4000 bytes could be formatted as 4.0kB. The main goal is to provide easy formatters for data sizes. It provides both binary and SI unit prefixes per default, though more could be added. ```rust use size_format::{SizeFormatterBinary, SizeFormatterSI}; assert_eq!( format!("{}B", SizeFormatterBinary::new(42 * 1024 * 1024)), "42.0MiB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(42_000_000)), "42.0MB".to_string() ); ``` The precision can also be specified. Please note that values are always rounded down. ```rust use size_format::SizeFormatterSI; assert_eq!( format!("{:.4}B", SizeFormatterSI::new(1_999_999_999)), "1.9999GB".to_string() ); assert_eq!( format!("{:.0}B", SizeFormatterSI::new(1_999_999_999)), "1GB".to_string() ); ``` The presented precision will also never exceed the available precision. ```rust use size_format::SizeFormatterSI; assert_eq!( format!("{:.10}B", SizeFormatterSI::new(678)), "678B".to_string() ); assert_eq!( format!("{:.10}B", SizeFormatterSI::new(1_999)), "1.999kB".to_string() ); ``` For more flexibility, use the `SizeFormatter` type directly with the correct type parameters. For example the following code formats a `u16` using binary prefixes and uses a comma as a separator. ```rust use size_format::{BinaryPrefixes, CommaSeparated, SizeFormatter}; assert_eq!( format!("{:.2}B", SizeFormatter::::from(65_535u16)), "63,99KiB".to_string() ); ``` Although this crate was mainly intended for data sizes, it can also be used for other units. It is also possible to implement the `PrefixType` trait to make your own prefix system. ```rust use size_format::{PointSeparated, PrefixType, SizeFormatter}; use generic_array::{typenum::U3, GenericArray}; struct Millimeter; impl PrefixType for Millimeter { type N = U3; const PREFIX_SIZE: u32 = 1000; fn prefixes() -> GenericArray<&'static str, Self::N> { ["m", "", "k"].into() } } assert_eq!( format!("{}m", SizeFormatter::::new(1)), "1mm".to_string() ); assert_eq!( format!("{}m", SizeFormatter::::new(1_000)), "1.0m".to_string() ); assert_eq!( format!("{}m", SizeFormatter::::new(1_000_000)), "1.0km".to_string() ); assert_eq!( format!("{}m", SizeFormatter::::new(10_000_000_000)), "10000.0km".to_string() ); ```size_format-1.0.2/src/config.rs010064400017500001750000000032361335623404700146720ustar0000000000000000//! This module contains all customization options for the formatting. use generic_array::{typenum::U9, ArrayLength, GenericArray}; /// A trait for marker types that represent decimal separators. pub trait DecimalSeparator { /// The separator to use. const SEPARATOR: char; } /// Represents a comma separation scheme for numbers (','). pub struct CommaSeparated; impl DecimalSeparator for CommaSeparated { const SEPARATOR: char = ','; } /// Represents a point or dot separation scheme for numbers ('.'). pub struct PointSeparated; impl DecimalSeparator for PointSeparated { const SEPARATOR: char = '.'; } /// Abstracts over the types of prefixes possible. pub trait PrefixType { /// The number of prefixes in the prefix array. type N: ArrayLength<&'static str>; /// Returns the size of the prefix used. /// /// For the metric system for example that would be 1000. const PREFIX_SIZE: u32; /// Represents the prefixes used by the prefix type. fn prefixes() -> GenericArray<&'static str, Self::N>; } /// Represents the prefixes used in the SI system of measurements. pub struct SIPrefixes; impl PrefixType for SIPrefixes { type N = U9; const PREFIX_SIZE: u32 = 1000; fn prefixes() -> GenericArray<&'static str, Self::N> { ["", "k", "M", "G", "T", "P", "E", "Z", "Y"].into() } } /// Represents the prefixes used for display file sizes using powers of 1024. pub struct BinaryPrefixes; impl PrefixType for BinaryPrefixes { type N = U9; const PREFIX_SIZE: u32 = 1024; fn prefixes() -> GenericArray<&'static str, Self::N> { ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"].into() } } size_format-1.0.2/src/lib.rs010064400017500001750000000334121335643415200141710ustar0000000000000000//! # size_format //! //! This crate provides formatting for sizes. //! //! The main goal is to provide easy formatters for data sizes. //! //! It provides both binary and SI unit prefixes per default, though more could be added. //! ``` //! use size_format::{SizeFormatterBinary, SizeFormatterSI}; //! //! assert_eq!( //! format!("{}B", SizeFormatterBinary::new(42 * 1024 * 1024)), //! "42.0MiB".to_string() //! ); //! assert_eq!( //! format!("{}B", SizeFormatterSI::new(42_000_000)), //! "42.0MB".to_string() //! ); //! ``` //! //! The precision can also be specified. Please note that values are always rounded down. //! ``` //! use size_format::SizeFormatterSI; //! //! assert_eq!( //! format!("{:.4}B", SizeFormatterSI::new(1_999_999_999)), //! "1.9999GB".to_string() //! ); //! assert_eq!( //! format!("{:.0}B", SizeFormatterSI::new(1_999_999_999)), //! "1GB".to_string() //! ); //! ``` //! //! The presented precision will also never exceed the available precision. //! ``` //! use size_format::SizeFormatterSI; //! //! assert_eq!( //! format!("{:.10}B", SizeFormatterSI::new(678)), //! "678B".to_string() //! ); //! assert_eq!( //! format!("{:.10}B", SizeFormatterSI::new(1_999)), //! "1.999kB".to_string() //! ); //! ``` //! //! For more flexibility, use the `SizeFormatter` type directly with the correct type parameters. //! For example the following code formats a `u16` using binary prefixes and uses a comma as a separator. //! ``` //! use size_format::{BinaryPrefixes, CommaSeparated, SizeFormatter}; //! //! assert_eq!( //! format!("{:.2}B", SizeFormatter::::from(65_535u16)), //! "63,99KiB".to_string() //! ); //! ``` //! //! Although this crate was mainly intended for data sizes, it can also be used for other units. //! //! It is also possible to implement the `PrefixType` trait to make your own prefix system. //! ``` //! extern crate generic_array; //! extern crate size_format; //! //! use size_format::{PointSeparated, PrefixType, SizeFormatter}; //! use generic_array::{typenum::U3, GenericArray}; //! //! struct Millimeter; //! //! impl PrefixType for Millimeter { //! type N = U3; //! //! const PREFIX_SIZE: u32 = 1000; //! //! fn prefixes() -> GenericArray<&'static str, Self::N> { //! ["m", "", "k"].into() //! } //! } //! //! assert_eq!( //! format!("{}m", SizeFormatter::::new(1)), //! "1mm".to_string() //! ); //! assert_eq!( //! format!("{}m", SizeFormatter::::new(1_000)), //! "1.0m".to_string() //! ); //! assert_eq!( //! format!("{}m", SizeFormatter::::new(1_000_000)), //! "1.0km".to_string() //! ); //! assert_eq!( //! format!("{}m", SizeFormatter::::new(10_000_000_000)), //! "10000.0km".to_string() //! ); //! ``` #![no_std] #![warn(missing_docs)] extern crate generic_array; extern crate num; use core::{ cmp, fmt::{self, Display}, marker::PhantomData, }; use num::{integer::Integer, rational::Ratio, traits::cast::FromPrimitive, traits::Pow}; mod config; pub use self::config::{ BinaryPrefixes, CommaSeparated, DecimalSeparator, PointSeparated, PrefixType, SIPrefixes, }; /// The precision to use by default for formatting the numbers. const DEFAULT_PRECISION: usize = 1; /// Implements `Display` to format the contained byte size using SI prefixes. pub type SizeFormatterSI = SizeFormatter; /// Implements `Display` to format the contained byte size using binary prefixes. pub type SizeFormatterBinary = SizeFormatter; /// Represents a size that can be formatted. /// /// # Panics /// - May panic if the `BaseType` is too small for the prefix specified in `Prefix` /// and the number is being formatted. pub struct SizeFormatter where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, Prefix: PrefixType, Separator: DecimalSeparator, { /// The number to be formatted. num: BaseType, _marker: PhantomData<(Prefix, Separator)>, } impl SizeFormatter where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, Prefix: PrefixType, Separator: DecimalSeparator, { /// Creates a new size formatter for the given number. pub fn new(num: BaseType) -> SizeFormatter { SizeFormatter { num, _marker: PhantomData, } } /// Creates a new size formatter from a compatible number. pub fn from>(num: T) -> SizeFormatter { SizeFormatter { num: num.into(), _marker: PhantomData, } } } impl Display for SizeFormatter where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, Prefix: PrefixType, Separator: DecimalSeparator, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let max_prefix = Prefix::prefixes().len() - 1; let precision = f.precision().unwrap_or(DEFAULT_PRECISION); let prefix_size = BaseType::from_u32(Prefix::PREFIX_SIZE) .expect("prefix size is too large for number type"); // Find the right prefix. let divisions = cmp::min(int_log(self.num.clone(), prefix_size.clone()), max_prefix); // Cap the precision to what makes sense. let precision = cmp::min(precision, divisions * 3); let ratio = Ratio::::new(self.num.clone(), prefix_size.pow(divisions as u32)); let format_number = FormatRatio::::new(ratio); write!( f, "{:.*}{}", precision, format_number, Prefix::prefixes()[divisions] ) } } /// Returns the number of times `num` can be divided by `base`. fn int_log(mut num: BaseType, base: BaseType) -> usize where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, { let mut divisions = 0; while num >= base { num = num / base.clone(); divisions += 1; } divisions } /// This allows formatting a ratio as a decimal number. /// /// This is a temporary solution until support for that is added to the `num` crate. struct FormatRatio where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, Separator: DecimalSeparator, { num: Ratio, _marker: PhantomData, } impl FormatRatio where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, Separator: DecimalSeparator, { /// Creates a new format ratio from the number. fn new(num: Ratio) -> FormatRatio { FormatRatio { num, _marker: PhantomData, } } } impl Display for FormatRatio where BaseType: Clone + Integer + Display + FromPrimitive + Pow, Ratio: FromPrimitive, Separator: DecimalSeparator, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.num.trunc())?; let precision = f.precision().unwrap_or(DEFAULT_PRECISION); if precision > 0 { write!(f, "{}", Separator::SEPARATOR)?; let mut frac = self.num.fract(); for _ in 0..precision { if frac.is_integer() { // If the fractional part is an integer, we're done and just need more zeroes. write!(f, "0")?; } else { // Otherwise print every digit separately. frac = frac * Ratio::from_u64(10).unwrap(); write!(f, "{}", frac.trunc())?; frac = frac.fract(); } } } Ok(()) } } #[cfg(test)] #[macro_use] extern crate std; #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn small_sizes() { assert_eq!(format!("{}B", SizeFormatterSI::new(0)), "0B".to_string()); assert_eq!(format!("{}B", SizeFormatterSI::new(1)), "1B".to_string()); assert_eq!( format!("{}B", SizeFormatterSI::new(999)), "999B".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(0)), "0B".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(1)), "1B".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(999)), "999B".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(1_000)), "1.0kB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(55_000)), "55.0kB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(999_999)), "999.9kB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(1_000_000)), "1.0MB".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(1 * 1024)), "1.0KiB".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(55 * 1024)), "55.0KiB".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(999 * 1024 + 1023)), "999.9KiB".to_string() ); assert_eq!( format!("{}B", SizeFormatterBinary::new(1 * 1024 * 1024)), "1.0MiB".to_string() ); } #[test] fn big_sizes() { assert_eq!( format!("{}B", SizeFormatterSI::new(387_854_348_875)), "387.8GB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(123_456_789_999_999)), "123.4TB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(499_999_999_999_999_999)), "499.9PB".to_string() ); assert_eq!( format!("{}B", SizeFormatterSI::new(1_000_000_000_000_000_000)), "1.0EB".to_string() ); assert_eq!( format!( "{}B", SizeFormatter::::new( 1_000_000_000_000_000_000_000 ) ), "1.0ZB".to_string() ); assert_eq!( format!( "{}B", SizeFormatter::::new( 1_000_000_000_000_000_000_000_000 ) ), "1.0YB".to_string() ); } #[test] fn exceeds_yotta() { assert_eq!( format!( "{}B", SizeFormatter::::new( 1_000_000_000_000_000_000_000_000_000 ) ), "1000.0YB".to_string() ); assert_eq!( format!( "{}B", SizeFormatter::::new( 1_000_000_000_000_000_000_000_000_000_000 ) ), "1000000.0YB".to_string() ); } #[test] fn precision() { assert_eq!(format!("{:.9}B", SizeFormatterSI::new(1)), "1B".to_string()); assert_eq!( format!("{:.0}B", SizeFormatterSI::new(1_111)), "1kB".to_string() ); assert_eq!( format!("{:.1}B", SizeFormatterSI::new(1_111)), "1.1kB".to_string() ); assert_eq!( format!("{:.2}B", SizeFormatterSI::new(1_111)), "1.11kB".to_string() ); assert_eq!( format!("{:.3}B", SizeFormatterSI::new(1_111)), "1.111kB".to_string() ); assert_eq!( format!("{:.4}B", SizeFormatterSI::new(1_111)), "1.111kB".to_string() ); assert_eq!( format!("{:.4}B", SizeFormatterSI::new(1_000_100)), "1.0001MB".to_string() ); assert_eq!( format!("{:.4}B", SizeFormatterSI::new(1_500_000)), "1.5000MB".to_string() ); assert_eq!( format!("{:.4}B", SizeFormatterSI::new(1_000_000)), "1.0000MB".to_string() ); } #[test] fn configurations() { assert_eq!( format!( "{}B", SizeFormatter::::new(65_535) ), "65,5kB".to_string() ); assert_eq!( format!( "{}B", SizeFormatter::::new(65_535) ), "63.9KiB".to_string() ); } #[test] fn from() { assert_eq!( format!("{}B", SizeFormatterSI::from(546_987u32)), "546.9kB".to_string() ); } #[test] #[should_panic(expected = "prefix size is too large")] fn incompatile_base_type_fails() { assert_eq!( format!( "{}B", SizeFormatter::::new(10) ), "65.5kB".to_string() ); } } size_format-1.0.2/tests/new_prefix.rs010064400017500001750000000021131335643374300161430ustar0000000000000000extern crate generic_array; extern crate size_format; use generic_array::{typenum::U3, GenericArray}; use size_format::{PointSeparated, PrefixType, SizeFormatter}; struct Millimeter; impl PrefixType for Millimeter { type N = U3; const PREFIX_SIZE: u32 = 1000; fn prefixes() -> GenericArray<&'static str, Self::N> { ["m", "", "k"].into() } } #[test] fn new_prefix_works() { assert_eq!( format!( "{}m", SizeFormatter::::new(1) ), "1mm".to_string() ); assert_eq!( format!( "{}m", SizeFormatter::::new(1_000) ), "1.0m".to_string() ); assert_eq!( format!( "{}m", SizeFormatter::::new(1_000_000) ), "1.0km".to_string() ); assert_eq!( format!( "{}m", SizeFormatter::::new(10_000_000_000) ), "10000.0km".to_string() ); } size_format-1.0.2/tests/no_std.rs010064400017500001750000000004521335643345400152660ustar0000000000000000#![no_std] extern crate size_format; #[cfg(test)] #[macro_use] extern crate std; #[cfg(test)] use std::string::ToString; use size_format::SizeFormatterSI; #[test] fn no_std_works() { assert_eq!( format!("{}B", SizeFormatterSI::new(8_500_000)), "8.5MB".to_string() ); } size_format-1.0.2/tests/std.rs010064400017500001750000000003051335643337100145650ustar0000000000000000extern crate size_format; use size_format::SizeFormatterSI; #[test] fn std_works() { assert_eq!( format!("{}B", SizeFormatterSI::new(8_500_000)), "8.5MB".to_string() ); } size_format-1.0.2/.cargo_vcs_info.json0000644000000001120000000000000134070ustar00{ "git": { "sha1": "6ac248e6b3a683148f0a7ecd132a3958af4e5d01" } }