├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── release.toml └── src ├── digits.rs ├── display.rs ├── helpers.rs ├── lib.rs ├── policies.rs └── traits.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | - 1.22.0 7 | 8 | matrix: 9 | allow_failures: 10 | - rust: nightly 11 | fast_finish: true 12 | 13 | notifications: 14 | email: 15 | on_success: never 16 | 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog] and this project adheres to 6 | [Semantic Versioning]. 7 | 8 | [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ 9 | [Semantic Versioning]: http://semver.org/spec/v2.0.0.html 10 | 11 | ## [0.1.4] - 2019-10-19 12 | 13 | ### Changed 14 | - The separator is now a `&str` rather than a `char`. 15 | - Oldest supported rustc version is now 1.22.0. 16 | 17 | ### Added 18 | - A non-blanket `impl Separable for str` allocates only once, for the result, 19 | rather than twice as the blanket `Display`-based `impl` does. 20 | - An empty group array results in no separators. 21 | 22 | ### Fixed 23 | - Now respects UTF-8 for the separator as well. 24 | 25 | ## [0.1.4] - 2019-10-19 26 | 27 | ### Fixed 28 | - Now respects UTF-8. 29 | 30 | ## [0.1.3] - 2019-10-19 31 | 32 | ### Added 33 | - `Separable::separate_with_underscores` method and 34 | `policies::UNDERSCORE_SEPARATOR` constant. 35 | 36 | ## [0.1.2] - 2018-09-18 37 | 38 | ### Fixed 39 | - Github URL in Cargo.toml. 40 | 41 | ## [0.1.1] - 2018-09-16 42 | 43 | ### Added 44 | - Doc comment for `policies` module. 45 | 46 | ## [0.1.0] - 2018-09-16 47 | 48 | Initial release. 49 | 50 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "thousands" 3 | version = "0.2.1-alpha.0" 4 | authors = ["Jesse A. Tov "] 5 | description = "Adds digit separators to numbers, configurably." 6 | repository = "https://github.com/tov/thousands-rs" 7 | readme = "README.md" 8 | license = "MIT/Apache-2.0" 9 | keywords = ["numbers", "formatting", "separators", "commas"] 10 | categories = ["value-formatting"] 11 | 12 | [badges] 13 | travis-ci = { repository = "tov/thousands-rs" } 14 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Jesse A. Tov 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # thousands 2 | 3 | [![Build Status](https://travis-ci.org/tov/thousands-rs.svg?branch=master)](https://travis-ci.org/tov/thousands-rs) 4 | [![Crates.io](https://img.shields.io/crates/v/thousands.svg?maxAge=2592000)](https://crates.io/crates/thousands) 5 | [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE-MIT) 6 | [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE-APACHE) 7 | 8 | Provides a trait, `Separable`, for formatting numbers with separators 9 | between the digits. Typically this will be used to add commas or spaces 10 | every three digits from the right, but can be configured via a 11 | `SeparatorPolicy`. 12 | 13 | ## Examples 14 | 15 | The simplest way to use the library is with trait `Separable`’s method 16 | `separate_with_commas` method, which does what it sounds like: 17 | 18 | ```rust 19 | use thousands::Separable; 20 | 21 | assert_eq!( 12345 .separate_with_commas(), "12,345" ); 22 | assert_eq!( (-12345) .separate_with_commas(), "-12,345" ); 23 | assert_eq!( 9876.5.separate_with_commas(), "9,876.5" ); 24 | ``` 25 | 26 | There are also methods `separate_with_spaces`, `separate_with_dots`, and 27 | `separate_with_underscores`, in case you, your culture, or your file 28 | format prefer those separators. 29 | 30 | However, it's also possible to pass a policy for different behavior: 31 | 32 | ```rust 33 | use thousands::{Separable, SeparatorPolicy, digits}; 34 | 35 | let policy = SeparatorPolicy { 36 | separator: ',', 37 | groups: &[3, 2], 38 | digits: digits::ASCII_DECIMAL, 39 | }; 40 | 41 | assert_eq!( 1234567890.separate_by_policy(policy), "1,23,45,67,890" ); 42 | ``` 43 | 44 | ## Usage 45 | 46 | It’s [on crates.io](https://crates.io/crates/thousands), so you can add 47 | 48 | ```toml 49 | [dependencies] 50 | thousands = "0.2.0" 51 | ``` 52 | 53 | to your `Cargo.toml`. 54 | 55 | This crate supports Rust version 1.22 and newer. 56 | 57 | -------------------------------------------------------------------------------- /release.toml: -------------------------------------------------------------------------------- 1 | pre-release-replacements = [ 2 | { file="README.md", search="thousands = \"[0-9.]*\"", replace="thousands = \"{{version}}\"" }, 3 | { file="src/lib.rs", search="thousands = \"[0-9.]*\"", replace="thousands = \"{{version}}\"" }, 4 | { file="src/lib.rs", search="https://docs[.]rs/thousands/[0-9.]*", replace="https://docs.rs/thousands/{{version}}" }, 5 | { file="CHANGELOG.md", search="\\[Unreleased\\]", replace="[{{version}}] - {{date}}" } 6 | ] 7 | -------------------------------------------------------------------------------- /src/digits.rs: -------------------------------------------------------------------------------- 1 | /// The decimal digits, in ASCII. 2 | pub const ASCII_DECIMAL: &[char] = &[ 3 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 4 | ]; 5 | 6 | /// The hexadecimal digits, in ASCII. 7 | pub const ASCII_HEXADECIMAL: &[char] = &[ 8 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 9 | 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', 10 | ]; 11 | -------------------------------------------------------------------------------- /src/display.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | use super::{Separable, SeparatorPolicy}; 4 | use super::helpers::SeparatorIterator; 5 | 6 | impl Separable for str { 7 | fn separate_by_policy(&self, policy: SeparatorPolicy) -> String { 8 | let (before, number, after, count) = find_span(&self, |c| policy.digits.contains(&c)); 9 | let iter = SeparatorIterator::new(&policy, count); 10 | 11 | let mut result = String::with_capacity(self.len() + iter.sep_len()); 12 | 13 | result.push_str(before); 14 | 15 | for (digit, comma_after) in number.chars().zip(iter) { 16 | result.push(digit); 17 | if comma_after { 18 | result.push_str(policy.separator); 19 | } 20 | } 21 | 22 | result.push_str(after); 23 | 24 | result 25 | } 26 | } 27 | 28 | impl Separable for T { 29 | fn separate_by_policy(&self, policy: SeparatorPolicy) -> String { 30 | self.to_string().as_str().separate_by_policy(policy) 31 | } 32 | } 33 | 34 | fn find_span bool>(s: &str, is_digit: F) -> (&str, &str, &str, usize) { 35 | let start = len_not_matching(s, &is_digit); 36 | let (len, count) = len_and_count_matching(&s[start ..], &is_digit); 37 | let limit = start + len; 38 | 39 | (&s[.. start], &s[start .. limit], &s[limit ..], count) 40 | } 41 | 42 | fn len_not_matching(s: &str, mut pred: F) -> usize 43 | where F: FnMut(char) -> bool { 44 | 45 | if let Some((i, _)) = s.char_indices().find(|p| pred(p.1)) { 46 | i 47 | } else { 48 | s.len() 49 | } 50 | } 51 | 52 | fn len_and_count_matching(s: &str, pred: F) -> (usize, usize) 53 | where F: Fn(char) -> bool { 54 | 55 | let mut count = 0; 56 | let len = len_not_matching(s, |c| 57 | if pred(c) { 58 | count += 1; 59 | false 60 | } else { 61 | true 62 | }); 63 | 64 | (len, count) 65 | } 66 | 67 | #[cfg(test)] 68 | mod test { 69 | use super::super::{Separable, SeparatorPolicy, digits, policies}; 70 | 71 | #[test] 72 | fn integer_thousands_commas() { 73 | assert_eq!( "12345".separate_with_commas(), 74 | "12,345" ); 75 | } 76 | 77 | #[test] 78 | fn smilies() { 79 | let policy = SeparatorPolicy { 80 | separator: "😃😃", 81 | groups: &[1], 82 | digits: &['🙁'], 83 | }; 84 | 85 | assert_eq!( " 🙁🙁🙁🙁🙁 ".separate_by_policy(policy), 86 | " 🙁😃😃🙁😃😃🙁😃😃🙁😃😃🙁 " ); 87 | } 88 | 89 | #[test] 90 | fn three_two_two_two() { 91 | let policy = SeparatorPolicy { 92 | separator: ",", 93 | groups: &[3, 2], 94 | digits: &digits::ASCII_DECIMAL, 95 | }; 96 | 97 | assert_eq!( "1234567890".separate_by_policy(policy), 98 | "1,23,45,67,890" ); 99 | } 100 | 101 | #[test] 102 | fn minus_sign_and_decimal_point() { 103 | assert_eq!( "-1234.5".separate_with_commas(), 104 | "-1,234.5" ); 105 | } 106 | 107 | #[test] 108 | fn hex_four() { 109 | assert_eq!( "deadbeef".separate_by_policy(policies::HEX_FOUR), 110 | "dead beef" ); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/helpers.rs: -------------------------------------------------------------------------------- 1 | use super::SeparatorPolicy; 2 | 3 | #[derive(Debug)] 4 | pub struct SeparatorIterator<'a> { 5 | groups: &'a [u8], 6 | repeat_groups_remaining: usize, 7 | current_group_index: usize, 8 | current_group_size: usize, 9 | len: usize, 10 | } 11 | 12 | impl<'a> SeparatorIterator<'a> { 13 | pub fn new(policy: &'a SeparatorPolicy, len: usize) -> Self { 14 | let groups = &policy.groups; 15 | 16 | let mut sum = 0; 17 | 18 | for (index, &group) in groups.into_iter().enumerate() { 19 | sum += group as usize; 20 | 21 | if len <= sum { 22 | return SeparatorIterator { 23 | groups, 24 | repeat_groups_remaining: 0, 25 | current_group_index: index, 26 | current_group_size: len - (sum - group as usize), 27 | len, 28 | } 29 | } 30 | } 31 | 32 | let repeat_group_len = match groups.last() { 33 | Some(n) => *n as usize, 34 | None => 35 | return SeparatorIterator { 36 | groups: &[], 37 | repeat_groups_remaining: 0, 38 | current_group_index: 0, 39 | current_group_size: 0, 40 | len, 41 | } 42 | }; 43 | 44 | let len_remaining = len - sum; 45 | let (repeat_groups_remaining, current_group_size) 46 | = ceil_div_mod(len_remaining, repeat_group_len); 47 | 48 | SeparatorIterator { 49 | groups, 50 | repeat_groups_remaining, 51 | current_group_index: groups.len() - 1, 52 | current_group_size, 53 | len, 54 | } 55 | } 56 | 57 | /// How many separators remain? 58 | pub fn sep_len(&self) -> usize { 59 | self.current_group_index + self.repeat_groups_remaining 60 | } 61 | } 62 | 63 | impl<'a> Iterator for SeparatorIterator<'a> { 64 | type Item = bool; 65 | 66 | fn next(&mut self) -> Option { 67 | self.len = self.len.checked_sub(1)?; 68 | 69 | self.current_group_size = self.current_group_size.saturating_sub(1); 70 | if self.current_group_size > 0 { 71 | return Some(false); 72 | } 73 | 74 | if let Some(repeat_groups_remaining) = self.repeat_groups_remaining.checked_sub(1) { 75 | self.repeat_groups_remaining = repeat_groups_remaining; 76 | } else if let Some(current_group_index) = self.current_group_index.checked_sub(1) { 77 | self.current_group_index = current_group_index; 78 | } else { 79 | return Some(false); 80 | } 81 | 82 | self.current_group_size = self.groups[self.current_group_index] as usize; 83 | return Some(true); 84 | } 85 | 86 | fn size_hint(&self) -> (usize, Option) { 87 | (self.len(), Some(self.len())) 88 | } 89 | } 90 | 91 | impl<'a> ExactSizeIterator for SeparatorIterator<'a> { 92 | fn len(&self) -> usize { 93 | self.len 94 | } 95 | } 96 | 97 | fn ceil_div_mod(n: usize, m: usize) -> (usize, usize) { 98 | let round_up = n + m - 1; 99 | (round_up / m, round_up % m + 1) 100 | } 101 | 102 | #[cfg(test)] 103 | mod test_common { 104 | use super::super::*; 105 | pub use super::*; 106 | 107 | pub fn make_policy(groups: &[u8]) -> SeparatorPolicy { 108 | let mut result = policies::COMMA_SEPARATOR; 109 | result.groups = groups; 110 | result 111 | } 112 | } 113 | 114 | #[cfg(test)] 115 | mod grouping_test { 116 | use super::test_common::*; 117 | 118 | fn group_string(groups: &[u8], digits: &str) -> String { 119 | use std::iter::once; 120 | 121 | let policy = &make_policy(groups); 122 | let iter = SeparatorIterator::new(policy, digits.chars().count()); 123 | 124 | digits.chars().zip(iter) 125 | .flat_map(|(digit, comma_after)| 126 | once(digit) 127 | .chain(if comma_after { Some(',') } else { None })) 128 | .collect() 129 | } 130 | 131 | macro_rules! grouping_test { 132 | ( $name:ident, $groups:tt, $result:tt ) => { 133 | #[test] 134 | fn $name() { 135 | let result = $result; 136 | let input = $result.chars().filter(|&c| c != ',').collect::(); 137 | assert_eq!(group_string(&$groups, &input), result); 138 | } 139 | }; 140 | } 141 | 142 | grouping_test!(by_nothing_of_0, [], ""); 143 | grouping_test!(by_nothing_of_1, [], "1"); 144 | grouping_test!(by_nothing_of_2, [], "21"); 145 | grouping_test!(by_nothing_of_3, [], "321"); 146 | 147 | grouping_test!(by_1s_of_0, [1], ""); 148 | grouping_test!(by_1s_of_1, [1], "1"); 149 | grouping_test!(by_1s_of_2, [1], "2,1"); 150 | grouping_test!(by_1s_of_3, [1], "3,2,1"); 151 | 152 | grouping_test!(by_2s_of_0, [2], ""); 153 | grouping_test!(by_2s_of_1, [2], "1"); 154 | grouping_test!(by_2s_of_2, [2], "21"); 155 | grouping_test!(by_2s_of_3, [2], "3,21"); 156 | grouping_test!(by_2s_of_4, [2], "43,21"); 157 | grouping_test!(by_2s_of_5, [2], "5,43,21"); 158 | grouping_test!(by_2s_of_6, [2], "65,43,21"); 159 | grouping_test!(by_2s_of_7, [2], "7,65,43,21"); 160 | grouping_test!(by_2s_of_8, [2], "87,65,43,21"); 161 | grouping_test!(by_2s_of_9, [2], "9,87,65,43,21"); 162 | 163 | grouping_test!(by_3s_of_1, [3], "1"); 164 | grouping_test!(by_3s_of_2, [3], "21"); 165 | grouping_test!(by_3s_of_3, [3], "321"); 166 | grouping_test!(by_3s_of_4, [3], "4,321"); 167 | grouping_test!(by_3s_of_5, [3], "54,321"); 168 | grouping_test!(by_3s_of_6, [3], "654,321"); 169 | grouping_test!(by_3s_of_7, [3], "7,654,321"); 170 | grouping_test!(by_3s_of_8, [3], "87,654,321"); 171 | grouping_test!(by_3s_of_9, [3], "987,654,321"); 172 | 173 | grouping_test!(by_2s3_of_1, [3, 2], "1"); 174 | grouping_test!(by_2s3_of_2, [3, 2], "21"); 175 | grouping_test!(by_2s3_of_3, [3, 2], "321"); 176 | grouping_test!(by_2s3_of_4, [3, 2], "4,321"); 177 | grouping_test!(by_2s3_of_5, [3, 2], "54,321"); 178 | grouping_test!(by_2s3_of_6, [3, 2], "6,54,321"); 179 | grouping_test!(by_2s3_of_7, [3, 2], "76,54,321"); 180 | grouping_test!(by_2s3_of_8, [3, 2], "8,76,54,321"); 181 | grouping_test!(by_2s3_of_9, [3, 2], "98,76,54,321"); 182 | 183 | grouping_test!(by_5s4321_of_20, [1, 2, 3, 4, 5], 184 | "KJIHG,FEDCB,A987,654,32,1"); 185 | grouping_test!(by_5s4321_of_16, [1, 2, 3, 4, 5], 186 | "G,FEDCB,A987,654,32,1"); 187 | grouping_test!(by_5s4321_of_11, [1, 2, 3, 4, 5], 188 | "B,A987,654,32,1"); 189 | grouping_test!(by_5s4321_of_10, [1, 2, 3, 4, 5], 190 | "A987,654,32,1"); 191 | grouping_test!(by_5s4321_of_9, [1, 2, 3, 4, 5], 192 | "987,654,32,1"); 193 | grouping_test!(by_5s4321_of_7, [1, 2, 3, 4, 5], 194 | "7,654,32,1"); 195 | grouping_test!(by_5s4321_of_1, [1, 2, 3, 4, 5], 196 | "1"); 197 | grouping_test!(by_5s4321_of_0, [1, 2, 3, 4, 5], 198 | ""); 199 | } 200 | 201 | #[cfg(test)] 202 | mod sep_len_test { 203 | use super::test_common::*; 204 | 205 | fn run_iterator(mut iter: SeparatorIterator) -> (Vec, Vec) { 206 | let mut predictions = Vec::with_capacity(iter.len()); 207 | let mut actuals = Vec::with_capacity(iter.len()); 208 | 209 | let mut prediction; 210 | while let Some(actual) = { 211 | prediction = iter.sep_len(); 212 | iter.next() 213 | } { 214 | predictions.push(prediction); 215 | actuals.push(if actual { 1 } else { 0 }) 216 | } 217 | 218 | let mut acc = 0; 219 | for actual in actuals.iter_mut().rev() { 220 | acc += *actual; 221 | *actual = acc; 222 | } 223 | 224 | (predictions, actuals) 225 | } 226 | 227 | macro_rules! run_down { 228 | ( $name:ident, $groups:tt, $size:tt ) => { 229 | #[test] 230 | fn $name() { 231 | let policy = &make_policy(&$groups); 232 | 233 | let (predictions, actuals) = 234 | run_iterator(SeparatorIterator::new(policy, $size)); 235 | 236 | assert_eq!(predictions, actuals); 237 | } 238 | }; 239 | } 240 | 241 | run_down!(by_nothing_of_10, [], 10); 242 | 243 | run_down!(by_3s_of_10, [3], 10); 244 | 245 | run_down!(by_2s_of_10, [2], 10); 246 | run_down!(by_2s_of_9, [2], 9); 247 | run_down!(by_2s_of_8, [2], 8); 248 | run_down!(by_2s_of_7, [2], 7); 249 | run_down!(by_2s_of_6, [2], 6); 250 | run_down!(by_2s_of_5, [2], 5); 251 | run_down!(by_2s_of_4, [2], 4); 252 | run_down!(by_2s_of_3, [2], 3); 253 | run_down!(by_2s_of_2, [2], 2); 254 | run_down!(by_2s_of_1, [2], 1); 255 | run_down!(by_2s_of_0, [2], 0); 256 | 257 | run_down!(by_1s23_of_10, [3, 2, 1], 10); 258 | run_down!(by_1s23_of_9, [3, 2, 1], 9); 259 | run_down!(by_1s23_of_8, [3, 2, 1], 8); 260 | run_down!(by_1s23_of_7, [3, 2, 1], 7); 261 | run_down!(by_1s23_of_6, [3, 2, 1], 6); 262 | run_down!(by_1s23_of_5, [3, 2, 1], 5); 263 | run_down!(by_1s23_of_4, [3, 2, 1], 4); 264 | run_down!(by_1s23_of_3, [3, 2, 1], 3); 265 | run_down!(by_1s23_of_2, [3, 2, 1], 2); 266 | run_down!(by_1s23_of_1, [3, 2, 1], 1); 267 | run_down!(by_1s23_of_0, [3, 2, 1], 0); 268 | } 269 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc(html_root_url = "https://docs.rs/thousands/0.2.0")] 2 | //! Provides a trait, [`Separable`], for formatting numbers with 3 | //! separators between the digits. Typically this will be used to add 4 | //! commas or spaces every three digits from the right, but can be 5 | //! configured via a [`SeparatorPolicy`]. 6 | //! 7 | //! # Examples 8 | //! 9 | //! The simplest way to use the library is with trait [`Separable`]’s method 10 | //! [`separate_with_commas`] method, which does what it sounds like: 11 | //! 12 | //! ``` 13 | //! use thousands::Separable; 14 | //! 15 | //! assert_eq!( 12345 .separate_with_commas(), "12,345" ); 16 | //! assert_eq!( (-12345) .separate_with_commas(), "-12,345" ); 17 | //! assert_eq!( 9876.5.separate_with_commas(), "9,876.5" ); 18 | //! ``` 19 | //! 20 | //! There are also methods [`separate_with_spaces`], [`separate_with_dots`], and 21 | //! [`separate_with_underscores`], in case you, your culture, or your file 22 | //! format prefer those separators. 23 | //! 24 | //! However, it's also possible to pass a policy for different behavior: 25 | //! 26 | //! ``` 27 | //! use thousands::{Separable, SeparatorPolicy, digits}; 28 | //! 29 | //! let policy = SeparatorPolicy { 30 | //! separator: ",", 31 | //! groups: &[3, 2], 32 | //! digits: digits::ASCII_DECIMAL, 33 | //! }; 34 | //! 35 | //! assert_eq!( 1234567890.separate_by_policy(policy), "1,23,45,67,890" ); 36 | //! ``` 37 | //! 38 | //! # Usage 39 | //! 40 | //! It’s [on crates.io](https://crates.io/crates/thousands), so you can add 41 | //! 42 | //! ```toml 43 | //! [dependencies] 44 | //! thousands = "0.2.0" 45 | //! ``` 46 | //! 47 | //! to your `Cargo.toml`. 48 | //! 49 | //! This crate supports Rust version 1.22 and newer. 50 | //! 51 | //! [`Separable`]: trait.Separable.html 52 | //! [`SeparatorPolicy`]: struct.SeparatorPolicy.html 53 | //! [`separate_with_commas`]: trait.Separable.html#method.separate_with_commas 54 | //! [`separate_with_spaces`]: trait.Separable.html#method.separate_with_spaces 55 | //! [`separate_with_dots`]: trait.Separable.html#method.separate_with_dots 56 | //! [`separate_with_underscores`]: trait.Separable.html#method.separate_with_underscores 57 | 58 | /// Collections of digits. 59 | /// 60 | /// These are used for constructing [SeparatorPolicy](struct.SeparatorPolicy.html)s. 61 | pub mod digits; 62 | 63 | /// Predefined policies. 64 | pub mod policies; 65 | pub use policies::SeparatorPolicy; 66 | 67 | mod traits; 68 | pub use traits::Separable; 69 | 70 | // Contains blanket impl Separable for T. 71 | mod display; 72 | 73 | mod helpers; 74 | -------------------------------------------------------------------------------- /src/policies.rs: -------------------------------------------------------------------------------- 1 | use super::digits::*; 2 | 3 | /// A policy for inserting separators into numbers. 4 | /// 5 | /// The configurable aspects are: 6 | /// 7 | /// - The separator character to insert. 8 | /// 9 | /// - How to group the separators. 10 | /// 11 | /// - What characters are considered digits (for skipping non-digits such as 12 | /// a minus sign). 13 | #[derive(Debug, Clone, Copy)] 14 | pub struct SeparatorPolicy<'a> { 15 | /// The separator to insert. 16 | pub separator: &'a str, 17 | /// The grouping. The numbers in this array give the size of the groups, from 18 | /// right to left, with the last number in the array giving the size of all 19 | /// subsequent groups. 20 | /// 21 | /// So to group by threes, as is typical in many places, 22 | /// this array should be `&[3]`. However, to get a grouping like `1,23,45,678`, 23 | /// where the last group has size three and the others size two, you would use 24 | /// `&[3, 2]`. 25 | pub groups: &'a [u8], 26 | /// The characters that are considered digits. If there are multiple groups of 27 | /// digits separated by non-digits, we only add separators to the first group. 28 | /// This means, for example, that the number `-12345.67` will only have separators 29 | /// inserted into the `12345` portion. 30 | pub digits: &'a [char], 31 | } 32 | 33 | /// Policy for placing a comma every three decimal digits. 34 | pub const COMMA_SEPARATOR: SeparatorPolicy = SeparatorPolicy { 35 | separator: ",", 36 | groups: &[3], 37 | digits: ASCII_DECIMAL, 38 | }; 39 | 40 | /// Policy for placing a space every three decimal digits. 41 | pub const SPACE_SEPARATOR: SeparatorPolicy = SeparatorPolicy { 42 | separator: " ", 43 | groups: &[3], 44 | digits: ASCII_DECIMAL, 45 | }; 46 | 47 | /// Policy for placing a period every three decimal digits. 48 | pub const DOT_SEPARATOR: SeparatorPolicy = SeparatorPolicy { 49 | separator: ".", 50 | groups: &[3], 51 | digits: ASCII_DECIMAL, 52 | }; 53 | 54 | /// Policy for placing an underscore every three decimal digits. 55 | pub const UNDERSCORE_SEPARATOR: SeparatorPolicy = SeparatorPolicy { 56 | separator: "_", 57 | groups: &[3], 58 | digits: ASCII_DECIMAL, 59 | }; 60 | 61 | /// Policy for placing a space every four hexadecimal digits. 62 | pub const HEX_FOUR: SeparatorPolicy = SeparatorPolicy { 63 | separator: " ", 64 | groups: &[4], 65 | digits: ASCII_HEXADECIMAL, 66 | }; 67 | -------------------------------------------------------------------------------- /src/traits.rs: -------------------------------------------------------------------------------- 1 | use super::{SeparatorPolicy, policies}; 2 | 3 | /// Provides methods for formatting numbers with separators between the digits. 4 | pub trait Separable { 5 | /// Inserts a comma every three digits from the right. 6 | /// 7 | /// This is equivalent to `self.separate_by_policy(policies::COMMA_SEPARATOR)`. 8 | /// 9 | /// # Examples 10 | /// 11 | /// ``` 12 | /// # use thousands::*; 13 | /// assert_eq!( 12345.separate_with_commas(), "12,345" ); 14 | /// ``` 15 | fn separate_with_commas(&self) -> String { 16 | self.separate_by_policy(policies::COMMA_SEPARATOR) 17 | } 18 | 19 | /// Inserts a space every three digits from the right. 20 | /// 21 | /// This is equivalent to `self.separate_by_policy(policies::SPACE_SEPARATOR)`. 22 | /// 23 | /// # Examples 24 | /// 25 | /// ``` 26 | /// # use thousands::*; 27 | /// assert_eq!( 12345.separate_with_spaces(), "12 345" ); 28 | /// ``` 29 | fn separate_with_spaces(&self) -> String { 30 | self.separate_by_policy(policies::SPACE_SEPARATOR) 31 | } 32 | 33 | /// Inserts a period every three digits from the right. 34 | /// 35 | /// This is equivalent to `self.separate_by_policy(policies::DOT_SEPARATOR)`. 36 | /// 37 | /// # Examples 38 | /// 39 | /// ``` 40 | /// # use thousands::*; 41 | /// assert_eq!( 12345.separate_with_dots(), "12.345" ); 42 | /// ``` 43 | fn separate_with_dots(&self) -> String { 44 | self.separate_by_policy(policies::DOT_SEPARATOR) 45 | } 46 | 47 | /// Inserts an underscore every three digits from the right. 48 | /// 49 | /// This is equivalent to `self.separate_by_policy(policies::UNDERSCORE_SEPARATOR)`. 50 | /// 51 | /// # Examples 52 | /// 53 | /// ``` 54 | /// # use thousands::*; 55 | /// assert_eq!( 12345.separate_with_underscores(), "12_345" ); 56 | /// ``` 57 | fn separate_with_underscores(&self) -> String { 58 | self.separate_by_policy(policies::UNDERSCORE_SEPARATOR) 59 | } 60 | 61 | /// Adds separators according to the given [`SeparatorPolicy`]. 62 | /// 63 | /// # Examples 64 | /// 65 | /// ``` 66 | /// use thousands::{Separable, SeparatorPolicy, digits}; 67 | /// 68 | /// let policy = SeparatorPolicy { 69 | /// separator: ":", 70 | /// groups: &[1, 2, 3, 4], 71 | /// digits: digits::ASCII_DECIMAL, 72 | /// }; 73 | /// 74 | /// assert_eq!( 1234567654321u64.separate_by_policy(policy), 75 | /// "123:4567:654:32:1" ); 76 | /// ``` 77 | /// 78 | /// [`SeparatorPolicy`]: struct.SeparatorPolicy.html 79 | fn separate_by_policy(&self, policy: SeparatorPolicy) -> String; 80 | } 81 | 82 | --------------------------------------------------------------------------------