uncased-0.9.6/.cargo_vcs_info.json0000644000000001120000000000000124630ustar { "git": { "sha1": "b654387f42a404a09504b0fc8321b116f4d22b51" } } uncased-0.9.6/.github/workflows/CI.yml000064400000000000000000000016710000000000000156570ustar 00000000000000name: CI on: [push, pull_request] jobs: test: name: "${{ matrix.os.name }} ${{ matrix.test.name }}" strategy: matrix: os: - name: Linux distro: ubuntu-latest - name: Windows distro: windows-latest - name: macOS distro: macOS-latest test: - name: Stable toolchain: stable flag: - name: Stable (--all-features) toolchain: stable flag: "--all-features" runs-on: ${{ matrix.os.distro }} steps: - name: Checkout Sources uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.test.toolchain }} override: true - name: Run Tests uses: actions-rs/cargo@v1 with: command: test args: ${{ matrix.test.flag }} uncased-0.9.6/.gitignore000064400000000000000000000000100000000000000132160ustar 00000000000000/target uncased-0.9.6/Cargo.toml0000644000000023460000000000000104740ustar # 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] edition = "2018" name = "uncased" version = "0.9.6" authors = ["Sergio Benitez "] description = "Case-preserving, ASCII case-insensitive, no_std string types." documentation = "https://docs.rs/uncased/0.9" readme = "README.md" keywords = ["ascii", "uncased", "case-preserving", "case-insensitive", "no_std"] categories = ["text-processing", "value-formatting", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/SergioBenitez/uncased" [dependencies.serde] version = "1.0" optional = true default-features = false [build-dependencies.version_check] version = "0.9" [features] alloc = [] default = ["alloc"] with-serde = ["serde"] with-serde-alloc = ["serde", "serde/alloc", "alloc"] uncased-0.9.6/Cargo.toml.orig000064400000000000000000000013330000000000000141260ustar 00000000000000[package] name = "uncased" version = "0.9.6" authors = ["Sergio Benitez "] edition = "2018" description = "Case-preserving, ASCII case-insensitive, no_std string types." documentation = "https://docs.rs/uncased/0.9" repository = "https://github.com/SergioBenitez/uncased" readme = "README.md" keywords = ["ascii", "uncased", "case-preserving", "case-insensitive", "no_std"] license = "MIT OR Apache-2.0" categories = ["text-processing", "value-formatting", "no-std"] [features] default = ["alloc"] alloc = [] with-serde = ["serde"] with-serde-alloc = ["serde", "serde/alloc", "alloc"] [dependencies] serde = { version = "1.0", default-features = false, optional = true } [build-dependencies] version_check = "0.9" uncased-0.9.6/LICENSE-APACHE000064400000000000000000000227730000000000000131760ustar 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 uncased-0.9.6/LICENSE-MIT000064400000000000000000000020700000000000000126720ustar 00000000000000The MIT License (MIT) Copyright (c) 2020 Sergio Benitez 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. uncased-0.9.6/README.md000064400000000000000000000033410000000000000125170ustar 00000000000000# uncased   [![crates.io]][crate] [![docs.rs]][docs] [crates.io]: https://img.shields.io/crates/v/uncased.svg [crate]: https://crates.io/crates/uncased [docs.rs]: https://docs.rs/uncased/badge.svg [docs]: https://docs.rs/uncased Case-preserving, ASCII case-insensitive `no_std` string types. An _uncased_ string is case-preserving. That is, the string itself contains cased characters, but comparison (including ordering, equality, and hashing) is ASCII case-insensitive. ```rust use uncased::UncasedStr; let x: &UncasedStr = "hello!".into(); let y: &UncasedStr = "HelLo!".into(); assert_eq!(x, y); assert_eq!(x.as_str(), "hello!"); assert_eq!(y.as_str(), "HelLo!"); ``` See the [documentation](http://docs.rs/uncased) for detailed usage information. # Usage Add the following to your `Cargo.toml`: ```toml [dependencies] uncased = "0.9" ``` This crate is `#![no_std]` compatible. By default, the `alloc` feature is enabled, which enables the `Uncased` type but requires `alloc` support. To disable the feature, disable this crate's default features: ```toml [dependencies] uncased = { version = "0.9", default-features = false } ``` **Note:** This crate _does not_ perform Unicode case-folding. For Unicode case-folding, see [`unicase`](https://crates.io/crates/unicase). # License `uncased` is licensed under either of the following, at your option: * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in `uncased` by you shall be dual licensed as above without any additional terms or conditions. uncased-0.9.6/build.rs000064400000000000000000000002010000000000000126750ustar 00000000000000fn main() { if let Some(true) = version_check::is_feature_flaggable() { println!("cargo:rustc-cfg=nightly"); } } uncased-0.9.6/src/as_uncased.rs000064400000000000000000000011360000000000000145020ustar 00000000000000use crate::UncasedStr; /// Helper trait to convert string-like references to `&UncasedStr`. /// /// # Example /// /// ```rust /// use uncased::AsUncased; /// /// let string = "Hello, world!".as_uncased(); /// assert_eq!(string, "hello, world!"); /// assert_eq!(string, "HELLO, world!"); /// assert_eq!(string, "HELLO, WORLD!"); /// ``` pub trait AsUncased { /// Convert `self` to an [`UncasedStr`]. fn as_uncased(&self) -> &UncasedStr; } impl + ?Sized> AsUncased for T { #[inline(always)] fn as_uncased(&self) -> &UncasedStr { UncasedStr::new(self.as_ref()) } } uncased-0.9.6/src/borrowed.rs000064400000000000000000000154770000000000000142350ustar 00000000000000use core::cmp::Ordering; use core::hash::{Hash, Hasher}; use core::fmt; #[cfg(feature = "alloc")] use alloc::string::String; /// A cost-free reference to an uncased (case-insensitive, case-preserving) /// ASCII string. /// /// This is typically created from an `&str` as follows: /// /// ```rust /// use uncased::UncasedStr; /// /// let ascii_ref: &UncasedStr = "Hello, world!".into(); /// ``` #[derive(Debug)] #[repr(transparent)] pub struct UncasedStr(str); impl UncasedStr { /// Cost-free conversion from an `&str` reference to an `UncasedStr`. /// /// # Example /// /// ```rust /// use uncased::UncasedStr; /// /// let uncased_str = UncasedStr::new("Hello!"); /// assert_eq!(uncased_str, "hello!"); /// assert_eq!(uncased_str, "Hello!"); /// assert_eq!(uncased_str, "HeLLo!"); /// ``` #[inline(always)] pub fn new(string: &str) -> &UncasedStr { // This is a `newtype`-like transformation. `repr(transparent)` ensures // that this is safe and correct. unsafe { &*(string as *const str as *const UncasedStr) } } /// Returns `self` as an `&str`. /// /// # Example /// /// ```rust /// use uncased::UncasedStr; /// /// let uncased_str = UncasedStr::new("Hello!"); /// assert_eq!(uncased_str.as_str(), "Hello!"); /// assert_ne!(uncased_str.as_str(), "hELLo!"); /// ``` #[inline(always)] pub fn as_str(&self) -> &str { &self.0 } /// Returns the length, in bytes, of `self`. /// /// # Example /// /// ```rust /// use uncased::UncasedStr; /// /// let uncased_str = UncasedStr::new("Hello!"); /// assert_eq!(uncased_str.len(), 6); /// ``` #[inline(always)] pub fn len(&self) -> usize { self.as_str().len() } /// Returns `true` if `self` has a length of zero bytes. /// /// # Examples /// /// ``` /// use uncased::UncasedStr; /// /// let s = UncasedStr::new(""); /// assert!(s.is_empty()); /// /// let s = UncasedStr::new("not empty"); /// assert!(!s.is_empty()); /// ``` #[inline] pub fn is_empty(&self) -> bool { self.as_str().is_empty() } /// Returns `true` if `self` starts with any casing of the string `string`; /// otherwise, returns `false`. /// /// # Example /// /// ```rust /// use uncased::UncasedStr; /// /// let uncased_str = UncasedStr::new("MoOO"); /// assert!(uncased_str.starts_with("moo")); /// assert!(uncased_str.starts_with("MOO")); /// assert!(uncased_str.starts_with("MOOO")); /// assert!(!uncased_str.starts_with("boo")); /// /// let uncased_str = UncasedStr::new("Bèe"); /// assert!(!uncased_str.starts_with("Be")); /// assert!(uncased_str.starts_with("Bè")); /// assert!(uncased_str.starts_with("Bè")); /// assert!(uncased_str.starts_with("bèe")); /// assert!(uncased_str.starts_with("BèE")); /// ``` #[inline(always)] pub fn starts_with(&self, string: &str) -> bool { self.as_str() .get(..string.len()) .map(|s| Self::new(s) == string) .unwrap_or(false) } /// Converts a `Box` into an `Uncased` without copying or /// allocating. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// let uncased = Uncased::new("Hello!"); /// let boxed = uncased.clone().into_boxed_uncased(); /// assert_eq!(boxed.into_uncased(), uncased); /// ``` #[inline(always)] #[cfg(feature = "alloc")] #[cfg_attr(nightly, doc(cfg(feature = "alloc")))] pub fn into_uncased(self: alloc::boxed::Box) -> crate::Uncased<'static> { // This is the inverse of a `newtype`-like transformation. The // `repr(transparent)` ensures that this is safe and correct. unsafe { let raw_str = alloc::boxed::Box::into_raw(self) as *mut str; crate::Uncased::from(alloc::boxed::Box::from_raw(raw_str).into_string()) } } } impl<'a> From<&'a str> for &'a UncasedStr { #[inline(always)] fn from(string: &'a str) -> &'a UncasedStr { UncasedStr::new(string) } } impl> core::ops::Index for UncasedStr { type Output = UncasedStr; #[inline] fn index(&self, index: I) -> &Self::Output { self.as_str()[index].into() } } impl AsRef for UncasedStr { fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<[u8]> for UncasedStr { fn as_ref(&self) -> &[u8] { self.as_str().as_bytes() } } impl fmt::Display for UncasedStr { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } macro_rules! impl_partial_eq { ($other:ty $([$o_i:ident])? = $this:ty $([$t_i:ident])?) => ( impl PartialEq<$other> for $this { #[inline(always)] fn eq(&self, other: &$other) -> bool { self $(.$t_i())? .eq_ignore_ascii_case(other $(.$o_i())?) } } ) } impl_partial_eq!(UncasedStr [as_str] = UncasedStr [as_str]); impl_partial_eq!(str = UncasedStr [as_str]); impl_partial_eq!(UncasedStr [as_str] = str); impl_partial_eq!(str = &UncasedStr [as_str]); impl_partial_eq!(&UncasedStr [as_str] = str); impl_partial_eq!(&str = UncasedStr [as_str]); impl_partial_eq!(UncasedStr [as_str] = &str); #[cfg(feature = "alloc")] impl_partial_eq!(String [as_str] = UncasedStr [as_str]); #[cfg(feature = "alloc")] impl_partial_eq!(UncasedStr [as_str] = String [as_str] ); impl Eq for UncasedStr { } macro_rules! impl_partial_ord { ($other:ty $([$o_i:ident])? >< $this:ty $([$t_i:ident])?) => ( impl PartialOrd<$other> for $this { #[inline(always)] fn partial_cmp(&self, other: &$other) -> Option { let this: &UncasedStr = self$(.$t_i())?.into(); let other: &UncasedStr = other$(.$o_i())?.into(); this.partial_cmp(other) } } ) } impl PartialOrd for UncasedStr { #[inline(always)] fn partial_cmp(&self, other: &UncasedStr) -> Option { Some(self.cmp(other)) } } impl Ord for UncasedStr { fn cmp(&self, other: &Self) -> Ordering { let self_chars = self.0.chars().map(|c| c.to_ascii_lowercase()); let other_chars = other.0.chars().map(|c| c.to_ascii_lowercase()); self_chars.cmp(other_chars) } } impl_partial_ord!(str >< UncasedStr); impl_partial_ord!(UncasedStr >< str); #[cfg(feature = "alloc")] impl_partial_ord!(String [as_str] >< UncasedStr); #[cfg(feature = "alloc")] impl_partial_ord!(UncasedStr >< String [as_str]); impl Hash for UncasedStr { #[inline(always)] fn hash(&self, hasher: &mut H) { self.0.bytes().for_each(|b| hasher.write_u8(b.to_ascii_lowercase())); } } uncased-0.9.6/src/lib.rs000064400000000000000000000053330000000000000131460ustar 00000000000000//! Case-preserving, ASCII case-insensitive `no_std` string types. //! //! An _uncased_ string is case-preserving. That is, the string itself contains //! cased characters, but comparison (including ordering, equality, and hashing) //! is ASCII case-insensitive. //! //! ```rust //! use uncased::UncasedStr; //! //! let x: &UncasedStr = "hello!".into(); //! let y: &UncasedStr = "HelLo!".into(); //! //! assert_eq!(x, y); //! assert_eq!(x.as_str(), "hello!"); //! assert_eq!(y.as_str(), "HelLo!"); //! //! let x_sub = &x[..4]; //! let y_sub = &y[..4]; //! assert_eq!(x_sub, y_sub); //! assert_eq!(x_sub.as_str(), "hell"); //! assert_eq!(y_sub.as_str(), "HelL"); //! ``` //! //! ## Unicode //! //! This crate _does not_ perform Unicode case-folding. For Unicode //! case-folding, see [`unicase`](https://crates.io/crates/unicase). //! //! ## Features and `no_std` //! //! Crate features: //! //! * `alloc` (_default_) - enables the [`Uncased`] type //! * `with-serde` - enables (de)serializing of [`UncasedStr`] via `serde` //! * `with-serde-alloc` - enables `alloc`, (de)serializing of [`UncasedStr`] //! and [`Uncased`] via `serde` //! //! This crate is `#![no_std]` compatible. By default, the `alloc` feature is //! enabled, which enables the [`Uncased`] type but requires `alloc` support. To //! disable the feature, disable this crate's default features: //! //! ```toml //! [dependencies] //! uncased = { version = "0.9", default-features = false } //! ``` //! //! In addition to the `alloc` feature, support for (de)serializing `UncasedStr` //! with `serde` can be enabled via the `with-serde` feature. Support for //! (de)serserializing both `UncasedStr` and `Uncased` can be enabled via the //! `with-serde-alloc` feature, which implicitly enables the `alloc` feature. #![no_std] #![cfg_attr(nightly, feature(doc_cfg))] #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "serde")] mod serde; #[cfg(feature = "alloc")] mod owned; #[cfg(test)] mod tests; mod borrowed; mod as_uncased; #[cfg(feature = "alloc")] pub use owned::Uncased; pub use borrowed::UncasedStr; pub use as_uncased::AsUncased; /// Returns true if `s1` and `s2` are equal without considering case. /// /// That is, this function returns `s1.to_ascii_lowercase() == /// s2.to_ascii_lowercase()`, but does it in a much faster way. This is also /// equivalent to `UncasedStr::new(s1) == UncasedStr::new(s2)`. /// /// # Example /// /// ```rust /// assert!(uncased::eq("ENV", "env")); /// assert!(uncased::eq("bRoWN", "BROWN")); /// assert!(uncased::eq("hi", "HI")); /// assert!(uncased::eq("dogs are COOL!", "DOGS are cool!")); /// ``` #[inline(always)] pub fn eq, S2: AsRef>(s1: S1, s2: S2) -> bool { UncasedStr::new(s1.as_ref()) == UncasedStr::new(s2.as_ref()) } uncased-0.9.6/src/owned.rs000064400000000000000000000173560000000000000135240ustar 00000000000000use alloc::borrow::{Cow, Borrow}; use alloc::{string::String, boxed::Box}; use core::ops::Deref; use core::cmp::Ordering; use core::hash::{Hash, Hasher}; use core::fmt; use crate::UncasedStr; /// An uncased (case-insensitive, case-preserving), owned _or_ borrowed ASCII /// string. #[cfg_attr(nightly, doc(cfg(feature = "alloc")))] #[derive(Clone, Debug)] pub struct Uncased<'s> { #[doc(hidden)] pub string: Cow<'s, str> } impl<'s> Uncased<'s> { /// Creates a new `Uncased` string from `string` without allocating. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// let uncased = Uncased::new("Content-Type"); /// assert_eq!(uncased, "content-type"); /// assert_eq!(uncased, "CONTENT-Type"); /// ``` #[inline(always)] pub fn new>>(string: S) -> Uncased<'s> { Uncased { string: string.into() } } /// Creates a new `Uncased` string from a borrowed `string`. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// const UNCASED: Uncased = Uncased::from_borrowed("Content-Type"); /// assert_eq!(UNCASED, "content-type"); /// assert_eq!(UNCASED, "CONTENT-Type"); /// ``` #[inline(always)] pub const fn from_borrowed(string: &'s str) -> Uncased<'s> { Uncased { string: Cow::Borrowed(string) } } /// Creates a new `Uncased` string from `string` without allocating. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// const UNCASED: Uncased = Uncased::from_owned(String::new()); /// /// let uncased = Uncased::from_owned("Content-Type".to_string()); /// assert_eq!(uncased, "content-type"); /// assert_eq!(uncased, "CONTENT-Type"); /// ``` #[inline(always)] pub const fn from_owned(string: String) -> Uncased<'s> { Uncased { string: Cow::Owned(string) } } /// Converts `self` into an owned `Uncased<'static>`, allocating if /// necessary. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// let foo = "foo".to_string(); /// let uncased = Uncased::from(foo.as_str()); /// let owned: Uncased<'static> = uncased.into_owned(); /// assert_eq!(owned, "foo"); /// ``` #[inline(always)] pub fn as_uncased_str(&self) -> &UncasedStr { self.as_ref() } /// Converts `self` into an owned `String`, allocating if necessary. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// let uncased = Uncased::new("Content-Type"); /// let string = uncased.into_string(); /// assert_eq!(string, "Content-Type".to_string()); /// ``` #[inline(always)] pub fn into_string(self) -> String { self.string.into_owned() } /// Converts `self` into an owned `Uncased<'static>`, allocating if /// necessary. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// let foo = "foo".to_string(); /// let uncased = Uncased::from(foo.as_str()); /// let owned: Uncased<'static> = uncased.into_owned(); /// assert_eq!(owned, "foo"); /// ``` #[inline(always)] pub fn into_owned(self) -> Uncased<'static> { match self.string { Cow::Owned(string) => Uncased::new(string), Cow::Borrowed(str) => Uncased::new(String::from(str)), } } /// Converts `self` into a `Box`. /// /// # Example /// /// ```rust /// use uncased::Uncased; /// /// let boxed = Uncased::new("Content-Type").into_boxed_uncased(); /// assert_eq!(&*boxed, "content-type"); /// ``` #[inline(always)] pub fn into_boxed_uncased(self) -> Box { // This is simply a `newtype`-like transformation. The // `repr(transparent)` ensures that this is safe and correct. Note this // exact pattern appears often in the standard library. unsafe { let raw_str = Box::into_raw(self.string.into_owned().into_boxed_str()); Box::from_raw(raw_str as *mut UncasedStr) } } /// Returns the inner `Cow`. #[doc(hidden)] #[inline(always)] pub fn into_cow(self) -> Cow<'s, str> { self.string } } impl Deref for Uncased<'_> { type Target = UncasedStr; #[inline(always)] fn deref(&self) -> &UncasedStr { UncasedStr::new(self.string.borrow()) } } impl AsRef for Uncased<'_> { #[inline(always)] fn as_ref(&self) -> &UncasedStr { UncasedStr::new(self.string.borrow()) } } impl AsRef for Uncased<'_> { #[inline(always)] fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<[u8]> for Uncased<'_> { #[inline(always)] fn as_ref(&self) -> &[u8] { self.as_str().as_bytes() } } impl Borrow for Uncased<'_> { #[inline(always)] fn borrow(&self) -> &UncasedStr { self.as_str().into() } } impl<'s, 'c: 's> From<&'c UncasedStr> for Uncased<'s> { #[inline(always)] fn from(string: &'c UncasedStr) -> Self { Uncased::new(string.as_str()) } } impl<'s, 'c: 's> From<&'c str> for Uncased<'s> { #[inline(always)] fn from(string: &'c str) -> Self { Uncased::new(string) } } impl From for Uncased<'static> { #[inline(always)] fn from(string: String) -> Self { Uncased::new(string) } } impl<'s, 'c: 's> From> for Uncased<'s> { #[inline(always)] fn from(string: Cow<'c, str>) -> Self { Uncased::new(string) } } impl fmt::Display for Uncased<'_> { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.string.fmt(f) } } macro_rules! impl_partial_eq { ($other:ty $([$o_i:ident])? = $this:ty $([$t_i:ident])?) => ( impl PartialEq<$other> for $this { #[inline(always)] fn eq(&self, other: &$other) -> bool { self $(.$t_i())? .eq(other $(.$o_i())?) } } ) } impl_partial_eq!(Uncased<'_> [as_uncased_str] = Uncased<'_> [as_uncased_str]); impl_partial_eq!(str = Uncased<'_> [as_uncased_str]); impl_partial_eq!(Uncased<'_> [as_uncased_str] = str); impl_partial_eq!(&str = Uncased<'_> [as_uncased_str]); impl_partial_eq!(Uncased<'_> [as_uncased_str] = &str); impl_partial_eq!(String [as_str] = Uncased<'_> [as_uncased_str]); impl_partial_eq!(Uncased<'_> [as_uncased_str] = String [as_str]); impl_partial_eq!(String [as_str] = &Uncased<'_> [as_uncased_str]); impl_partial_eq!(&Uncased<'_> [as_uncased_str] = String [as_str]); macro_rules! impl_partial_ord { ($other:ty $([$o_i:ident])? >< $this:ty $([$t_i:ident])?) => ( impl PartialOrd<$other> for $this { #[inline(always)] fn partial_cmp(&self, other: &$other) -> Option { let this: &UncasedStr = self$(.$t_i())?.into(); let other: &UncasedStr = other$(.$o_i())?.into(); this.partial_cmp(other) } } ) } impl Ord for Uncased<'_> { fn cmp(&self, other: &Self) -> Ordering { self.as_uncased_str().cmp(other.as_uncased_str()) } } impl_partial_ord!(Uncased<'_> [as_uncased_str] >< Uncased<'_> [as_uncased_str]); impl_partial_ord!(str >< Uncased<'_> [as_uncased_str]); impl_partial_ord!(Uncased<'_> [as_uncased_str] >< str); impl_partial_ord!(String [as_str] >< Uncased<'_> [as_uncased_str]); impl_partial_ord!(Uncased<'_> [as_uncased_str] >< String [as_str]); impl_partial_ord!(String [as_str] >< &Uncased<'_> [as_uncased_str]); impl_partial_ord!(&Uncased<'_> [as_uncased_str] >< String [as_str]); impl Eq for Uncased<'_> { } impl Hash for Uncased<'_> { #[inline(always)] fn hash(&self, hasher: &mut H) { self.as_uncased_str().hash(hasher) } } uncased-0.9.6/src/serde.rs000064400000000000000000000020640000000000000135000ustar 00000000000000use serde::de::Deserialize; use serde::ser::{self, Serialize}; use crate::UncasedStr; impl<'a, 'de: 'a> Deserialize<'de> for &'a UncasedStr { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { Ok(<&str>::deserialize(deserializer)?.into()) } } impl<'a> Serialize for &'a UncasedStr { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.as_str()) } } #[cfg(feature = "with-serde-alloc")] mod uncased_alloc { use super::*; use crate::Uncased; impl<'a, 'de> Deserialize<'de> for Uncased<'a> { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { Ok(alloc::string::String::deserialize(deserializer)?.into()) } } impl<'a> Serialize for Uncased<'a> { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.as_str()) } } } uncased-0.9.6/src/tests.rs000064400000000000000000000037440000000000000135460ustar 00000000000000#![allow(deprecated)] use crate::UncasedStr; use core::hash::{Hash, Hasher, SipHasher}; fn hash(t: &T) -> u64 { let mut s = SipHasher::new(); t.hash(&mut s); s.finish() } macro_rules! assert_uncased_eq { ($($string:expr),+) => ({ let strings = [$($string),+]; for i in 0..strings.len() { for j in i..strings.len() { let (str_a, str_b) = (strings[i], strings[j]); let ascii_a = UncasedStr::new(str_a); let ascii_b = UncasedStr::new(str_b); assert_eq!(ascii_a, ascii_b); assert_eq!(hash(&ascii_a), hash(&ascii_b)); assert_eq!(ascii_a, str_a); assert_eq!(ascii_b, str_b); assert_eq!(ascii_a, str_b); assert_eq!(ascii_b, str_a); } } }) } #[test] fn test_case_insensitive() { assert_uncased_eq!["a", "A"]; assert_uncased_eq!["Aa", "aA", "AA", "aa"]; assert_uncased_eq!["a a", "a A", "A A", "a a"]; assert_uncased_eq!["foobar", "FOOBAR", "FooBar", "fOObAr", "fooBAR"]; assert_uncased_eq!["", ""]; assert_uncased_eq!["content-type", "Content-Type", "CONTENT-TYPE"]; } #[test] fn test_case_cmp() { assert!(UncasedStr::new("foobar") == UncasedStr::new("FOOBAR")); assert!(UncasedStr::new("a") == UncasedStr::new("A")); assert!(UncasedStr::new("a") < UncasedStr::new("B")); assert!(UncasedStr::new("A") < UncasedStr::new("B")); assert!(UncasedStr::new("A") < UncasedStr::new("b")); assert!(UncasedStr::new("aa") > UncasedStr::new("a")); assert!(UncasedStr::new("aa") > UncasedStr::new("A")); assert!(UncasedStr::new("AA") > UncasedStr::new("a")); assert!(UncasedStr::new("AA") > UncasedStr::new("a")); assert!(UncasedStr::new("Aa") > UncasedStr::new("a")); assert!(UncasedStr::new("Aa") > UncasedStr::new("A")); assert!(UncasedStr::new("aA") > UncasedStr::new("a")); assert!(UncasedStr::new("aA") > UncasedStr::new("A")); }