cow_to_ascii_lowercase()

This commit is contained in:
Simon Sapin 2016-10-06 18:39:03 +02:00
parent 120b003195
commit 97344b150d
5 changed files with 27 additions and 1 deletions

View file

@ -3,6 +3,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use num_traits::ToPrimitive;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::convert::AsRef;
use std::iter::{Filter, Peekable};
use std::str::Split;
@ -125,3 +127,13 @@ pub fn str_join<I, T>(strs: I, join: &str) -> String
acc
})
}
/// Like AsciiExt::to_ascii_lowercase, but avoids allocating when the input is already lower-case.
pub fn cow_into_ascii_lowercase<'a, S: Into<Cow<'a, str>>>(s: S) -> Cow<'a, str> {
let mut cow = s.into();
match cow.bytes().position(|byte| byte >= b'A' && byte <= b'Z') {
Some(first_uppercase) => cow.to_mut()[first_uppercase..].make_ascii_lowercase(),
None => {}
}
cow
}