use std::borrow::Cow;
use icu_casemap::CaseMapper;
pub fn fold(text: &str) -> Cow<'_, str> {
if text.is_ascii() {
return if text.bytes().any(|byte| byte.is_ascii_uppercase()) {
Cow::Owned(text.to_ascii_lowercase())
} else {
Cow::Borrowed(text)
};
}
let mapper = CaseMapper::new();
let first_change = text
.char_indices()
.find(|&(_, ch)| mapper.simple_fold(ch) != ch);
match first_change {
None => Cow::Borrowed(text),
Some((at, _)) => {
let mut folded = String::with_capacity(text.len());
folded.push_str(&text[..at]);
folded.extend(text[at..].chars().map(|ch| mapper.simple_fold(ch)));
Cow::Owned(folded)
}
}
}
pub fn fold_into(text: &str, out: &mut String) {
if text.is_ascii() {
let start = out.len();
out.push_str(text);
out[start..].make_ascii_lowercase();
} else {
let mapper = CaseMapper::new();
out.extend(text.chars().map(|ch| mapper.simple_fold(ch)));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ascii_shortcut_agrees_with_unicode_simple_folding() {
let mapper = CaseMapper::new();
for byte in 0_u8..=127 {
let ch = char::from(byte);
assert_eq!(
mapper.simple_fold(ch),
ch.to_ascii_lowercase(),
"character {byte}"
);
}
}
#[test]
fn fold_into_appends_the_same_folding() {
for text in ["PowerShell.EXE", "\u{3a3}\u{3c2}", "\u{212a}elvin", ""] {
let mut out = String::from("prefix:");
fold_into(text, &mut out);
assert_eq!(out, format!("prefix:{}", fold(text)));
}
}
#[test]
fn ascii_folds_to_lower_case() {
assert_eq!(fold("PowerShell.EXE"), "powershell.exe");
}
#[test]
fn unchanged_text_is_borrowed() {
assert!(matches!(fold(r"c:\windows\cmd.exe"), Cow::Borrowed(_)));
assert!(matches!(fold(""), Cow::Borrowed(_)));
}
#[test]
fn every_greek_sigma_folds_to_the_same_character() {
assert_eq!(fold("\u{3a3}"), "\u{3c3}");
assert_eq!(fold("\u{3c2}"), "\u{3c3}");
}
#[test]
fn compatibility_characters_fold_to_their_letters() {
assert_eq!(fold("\u{212a}"), "k");
assert_eq!(fold("\u{17f}"), "s");
}
#[test]
fn sharp_s_keeps_its_length() {
assert_eq!(fold("\u{df}"), "\u{df}");
assert_eq!(fold("\u{1e9e}"), "\u{df}");
}
#[test]
fn folding_ignores_locale() {
assert_eq!(fold("\u{130}"), "\u{130}");
assert_eq!(fold("\u{131}"), "\u{131}");
}
#[test]
fn folding_is_idempotent() {
for text in ["MiXeD", "\u{3a3}\u{3c2}", "\u{212a}elvin", "\u{1e9e}"] {
let once = fold(text).into_owned();
assert_eq!(fold(&once), once.as_str());
}
}
}