numeric-sort-0.1.4/.cargo_vcs_info.json0000644000000001360000000000100134650ustar { "git": { "sha1": "5840d26b17a62b86f4ed73b85f0864b8f26bb553" }, "path_in_vcs": "" }numeric-sort-0.1.4/.github/workflows/ci.yaml000064400000000000000000000015521046102023000171340ustar 00000000000000name: CI on: push: pull_request: jobs: doc: name: doc runs-on: ubuntu-latest env: RUSTDOCFLAGS: "-D warnings" steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: actions-rs/cargo@v1 with: command: doc args: --no-deps test: name: test runs-on: ubuntu-latest strategy: matrix: feats: ["", "--no-default-features"] opt: ["", "--release"] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - uses: actions-rs/cargo@v1 with: command: test args: --lib ${{ matrix.feats }} ${{ matrix.opt }} numeric-sort-0.1.4/.gitignore000064400000000000000000000000241046102023000142410ustar 00000000000000/target /Cargo.lock numeric-sort-0.1.4/Cargo.toml0000644000000017410000000000100114660ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "numeric-sort" version = "0.1.4" authors = ["Devin Jean "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = """ A zero-allocation, human-readable sorting library. """ documentation = "https://docs.rs/numeric-sort" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/dragazo/numeric-sort" [lib] name = "numeric_sort" path = "src/lib.rs" [features] alloc = [] default = ["alloc"] numeric-sort-0.1.4/Cargo.toml.orig000064400000000000000000000005561046102023000151520ustar 00000000000000[package] name = "numeric-sort" version = "0.1.4" authors = ["Devin Jean "] edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/dragazo/numeric-sort" documentation = "https://docs.rs/numeric-sort" description = """ A zero-allocation, human-readable sorting library. """ [features] default = ["alloc"] alloc = [] numeric-sort-0.1.4/LICENSE-APACHE.txt000064400000000000000000000261201046102023000150200ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [2022] [Devin Jean] 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. numeric-sort-0.1.4/LICENSE-MIT.txt000064400000000000000000000020531046102023000145270ustar 00000000000000MIT License Copyright (c) 2022 Devin Jean 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. numeric-sort-0.1.4/README.md000064400000000000000000000014431046102023000135360ustar 00000000000000## `numeric-sort` A zero-allocation, human-readable sorting library. This library provides convenient ways to compare or sort strings and keep numeric components in proper numerical order. For instance `"test-7"` will come before `"test-10"`, contrary to traditional lexicographic comparison of characters. The primary functions of interest are [`cmp`], [`sort`], and [`sort_unstable`]. ## `no-std` `numeric-sort` is compatible with `no-std` projects out of the box. However, by default we link to `alloc` in order to support [`sort`] (stable sorts require allocations). To prevent this, you can disable the default `alloc` feature, which will disable [`sort`] but leave all other functions still available. ```toml [dependencies] numeric-sort = { version = "...", default-features = false } ``` numeric-sort-0.1.4/src/lib.rs000064400000000000000000000515101046102023000141620ustar 00000000000000#![doc = include_str!("../README.md")] #![forbid(unsafe_code)] #![no_std] #[cfg(any(test, feature = "alloc"))] extern crate alloc; #[cfg(test)] use alloc::format; use core::cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering}; use core::iter::FusedIterator; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum Sign { Negative, Positive, } /// A reference to a substring of one or more non- (decimal) digits. /// /// [`Ord`] and [`Eq`] are implemented for this type, which is equivalent to comparing the raw [`str`] values. #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] pub struct Text<'a> { content: &'a str, } impl<'a> Text<'a> { /// Greedily reads a (non-empty) [`Text`] segment from the beginning of the string. /// Returns [`None`] if the string is empty or starts with a (decimal) digit. pub fn read(src: &'a str) -> Option { if Number::read(src).is_some() { return None; } let mut pos = src.char_indices(); loop { match pos.next() { None => return if !src.is_empty() { Some(Self { content: src }) } else { None }, Some((i, ch)) => { if (ch.is_ascii_whitespace() || ch.is_ascii_punctuation()) && Number::read(&src[i + 1..]).is_some() { return Some(Self { content: &src[..i + 1] }); } if ch.is_digit(10) { return if i != 0 { Some(Self { content: &src[..i] }) } else { None }; } } } } } /// Returns the (non-empty) substring that was read via [`Text::read`]. pub fn as_str(&self) -> &'a str { self.content } } #[test] fn test_text() { assert_eq!(Text::read("hello world ").map(|v| v.content), Some("hello world ")); assert_eq!(Text::read("hello world 7").map(|v| v.content), Some("hello world ")); assert_eq!(Text::read("hello world 7").map(|v| v.content), Some("hello world ")); assert_eq!(Text::read("hello world -7").map(|v| v.content), Some("hello world ")); assert_eq!(Text::read("hello world -7").map(|v| v.content), Some("hello world ")); assert_eq!(Text::read("hello world-").map(|v| v.content), Some("hello world-")); assert_eq!(Text::read("hello world-4").map(|v| v.content), Some("hello world-")); assert_eq!(Text::read("hello world--4").map(|v| v.content), Some("hello world-")); assert_eq!(Text::read("hello world---4").map(|v| v.content), Some("hello world--")); assert_eq!(Text::read("hello world----4").map(|v| v.content), Some("hello world---")); assert_eq!(Text::read("hello world").map(|v| v.content), Some("hello world")); assert_eq!(Text::read("hello wor4ld").map(|v| v.content), Some("hello wor")); assert_eq!(Text::read("안영하세요 wor4ld").map(|v| v.content), Some("안영하세요 wor")); assert_eq!(Text::read("h2ell wor4ld").map(|v| v.content), Some("h")); assert_eq!(Text::read("34hello wor4ld").map(|v| v.content), None); assert_eq!(Text::read("-34hello wor4ld").map(|v| v.content), None); assert_eq!(Text::read("--34hello wor4ld").map(|v| v.content), Some("-")); assert_eq!(Text::read("+-34hello wor4ld").map(|v| v.content), Some("+")); assert_eq!(Text::read("+34hello wor4ld").map(|v| v.content), None); assert_eq!(Text::read("-+34hello wor4ld").map(|v| v.content), Some("-")); assert_eq!(Text::read("++34hello wor4ld").map(|v| v.content), Some("+")); assert_eq!(Text::read("").map(|v| v.content), None); for p in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".chars() { assert_eq!(Text::read(&format!("hello world{p}-4")).map(|v| v.content), Some(format!("hello world{p}").as_str())); } fn get(v: &str) -> &str { Text::read(v).unwrap().as_str() } assert_eq!(get("hello world"), "hello world"); assert_eq!(get("hello wor4ld"), "hello wor"); assert_eq!(get("h2ell wor4ld"), "h"); assert_eq!(get(" h2ell wor4ld"), " h"); assert_eq!(get(" h 2ell wor4ld"), " h "); } /// A reference to a substring of one or more (decimal) digits. /// /// [`Ord`] and [`Eq`] are implemented for this type, which behave as if using arbitrary-precision integers, but performs no allocations. /// Note that this means that leading zeros on a number will be ignored for the purpose of comparison. #[derive(Debug, Clone, Copy)] pub struct Number<'a> { sign: Option, leading_zeros: usize, content: &'a str, } impl<'a> Number<'a> { /// Greedily reads a (non-empty) [`Number`] segment from the beginning of the string. /// Returns [`None`] if the string does not start with a (decimal) digit. pub fn read(src: &'a str) -> Option { let (sign, tail) = match src.chars().next() { Some('+') => (Some(Sign::Positive), &src[1..]), Some('-') => (Some(Sign::Negative), &src[1..]), _ => (None, src), }; match tail.chars().position(|ch| !ch.is_digit(10)).unwrap_or(tail.len()) { 0 => None, stop => { let leading_zeros = tail.chars().position(|ch| ch != '0').unwrap_or(tail.len()); Some(Self { sign, leading_zeros, content: &src[..stop + (src.len() - tail.len())] }) // ascii digits are 1 byte in utf8, so this is safe (otherwise we'd need char_indices()) } } } /// Returns the (non-empty) substring that was read via [`Number::read`]. pub fn as_str(&self) -> &'a str { self.content } } impl Ord for Number<'_> { fn cmp(&self, other: &Self) -> Ordering { let t = |x: &Self| (x.content.len() - if x.sign.is_some() { 1 } else { 0 } - x.leading_zeros, &x.content[if x.sign.is_some() { 1 } else { 0 } + x.leading_zeros..]); match (self.sign.unwrap_or(Sign::Positive), other.sign.unwrap_or(Sign::Positive)) { (Sign::Positive, Sign::Positive) => t(self).cmp(&t(other)), (Sign::Positive, Sign::Negative) => if t(self).0 == 0 && t(other).0 == 0 { Ordering::Equal } else { Ordering::Greater }, (Sign::Negative, Sign::Positive) => if t(self).0 == 0 && t(other).0 == 0 { Ordering::Equal } else { Ordering::Less }, (Sign::Negative, Sign::Negative) => t(other).cmp(&t(self)), } } } impl PartialOrd for Number<'_> { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Number<'_> { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for Number<'_> {} #[test] fn test_number() { assert_eq!(Number::read("0").map(|v| (v.content, v.leading_zeros)), Some(("0", 1))); assert_eq!(Number::read("+0").map(|v| (v.content, v.leading_zeros)), Some(("+0", 1))); assert_eq!(Number::read("-0").map(|v| (v.content, v.leading_zeros)), Some(("-0", 1))); assert_eq!(Number::read("00").map(|v| (v.content, v.leading_zeros)), Some(("00", 2))); assert_eq!(Number::read("+00").map(|v| (v.content, v.leading_zeros)), Some(("+00", 2))); assert_eq!(Number::read("-00").map(|v| (v.content, v.leading_zeros)), Some(("-00", 2))); assert_eq!(Number::read("53426").map(|v| (v.content, v.leading_zeros)), Some(("53426", 0))); assert_eq!(Number::read("-53426").map(|v| (v.content, v.leading_zeros)), Some(("-53426", 0))); assert_eq!(Number::read("-53426g").map(|v| (v.content, v.leading_zeros)), Some(("-53426", 0))); assert_eq!(Number::read("-053426").map(|v| (v.content, v.leading_zeros)), Some(("-053426", 1))); assert_eq!(Number::read("-053426f").map(|v| (v.content, v.leading_zeros)), Some(("-053426", 1))); assert_eq!(Number::read("+53426").map(|v| (v.content, v.leading_zeros)), Some(("+53426", 0))); assert_eq!(Number::read("+53426g").map(|v| (v.content, v.leading_zeros)), Some(("+53426", 0))); assert_eq!(Number::read("+053426").map(|v| (v.content, v.leading_zeros)), Some(("+053426", 1))); assert_eq!(Number::read("+053426f").map(|v| (v.content, v.leading_zeros)), Some(("+053426", 1))); assert_eq!(Number::read("053426").map(|v| (v.content, v.leading_zeros)), Some(("053426", 1))); assert_eq!(Number::read("00053426").map(|v| (v.content, v.leading_zeros)), Some(("00053426", 3))); assert_eq!(Number::read("00053d426").map(|v| (v.content, v.leading_zeros)), Some(("00053", 3))); assert_eq!(Number::read("000g53d426").map(|v| (v.content, v.leading_zeros)), Some(("000", 3))); assert_eq!(Number::read("00g53d426").map(|v| (v.content, v.leading_zeros)), Some(("00", 2))); assert_eq!(Number::read("g53d426").map(|v| (v.content, v.leading_zeros)), None); assert_eq!(Number::read("2345").unwrap().cmp(&Number::read("2346").unwrap()), Ordering::Less); assert_eq!(Number::read("-2345").unwrap().cmp(&Number::read("-2346").unwrap()), Ordering::Greater); assert_eq!(Number::read("-2345").unwrap().cmp(&Number::read("-2345").unwrap()), Ordering::Equal); assert_eq!(Number::read("-2345").unwrap().cmp(&Number::read("+2345").unwrap()), Ordering::Less); assert_eq!(Number::read("-2345").unwrap().cmp(&Number::read("2345").unwrap()), Ordering::Less); assert_eq!(Number::read("+2345").unwrap().cmp(&Number::read("-2345").unwrap()), Ordering::Greater); assert_eq!(Number::read("2345").unwrap().cmp(&Number::read("-2345").unwrap()), Ordering::Greater); assert_eq!(Number::read("+2345").unwrap().cmp(&Number::read("+2345").unwrap()), Ordering::Equal); assert_eq!(Number::read("+2345").unwrap().cmp(&Number::read("2345").unwrap()), Ordering::Equal); assert_eq!(Number::read("2345").unwrap().cmp(&Number::read("+2345").unwrap()), Ordering::Equal); assert_eq!(Number::read("2345").unwrap().cmp(&Number::read("2345").unwrap()), Ordering::Equal); assert_eq!(Number::read("2345").unwrap().cmp(&Number::read("0002345").unwrap()), Ordering::Equal); assert_eq!(Number::read("234").unwrap().cmp(&Number::read("2345").unwrap()), Ordering::Less); assert_eq!(Number::read("0").unwrap().cmp(&Number::read("0").unwrap()), Ordering::Equal); assert_eq!(Number::read("0").unwrap().cmp(&Number::read("+0").unwrap()), Ordering::Equal); assert_eq!(Number::read("0").unwrap().cmp(&Number::read("-0").unwrap()), Ordering::Equal); assert_eq!(Number::read("+0").unwrap().cmp(&Number::read("0").unwrap()), Ordering::Equal); assert_eq!(Number::read("+0").unwrap().cmp(&Number::read("+0").unwrap()), Ordering::Equal); assert_eq!(Number::read("+0").unwrap().cmp(&Number::read("-0").unwrap()), Ordering::Equal); assert_eq!(Number::read("-0").unwrap().cmp(&Number::read("0").unwrap()), Ordering::Equal); assert_eq!(Number::read("-0").unwrap().cmp(&Number::read("+0").unwrap()), Ordering::Equal); assert_eq!(Number::read("-0").unwrap().cmp(&Number::read("-0").unwrap()), Ordering::Equal); assert_eq!(Number::read("000000234").unwrap().cmp(&Number::read("2345").unwrap()), Ordering::Less); assert_eq!(Number::read("000000234").unwrap().cmp(&Number::read("236521548").unwrap()), Ordering::Less); assert_eq!(Number::read("000000234").unwrap().cmp(&Number::read("000000236521548").unwrap()), Ordering::Less); assert_eq!(Number::read("01000000").unwrap().cmp(&Number::read("000000236521548").unwrap()), Ordering::Less); assert_eq!(Number::read("123").unwrap().cmp(&Number::read("101").unwrap()), Ordering::Greater); assert_eq!(Number::read("2345").unwrap(), Number::read("2345").unwrap()); assert_eq!(Number::read("2345").unwrap(), Number::read("02345").unwrap()); assert_eq!(Number::read("002345").unwrap(), Number::read("2345").unwrap()); assert_eq!(Number::read(""), None); assert_eq!(Number::read("help"), None); assert_eq!(Number::read("-"), None); assert_eq!(Number::read("+"), None); fn get(v: &str) -> &str { Number::read(v).unwrap().as_str() } assert_eq!(get("2345"), "2345"); assert_eq!(get("002345"), "002345"); assert_eq!(get("00000"), "00000"); assert_eq!(get("0"), "0"); for a in -128..=128 { for b in -128..=128 { assert_eq!(Number::read(&format!("{a}")).unwrap().cmp(&Number::read(&format!("{b}")).unwrap()), a.cmp(&b)); assert_eq!(Number::read(&format!("{a}")).unwrap().cmp(&Number::read(&format!("{b:+}")).unwrap()), a.cmp(&b)); assert_eq!(Number::read(&format!("{a:+}")).unwrap().cmp(&Number::read(&format!("{b}")).unwrap()), a.cmp(&b)); assert_eq!(Number::read(&format!("{a:+}")).unwrap().cmp(&Number::read(&format!("{b:+}")).unwrap()), a.cmp(&b)); } assert_eq!(Number::read("0").unwrap().cmp(&Number::read(&format!("{a:+}")).unwrap()), 0.cmp(&a)); assert_eq!(Number::read("+0").unwrap().cmp(&Number::read(&format!("{a:+}")).unwrap()), 0.cmp(&a)); assert_eq!(Number::read("-0").unwrap().cmp(&Number::read(&format!("{a:+}")).unwrap()), 0.cmp(&a)); assert_eq!(Number::read(&format!("{a:+}")).unwrap().cmp(&Number::read("0").unwrap()), a.cmp(&0)); assert_eq!(Number::read(&format!("{a:+}")).unwrap().cmp(&Number::read("+0").unwrap()), a.cmp(&0)); assert_eq!(Number::read(&format!("{a:+}")).unwrap().cmp(&Number::read("-0").unwrap()), a.cmp(&0)); } } /// A reference to a homogenous segment of text in a string. /// /// [`Ord`] and [`Eq`] are implemented for this type, which delegate to their respective types for same variant comparison, /// and otherwise considers every [`Segment::Number`] to come before every [`Segment::Text`]. #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] pub enum Segment<'a> { Number(Number<'a>), Text(Text<'a>), } impl<'a> Segment<'a> { /// Greedily reads a (non-empty) [`Text`] or [`Number`] segment from the beginning of the string. /// Returns [`None`] if the string is empty. pub fn read(src: &'a str) -> Option { if let Some(x) = Number::read(src) { return Some(Segment::Number(x)) } if let Some(x) = Text::read(src) { return Some(Segment::Text(x)) } debug_assert_eq!(src, ""); None } /// Returns the (non-empty) substring that was read via [`Segment::read`]. pub fn as_str(&self) -> &'a str { match self { Segment::Text(x) => x.as_str(), Segment::Number(x) => x.as_str(), } } /// Retrieves the value of the [`Segment::Number`] variant, or [`None`] if that is not the current variant. pub fn as_number(&self) -> Option> { if let Segment::Number(x) = self { Some(*x) } else { None } } /// Retrieves the value of the [`Segment::Text`] variant, or [`None`] if that is not the current variant. pub fn as_text(&self) -> Option> { if let Segment::Text(x) = self { Some(*x) } else { None } } } #[test] fn test_segment() { assert_eq!(Segment::read("00453hello").unwrap().as_number().unwrap().as_str(), "00453"); assert_eq!(Segment::read("453hello").unwrap().as_number().unwrap().as_str(), "453"); assert_eq!(Segment::read("000hello").unwrap().as_number().unwrap().as_str(), "000"); assert_eq!(Segment::read("hello 453").unwrap().as_text().unwrap().as_str(), "hello "); assert_eq!(Segment::read(" ").unwrap().as_text().unwrap().as_str(), " "); assert_eq!(Segment::read(""), None); fn get(v: &str) -> &str { Segment::read(v).unwrap().as_str() } assert_eq!(get("hello 69"), "hello "); assert_eq!(get("453 hello 69"), "453"); assert_eq!(get("00453 hello 69"), "00453"); assert_eq!(get("000"), "000"); assert_eq!(get("abc"), "abc"); assert_eq!(Segment::read("00000").unwrap().cmp(&Segment::read("aaaaa").unwrap()), Ordering::Less); assert_eq!(Segment::read("aaaaa").unwrap().cmp(&Segment::read("00000").unwrap()), Ordering::Greater); assert_eq!(Segment::read("0000").unwrap().cmp(&Segment::read("aaaaa").unwrap()), Ordering::Less); assert_eq!(Segment::read("aaaa").unwrap().cmp(&Segment::read("00000").unwrap()), Ordering::Greater); assert_eq!(Segment::read("00000").unwrap().cmp(&Segment::read("aaaa").unwrap()), Ordering::Less); assert_eq!(Segment::read("aaaaa").unwrap().cmp(&Segment::read("0000").unwrap()), Ordering::Greater); } /// An iterator over the [`Segment`] values within a string. /// /// This is a potentially-empty sequence of alternating [`Segment::Number`] and [`Segment::Text`] values (not necessarily in that order). #[derive(Clone, Copy)] pub struct SegmentIter<'a>(&'a str); impl<'a> SegmentIter<'a> { /// Constructs a new [`SegmentIter`] that iterates over the segments of the string. /// If the string is empty, the resulting iterator is likewise an empty sequence. pub fn new(src: &'a str) -> Self { Self(src) } /// Returns the remaining portion of the original string that has not yet been iterated. /// Returns an empty string if the iterator has been exhausted. pub fn as_str(&self) -> &'a str { self.0 } } impl<'a> Iterator for SegmentIter<'a> { type Item = Segment<'a>; fn next(&mut self) -> Option { let res = Segment::read(self.0)?; self.0 = &self.0[res.as_str().len()..]; Some(res) } } impl FusedIterator for SegmentIter<'_> {} #[test] fn test_segment_iter() { let mut seq = SegmentIter::new("34543hello this is 00343 2 a test"); assert_eq!(seq.as_str(), "34543hello this is 00343 2 a test"); assert_eq!(seq.next().unwrap().as_number().unwrap().as_str(), "34543"); assert_eq!(seq.as_str(), "hello this is 00343 2 a test"); assert_eq!(seq.next().unwrap().as_text().unwrap().as_str(), "hello this is "); assert_eq!(seq.as_str(), "00343 2 a test"); assert_eq!(seq.next().unwrap().as_number().unwrap().as_str(), "00343"); assert_eq!(seq.as_str(), " 2 a test"); assert_eq!(seq.next().unwrap().as_text().unwrap().as_str(), " "); assert_eq!(seq.as_str(), "2 a test"); assert_eq!(seq.next().unwrap().as_number().unwrap().as_str(), "2"); assert_eq!(seq.as_str(), " a test"); assert_eq!(seq.next().unwrap().as_text().unwrap().as_str(), " a test"); assert_eq!(seq.as_str(), ""); for _ in 0..16 { assert!(seq.next().is_none()); assert_eq!(seq.as_str(), ""); } fn get(v: &str) -> &str { SegmentIter::new(v).as_str() } assert_eq!(get("hello world"), "hello world"); } /// Performs a lexicographic comparison of the [`Segment`] sequences of two strings. /// /// This has the effect of ordering the strings with respect to [`Number`] and [`Text`] substrings. /// /// ``` /// # use numeric_sort::cmp; /// # use std::cmp::Ordering; /// assert_eq!(cmp("apple", "cable"), Ordering::Less); /// assert_eq!(cmp("32454", "hello"), Ordering::Less); /// assert_eq!(cmp("file-10", "file-3"), Ordering::Greater); /// assert_eq!(cmp("test-v1.10.25", "test-v1.9.2"), Ordering::Greater); /// assert_eq!(cmp("agent-007", "agent-7"), Ordering::Equal); /// ``` pub fn cmp(a: &str, b: &str) -> Ordering { SegmentIter::new(a).cmp(SegmentIter::new(b)) } #[test] fn test_cmp() { assert_eq!(cmp("hello-456", "hello-0999"), Ordering::Less); assert_eq!(cmp("hellos-456", "hello-0999"), Ordering::Greater); assert_eq!(cmp("hello--456", "hello-0999"), Ordering::Less); assert_eq!(cmp("v1.4.12.3", "v1.4.4.3"), Ordering::Greater); assert_eq!(cmp("val[-1]", "val[0]"), Ordering::Less); assert_eq!(cmp("val[-1]", "val[2]"), Ordering::Less); assert_eq!(cmp("val -1", "val 0"), Ordering::Less); assert_eq!(cmp("val -1", "val 2"), Ordering::Less); } /// Sorts an array via the [`cmp`] ordering. /// /// Because this function performs a stable sort, it must be allocating and so is only enabled with the `alloc` (default) feature. /// If `alloc` is not enabled or you do not require a stable sort, you may instead consider using [`sort_unstable`]. /// /// ``` /// # use numeric_sort::sort; /// let mut arr = ["file-1", "file-10", "file-2"]; /// sort(&mut arr); /// assert_eq!(&arr, &["file-1", "file-2", "file-10"]); /// ``` #[cfg(feature = "alloc")] pub fn sort>(arr: &mut [T]) { arr.sort_by(|a, b| cmp(a.as_ref(), b.as_ref())) // [T]::sort_by is stable and so requires alloc } /// Equivalent to [`sort`], but performs an unstable sort. /// /// Because this function works in-place, it is available even when the default `alloc` feature is disabled. pub fn sort_unstable>(arr: &mut [T]) { arr.sort_unstable_by(|a, b| cmp(a.as_ref(), b.as_ref())) } #[test] #[cfg(feature = "alloc")] fn test_sort() { use alloc::borrow::ToOwned; macro_rules! sorted { ($in:expr) => {{ let mut v = $in; sort(&mut v); v }} } assert_eq!(&sorted!(["file-1", "file-10", "file-2"]), &["file-1", "file-2", "file-10"]); assert_eq!(&sorted!(["file-1".to_owned(), "file-10".to_owned(), "file-2".to_owned()]), &["file-1", "file-2", "file-10"]); macro_rules! sorted_unstable { ($in:expr) => {{ let mut v = $in; sort_unstable(&mut v); v }} } assert_eq!(&sorted_unstable!(["file-1", "file-10", "file-2"]), &["file-1", "file-2", "file-10"]); assert_eq!(&sorted_unstable!(["file-1".to_owned(), "file-10".to_owned(), "file-2".to_owned()]), &["file-1", "file-2", "file-10"]); } #[test] fn test_sort_unstable() { macro_rules! sorted_unstable { ($in:expr) => {{ let mut v = $in; sort_unstable(&mut v); v }} } assert_eq!(&sorted_unstable!(["file-1", "file-10", "file-2"]), &["file-1", "file-2", "file-10"]); }