Skip to content

Commit

Permalink
feat: add to_folded_case() method
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmonstar committed Oct 30, 2023
1 parent 917c88b commit 07f81c1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,24 @@ impl<S: AsRef<str>> UniCase<S> {
UniCase(Encoding::Unicode(Unicode(s)))
}
}

/// Returns a copy of this string where each character is mapped to its
/// Unicode CaseFolding equivalent.
///
/// # Note
///
/// Unicode Case Folding is meant for string storage and matching, not for
/// display.
pub fn to_folded_case(&self) -> String {
#[cfg(not(__unicase__core_and_alloc))]
#[allow(deprecated, unused)]
use std::ascii::AsciiExt;

match self.0 {
Encoding::Ascii(ref s) => s.0.as_ref().to_ascii_lowercase(),
Encoding::Unicode(ref s) => s.to_folded_case(),
}
}
}

impl<S> UniCase<S> {
Expand Down
13 changes: 13 additions & 0 deletions src/unicode/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#[cfg(all(__unicase__core_and_alloc, not(test)))]
use alloc::string::String;
#[cfg(__unicase__iter_cmp)]
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
Expand All @@ -8,6 +10,12 @@ mod map;
#[derive(Clone, Copy, Debug, Default)]
pub struct Unicode<S>(pub S);

impl<S: AsRef<str>> Unicode<S> {
pub fn to_folded_case(&self) -> String {
self.0.as_ref().chars().flat_map(lookup).collect()
}
}

impl<S1: AsRef<str>, S2: AsRef<str>> PartialEq<Unicode<S2>> for Unicode<S1> {
#[inline]
fn eq(&self, other: &Unicode<S2>) -> bool {
Expand Down Expand Up @@ -184,6 +192,11 @@ mod tests {
eq!("ᾲ στο διάολο", "ὰι στο διάολο");
}

#[test]
fn test_to_folded_case() {
assert_eq!(Unicode("Maße").to_folded_case(), "masse");
}

#[cfg(feature = "nightly")]
#[bench]
fn bench_ascii_folding(b: &mut ::test::Bencher) {
Expand Down

0 comments on commit 07f81c1

Please sign in to comment.