thousands-0.2.0/.gitignore010066000007660000024000000000231334753567300137420ustar0000000000000000target/ Cargo.lock thousands-0.2.0/.travis.yml010066000007660000024000000002631355275012100140520ustar0000000000000000language: rust rust: - stable - beta - nightly - 1.22.0 matrix: allow_failures: - rust: nightly fast_finish: true notifications: email: on_success: never thousands-0.2.0/Cargo.toml.orig010066000007660000024000000006341355275046000146400ustar0000000000000000[package] name = "thousands" version = "0.2.0" authors = ["Jesse A. Tov "] description = "Adds digit separators to numbers, configurably." repository = "https://github.com/tov/thousands-rs" readme = "README.md" license = "MIT/Apache-2.0" keywords = ["numbers", "formatting", "separators", "commas"] categories = ["value-formatting"] [badges] travis-ci = { repository = "tov/thousands-rs" } thousands-0.2.0/Cargo.toml0000644000000016420000000000000111030ustar00# 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 = "thousands" version = "0.2.0" authors = ["Jesse A. Tov "] description = "Adds digit separators to numbers, configurably." readme = "README.md" keywords = ["numbers", "formatting", "separators", "commas"] categories = ["value-formatting"] license = "MIT/Apache-2.0" repository = "https://github.com/tov/thousands-rs" [badges.travis-ci] repository = "tov/thousands-rs" thousands-0.2.0/CHANGELOG.md010066000007660000024000000020441355275046000135570ustar0000000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog] and this project adheres to [Semantic Versioning]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ [Semantic Versioning]: http://semver.org/spec/v2.0.0.html ## [0.1.4] - 2019-10-19 ### Changed - The separator is now a `&str` rather than a `char`. - Oldest supported rustc version is now 1.22.0. ### Added - A non-blanket `impl Separable for str` allocates only once, for the result, rather than twice as the blanket `Display`-based `impl` does. - An empty group array results in no separators. ### Fixed - Now respects UTF-8 for the separator as well. ## [0.1.4] - 2019-10-19 ### Fixed - Now respects UTF-8. ## [0.1.3] - 2019-10-19 ### Added - `Separable::separate_with_underscores` method and `policies::UNDERSCORE_SEPARATOR` constant. ## [0.1.2] - 2018-09-18 ### Fixed - Github URL in Cargo.toml. ## [0.1.1] - 2018-09-16 ### Added - Doc comment for `policies` module. ## [0.1.0] - 2018-09-16 Initial release. thousands-0.2.0/LICENSE-APACHE010066000007660000024000000251371334754004600137010ustar0000000000000000 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. thousands-0.2.0/LICENSE-MIT010066000007660000024000000020401334754416000133760ustar0000000000000000Copyright (c) 2018 Jesse A. Tov 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. thousands-0.2.0/README.md010066000007660000024000000032771355275046000132360ustar0000000000000000# thousands [![Build Status](https://travis-ci.org/tov/thousands-rs.svg?branch=master)](https://travis-ci.org/tov/thousands-rs) [![Crates.io](https://img.shields.io/crates/v/thousands.svg?maxAge=2592000)](https://crates.io/crates/thousands) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE-MIT) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-APACHE) Provides a trait, `Separable`, for formatting numbers with separators between the digits. Typically this will be used to add commas or spaces every three digits from the right, but can be configured via a `SeparatorPolicy`. ## Examples The simplest way to use the library is with trait `Separable`’s method `separate_with_commas` method, which does what it sounds like: ```rust use thousands::Separable; assert_eq!( 12345 .separate_with_commas(), "12,345" ); assert_eq!( (-12345) .separate_with_commas(), "-12,345" ); assert_eq!( 9876.5.separate_with_commas(), "9,876.5" ); ``` There are also methods `separate_with_spaces`, `separate_with_dots`, and `separate_with_underscores`, in case you, your culture, or your file format prefer those separators. However, it's also possible to pass a policy for different behavior: ```rust use thousands::{Separable, SeparatorPolicy, digits}; let policy = SeparatorPolicy { separator: ',', groups: &[3, 2], digits: digits::ASCII_DECIMAL, }; assert_eq!( 1234567890.separate_by_policy(policy), "1,23,45,67,890" ); ``` ## Usage It’s [on crates.io](https://crates.io/crates/thousands), so you can add ```toml [dependencies] thousands = "0.2.0" ``` to your `Cargo.toml`. This crate supports Rust version 1.22 and newer. thousands-0.2.0/release.toml010064000007660000024000000006631334754447300142750ustar0000000000000000pre-release-replacements = [ { file="README.md", search="thousands = \"[0-9.]*\"", replace="thousands = \"{{version}}\"" }, { file="src/lib.rs", search="thousands = \"[0-9.]*\"", replace="thousands = \"{{version}}\"" }, { file="src/lib.rs", search="https://docs[.]rs/thousands/[0-9.]*", replace="https://docs.rs/thousands/{{version}}" }, { file="CHANGELOG.md", search="\\[Unreleased\\]", replace="[{{version}}] - {{date}}" } ] thousands-0.2.0/src/digits.rs010064400007660000024000000005131355270135300143640ustar0000000000000000/// The decimal digits, in ASCII. pub const ASCII_DECIMAL: &[char] = &[ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ]; /// The hexadecimal digits, in ASCII. pub const ASCII_HEXADECIMAL: &[char] = &[ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', ]; thousands-0.2.0/src/display.rs010066000007660000024000000054771355275012100145570ustar0000000000000000use std::fmt::Display; use super::{Separable, SeparatorPolicy}; use super::helpers::SeparatorIterator; impl Separable for str { fn separate_by_policy(&self, policy: SeparatorPolicy) -> String { let (before, number, after, count) = find_span(&self, |c| policy.digits.contains(&c)); let iter = SeparatorIterator::new(&policy, count); let mut result = String::with_capacity(self.len() + iter.sep_len()); result.push_str(before); for (digit, comma_after) in number.chars().zip(iter) { result.push(digit); if comma_after { result.push_str(policy.separator); } } result.push_str(after); result } } impl Separable for T { fn separate_by_policy(&self, policy: SeparatorPolicy) -> String { self.to_string().as_str().separate_by_policy(policy) } } fn find_span bool>(s: &str, is_digit: F) -> (&str, &str, &str, usize) { let start = len_not_matching(s, &is_digit); let (len, count) = len_and_count_matching(&s[start ..], &is_digit); let limit = start + len; (&s[.. start], &s[start .. limit], &s[limit ..], count) } fn len_not_matching(s: &str, mut pred: F) -> usize where F: FnMut(char) -> bool { if let Some((i, _)) = s.char_indices().find(|p| pred(p.1)) { i } else { s.len() } } fn len_and_count_matching(s: &str, pred: F) -> (usize, usize) where F: Fn(char) -> bool { let mut count = 0; let len = len_not_matching(s, |c| if pred(c) { count += 1; false } else { true }); (len, count) } #[cfg(test)] mod test { use super::super::{Separable, SeparatorPolicy, digits, policies}; #[test] fn integer_thousands_commas() { assert_eq!( "12345".separate_with_commas(), "12,345" ); } #[test] fn smilies() { let policy = SeparatorPolicy { separator: "πŸ˜ƒπŸ˜ƒ", groups: &[1], digits: &['πŸ™'], }; assert_eq!( " πŸ™πŸ™πŸ™πŸ™πŸ™ ".separate_by_policy(policy), " πŸ™πŸ˜ƒπŸ˜ƒπŸ™πŸ˜ƒπŸ˜ƒπŸ™πŸ˜ƒπŸ˜ƒπŸ™πŸ˜ƒπŸ˜ƒπŸ™ " ); } #[test] fn three_two_two_two() { let policy = SeparatorPolicy { separator: ",", groups: &[3, 2], digits: &digits::ASCII_DECIMAL, }; assert_eq!( "1234567890".separate_by_policy(policy), "1,23,45,67,890" ); } #[test] fn minus_sign_and_decimal_point() { assert_eq!( "-1234.5".separate_with_commas(), "-1,234.5" ); } #[test] fn hex_four() { assert_eq!( "deadbeef".separate_by_policy(policies::HEX_FOUR), "dead beef" ); } } thousands-0.2.0/src/helpers.rs010066000007660000024000000204521355275012100145420ustar0000000000000000use super::SeparatorPolicy; #[derive(Debug)] pub struct SeparatorIterator<'a> { groups: &'a [u8], repeat_groups_remaining: usize, current_group_index: usize, current_group_size: usize, len: usize, } impl<'a> SeparatorIterator<'a> { pub fn new(policy: &'a SeparatorPolicy, len: usize) -> Self { let groups = &policy.groups; let mut sum = 0; for (index, &group) in groups.into_iter().enumerate() { sum += group as usize; if len <= sum { return SeparatorIterator { groups, repeat_groups_remaining: 0, current_group_index: index, current_group_size: len - (sum - group as usize), len, } } } let repeat_group_len = match groups.last() { Some(n) => *n as usize, None => return SeparatorIterator { groups: &[], repeat_groups_remaining: 0, current_group_index: 0, current_group_size: 0, len, } }; let len_remaining = len - sum; let (repeat_groups_remaining, current_group_size) = ceil_div_mod(len_remaining, repeat_group_len); SeparatorIterator { groups, repeat_groups_remaining, current_group_index: groups.len() - 1, current_group_size, len, } } /// How many separators remain? pub fn sep_len(&self) -> usize { self.current_group_index + self.repeat_groups_remaining } } impl<'a> Iterator for SeparatorIterator<'a> { type Item = bool; fn next(&mut self) -> Option { self.len = self.len.checked_sub(1)?; self.current_group_size = self.current_group_size.saturating_sub(1); if self.current_group_size > 0 { return Some(false); } if let Some(repeat_groups_remaining) = self.repeat_groups_remaining.checked_sub(1) { self.repeat_groups_remaining = repeat_groups_remaining; } else if let Some(current_group_index) = self.current_group_index.checked_sub(1) { self.current_group_index = current_group_index; } else { return Some(false); } self.current_group_size = self.groups[self.current_group_index] as usize; return Some(true); } fn size_hint(&self) -> (usize, Option) { (self.len(), Some(self.len())) } } impl<'a> ExactSizeIterator for SeparatorIterator<'a> { fn len(&self) -> usize { self.len } } fn ceil_div_mod(n: usize, m: usize) -> (usize, usize) { let round_up = n + m - 1; (round_up / m, round_up % m + 1) } #[cfg(test)] mod test_common { use super::super::*; pub use super::*; pub fn make_policy(groups: &[u8]) -> SeparatorPolicy { let mut result = policies::COMMA_SEPARATOR; result.groups = groups; result } } #[cfg(test)] mod grouping_test { use super::test_common::*; fn group_string(groups: &[u8], digits: &str) -> String { use std::iter::once; let policy = &make_policy(groups); let iter = SeparatorIterator::new(policy, digits.chars().count()); digits.chars().zip(iter) .flat_map(|(digit, comma_after)| once(digit) .chain(if comma_after { Some(',') } else { None })) .collect() } macro_rules! grouping_test { ( $name:ident, $groups:tt, $result:tt ) => { #[test] fn $name() { let result = $result; let input = $result.chars().filter(|&c| c != ',').collect::(); assert_eq!(group_string(&$groups, &input), result); } }; } grouping_test!(by_nothing_of_0, [], ""); grouping_test!(by_nothing_of_1, [], "1"); grouping_test!(by_nothing_of_2, [], "21"); grouping_test!(by_nothing_of_3, [], "321"); grouping_test!(by_1s_of_0, [1], ""); grouping_test!(by_1s_of_1, [1], "1"); grouping_test!(by_1s_of_2, [1], "2,1"); grouping_test!(by_1s_of_3, [1], "3,2,1"); grouping_test!(by_2s_of_0, [2], ""); grouping_test!(by_2s_of_1, [2], "1"); grouping_test!(by_2s_of_2, [2], "21"); grouping_test!(by_2s_of_3, [2], "3,21"); grouping_test!(by_2s_of_4, [2], "43,21"); grouping_test!(by_2s_of_5, [2], "5,43,21"); grouping_test!(by_2s_of_6, [2], "65,43,21"); grouping_test!(by_2s_of_7, [2], "7,65,43,21"); grouping_test!(by_2s_of_8, [2], "87,65,43,21"); grouping_test!(by_2s_of_9, [2], "9,87,65,43,21"); grouping_test!(by_3s_of_1, [3], "1"); grouping_test!(by_3s_of_2, [3], "21"); grouping_test!(by_3s_of_3, [3], "321"); grouping_test!(by_3s_of_4, [3], "4,321"); grouping_test!(by_3s_of_5, [3], "54,321"); grouping_test!(by_3s_of_6, [3], "654,321"); grouping_test!(by_3s_of_7, [3], "7,654,321"); grouping_test!(by_3s_of_8, [3], "87,654,321"); grouping_test!(by_3s_of_9, [3], "987,654,321"); grouping_test!(by_2s3_of_1, [3, 2], "1"); grouping_test!(by_2s3_of_2, [3, 2], "21"); grouping_test!(by_2s3_of_3, [3, 2], "321"); grouping_test!(by_2s3_of_4, [3, 2], "4,321"); grouping_test!(by_2s3_of_5, [3, 2], "54,321"); grouping_test!(by_2s3_of_6, [3, 2], "6,54,321"); grouping_test!(by_2s3_of_7, [3, 2], "76,54,321"); grouping_test!(by_2s3_of_8, [3, 2], "8,76,54,321"); grouping_test!(by_2s3_of_9, [3, 2], "98,76,54,321"); grouping_test!(by_5s4321_of_20, [1, 2, 3, 4, 5], "KJIHG,FEDCB,A987,654,32,1"); grouping_test!(by_5s4321_of_16, [1, 2, 3, 4, 5], "G,FEDCB,A987,654,32,1"); grouping_test!(by_5s4321_of_11, [1, 2, 3, 4, 5], "B,A987,654,32,1"); grouping_test!(by_5s4321_of_10, [1, 2, 3, 4, 5], "A987,654,32,1"); grouping_test!(by_5s4321_of_9, [1, 2, 3, 4, 5], "987,654,32,1"); grouping_test!(by_5s4321_of_7, [1, 2, 3, 4, 5], "7,654,32,1"); grouping_test!(by_5s4321_of_1, [1, 2, 3, 4, 5], "1"); grouping_test!(by_5s4321_of_0, [1, 2, 3, 4, 5], ""); } #[cfg(test)] mod sep_len_test { use super::test_common::*; fn run_iterator(mut iter: SeparatorIterator) -> (Vec, Vec) { let mut predictions = Vec::with_capacity(iter.len()); let mut actuals = Vec::with_capacity(iter.len()); let mut prediction; while let Some(actual) = { prediction = iter.sep_len(); iter.next() } { predictions.push(prediction); actuals.push(if actual { 1 } else { 0 }) } let mut acc = 0; for actual in actuals.iter_mut().rev() { acc += *actual; *actual = acc; } (predictions, actuals) } macro_rules! run_down { ( $name:ident, $groups:tt, $size:tt ) => { #[test] fn $name() { let policy = &make_policy(&$groups); let (predictions, actuals) = run_iterator(SeparatorIterator::new(policy, $size)); assert_eq!(predictions, actuals); } }; } run_down!(by_nothing_of_10, [], 10); run_down!(by_3s_of_10, [3], 10); run_down!(by_2s_of_10, [2], 10); run_down!(by_2s_of_9, [2], 9); run_down!(by_2s_of_8, [2], 8); run_down!(by_2s_of_7, [2], 7); run_down!(by_2s_of_6, [2], 6); run_down!(by_2s_of_5, [2], 5); run_down!(by_2s_of_4, [2], 4); run_down!(by_2s_of_3, [2], 3); run_down!(by_2s_of_2, [2], 2); run_down!(by_2s_of_1, [2], 1); run_down!(by_2s_of_0, [2], 0); run_down!(by_1s23_of_10, [3, 2, 1], 10); run_down!(by_1s23_of_9, [3, 2, 1], 9); run_down!(by_1s23_of_8, [3, 2, 1], 8); run_down!(by_1s23_of_7, [3, 2, 1], 7); run_down!(by_1s23_of_6, [3, 2, 1], 6); run_down!(by_1s23_of_5, [3, 2, 1], 5); run_down!(by_1s23_of_4, [3, 2, 1], 4); run_down!(by_1s23_of_3, [3, 2, 1], 3); run_down!(by_1s23_of_2, [3, 2, 1], 2); run_down!(by_1s23_of_1, [3, 2, 1], 1); run_down!(by_1s23_of_0, [3, 2, 1], 0); } thousands-0.2.0/src/lib.rs010066000007660000024000000043651355275046000136610ustar0000000000000000#![doc(html_root_url = "https://docs.rs/thousands/0.2.0")] //! Provides a trait, [`Separable`], for formatting numbers with //! separators between the digits. Typically this will be used to add //! commas or spaces every three digits from the right, but can be //! configured via a [`SeparatorPolicy`]. //! //! # Examples //! //! The simplest way to use the library is with trait [`Separable`]’s method //! [`separate_with_commas`] method, which does what it sounds like: //! //! ``` //! use thousands::Separable; //! //! assert_eq!( 12345 .separate_with_commas(), "12,345" ); //! assert_eq!( (-12345) .separate_with_commas(), "-12,345" ); //! assert_eq!( 9876.5.separate_with_commas(), "9,876.5" ); //! ``` //! //! There are also methods [`separate_with_spaces`], [`separate_with_dots`], and //! [`separate_with_underscores`], in case you, your culture, or your file //! format prefer those separators. //! //! However, it's also possible to pass a policy for different behavior: //! //! ``` //! use thousands::{Separable, SeparatorPolicy, digits}; //! //! let policy = SeparatorPolicy { //! separator: ",", //! groups: &[3, 2], //! digits: digits::ASCII_DECIMAL, //! }; //! //! assert_eq!( 1234567890.separate_by_policy(policy), "1,23,45,67,890" ); //! ``` //! //! # Usage //! //! It’s [on crates.io](https://crates.io/crates/thousands), so you can add //! //! ```toml //! [dependencies] //! thousands = "0.2.0" //! ``` //! //! to your `Cargo.toml`. //! //! This crate supports Rust version 1.22 and newer. //! //! [`Separable`]: trait.Separable.html //! [`SeparatorPolicy`]: struct.SeparatorPolicy.html //! [`separate_with_commas`]: trait.Separable.html#method.separate_with_commas //! [`separate_with_spaces`]: trait.Separable.html#method.separate_with_spaces //! [`separate_with_dots`]: trait.Separable.html#method.separate_with_dots //! [`separate_with_underscores`]: trait.Separable.html#method.separate_with_underscores /// Collections of digits. /// /// These are used for constructing [SeparatorPolicy](struct.SeparatorPolicy.html)s. pub mod digits; /// Predefined policies. pub mod policies; pub use policies::SeparatorPolicy; mod traits; pub use traits::Separable; // Contains blanket impl Separable for T. mod display; mod helpers; thousands-0.2.0/src/policies.rs010066000007660000024000000042771355275012100147160ustar0000000000000000use super::digits::*; /// A policy for inserting separators into numbers. /// /// The configurable aspects are: /// /// - The separator character to insert. /// /// - How to group the separators. /// /// - What characters are considered digits (for skipping non-digits such as /// a minus sign). #[derive(Debug, Clone, Copy)] pub struct SeparatorPolicy<'a> { /// The separator to insert. pub separator: &'a str, /// The grouping. The numbers in this array give the size of the groups, from /// right to left, with the last number in the array giving the size of all /// subsequent groups. /// /// So to group by threes, as is typical in many places, /// this array should be `&[3]`. However, to get a grouping like `1,23,45,678`, /// where the last group has size three and the others size two, you would use /// `&[3, 2]`. pub groups: &'a [u8], /// The characters that are considered digits. If there are multiple groups of /// digits separated by non-digits, we only add separators to the first group. /// This means, for example, that the number `-12345.67` will only have separators /// inserted into the `12345` portion. pub digits: &'a [char], } /// Policy for placing a comma every three decimal digits. pub const COMMA_SEPARATOR: SeparatorPolicy = SeparatorPolicy { separator: ",", groups: &[3], digits: ASCII_DECIMAL, }; /// Policy for placing a space every three decimal digits. pub const SPACE_SEPARATOR: SeparatorPolicy = SeparatorPolicy { separator: " ", groups: &[3], digits: ASCII_DECIMAL, }; /// Policy for placing a period every three decimal digits. pub const DOT_SEPARATOR: SeparatorPolicy = SeparatorPolicy { separator: ".", groups: &[3], digits: ASCII_DECIMAL, }; /// Policy for placing an underscore every three decimal digits. pub const UNDERSCORE_SEPARATOR: SeparatorPolicy = SeparatorPolicy { separator: "_", groups: &[3], digits: ASCII_DECIMAL, }; /// Policy for placing a space every four hexadecimal digits. pub const HEX_FOUR: SeparatorPolicy = SeparatorPolicy { separator: " ", groups: &[4], digits: ASCII_HEXADECIMAL, }; thousands-0.2.0/src/traits.rs010066000007660000024000000045741355275012100144150ustar0000000000000000use super::{SeparatorPolicy, policies}; /// Provides methods for formatting numbers with separators between the digits. pub trait Separable { /// Inserts a comma every three digits from the right. /// /// This is equivalent to `self.separate_by_policy(policies::COMMA_SEPARATOR)`. /// /// # Examples /// /// ``` /// # use thousands::*; /// assert_eq!( 12345.separate_with_commas(), "12,345" ); /// ``` fn separate_with_commas(&self) -> String { self.separate_by_policy(policies::COMMA_SEPARATOR) } /// Inserts a space every three digits from the right. /// /// This is equivalent to `self.separate_by_policy(policies::SPACE_SEPARATOR)`. /// /// # Examples /// /// ``` /// # use thousands::*; /// assert_eq!( 12345.separate_with_spaces(), "12 345" ); /// ``` fn separate_with_spaces(&self) -> String { self.separate_by_policy(policies::SPACE_SEPARATOR) } /// Inserts a period every three digits from the right. /// /// This is equivalent to `self.separate_by_policy(policies::DOT_SEPARATOR)`. /// /// # Examples /// /// ``` /// # use thousands::*; /// assert_eq!( 12345.separate_with_dots(), "12.345" ); /// ``` fn separate_with_dots(&self) -> String { self.separate_by_policy(policies::DOT_SEPARATOR) } /// Inserts an underscore every three digits from the right. /// /// This is equivalent to `self.separate_by_policy(policies::UNDERSCORE_SEPARATOR)`. /// /// # Examples /// /// ``` /// # use thousands::*; /// assert_eq!( 12345.separate_with_underscores(), "12_345" ); /// ``` fn separate_with_underscores(&self) -> String { self.separate_by_policy(policies::UNDERSCORE_SEPARATOR) } /// Adds separators according to the given [`SeparatorPolicy`]. /// /// # Examples /// /// ``` /// use thousands::{Separable, SeparatorPolicy, digits}; /// /// let policy = SeparatorPolicy { /// separator: ":", /// groups: &[1, 2, 3, 4], /// digits: digits::ASCII_DECIMAL, /// }; /// /// assert_eq!( 1234567654321u64.separate_by_policy(policy), /// "123:4567:654:32:1" ); /// ``` /// /// [`SeparatorPolicy`]: struct.SeparatorPolicy.html fn separate_by_policy(&self, policy: SeparatorPolicy) -> String; } thousands-0.2.0/.cargo_vcs_info.json0000644000000001120000000000000130740ustar00{ "git": { "sha1": "aa1b623cdb812e649f3b4ced80e6a9adb40d2f31" } }