Skip to content

Commit b6d072d

Browse files
committed
Make collate_remove_chars return a Cow
1 parent 6f5312b commit b6d072d

File tree

1 file changed

+31
-17
lines changed

1 file changed

+31
-17
lines changed

components/suggest/src/geoname.rs

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
use rusqlite::{named_params, Connection};
1616
use serde::Deserialize;
1717
use sql_support::ConnExt;
18-
use std::hash::{Hash, Hasher};
18+
use std::{
19+
borrow::Cow,
20+
hash::{Hash, Hasher},
21+
};
1922
use unicase::UniCase;
2023
use unicode_normalization::{char::is_combining_mark, UnicodeNormalization};
2124

@@ -225,23 +228,34 @@ pub fn geonames_collate(a: &str, b: &str) -> std::cmp::Ordering {
225228
UniCase::new(collate_remove_chars(a)).cmp(&UniCase::new(collate_remove_chars(b)))
226229
}
227230

228-
fn collate_remove_chars(s: &str) -> String {
229-
s.nfkd()
230-
.filter_map(|c| {
231-
if is_combining_mark(c) {
232-
// remove Unicode combining marks ("Que\u{0301}bec" => "Quebec")
233-
None
234-
} else {
235-
match c {
236-
// remove '.' and ',' ("St. Louis, U.S.A." => "St Louis USA")
237-
'.' | ',' => None,
238-
// replace '-' with space ("Carmel-by-the-Sea" => "Carmel by the Sea")
239-
'-' => Some(' '),
240-
_ => Some(c),
231+
fn collate_remove_chars(s: &str) -> Cow<'_, str> {
232+
let borrowable = !s
233+
.nfkd()
234+
.any(|c| is_combining_mark(c) || matches!(c, '.' | ',' | '-'));
235+
236+
if borrowable {
237+
Cow::from(s)
238+
} else {
239+
s.nfkd()
240+
.filter_map(|c| {
241+
if is_combining_mark(c) {
242+
// Remove Unicode combining marks:
243+
// "Que\u{0301}bec" => "Quebec"
244+
None
245+
} else {
246+
match c {
247+
// Remove '.' and ',':
248+
// "St. Louis, U.S.A." => "St Louis USA"
249+
'.' | ',' => None,
250+
// Replace '-' with space:
251+
// "Carmel-by-the-Sea" => "Carmel by the Sea"
252+
'-' => Some(' '),
253+
_ => Some(c),
254+
}
241255
}
242-
}
243-
})
244-
.collect::<String>()
256+
})
257+
.collect::<_>()
258+
}
245259
}
246260

247261
impl SuggestDao<'_> {

0 commit comments

Comments
 (0)