简体   繁体   中英

Why does to_ascii_lowercase return a String rather than a Cow<str>?

str::to_ascii_lowercase returns a String. Why doesn't it return a Cow<str> just like to_string_lossy or String::from_utf8_lossy ?

The same applies to str::to_ascii_uppercase .

The reason why you might want to return a Cow<str> presumably is because the string may already be lower case. However, to detect this edge case might also introduce a performance degradation when the string is not already lower case, which intuitively seems like the most common scenario.

You can, of course, create your own function that wraps to_ascii_lowercase() , checks if it is already lower case, and return a Cow<str> :

fn my_to_ascii_lowercase<'a>(s: &'a str) -> Cow<'a, str> {
    let bytes = s.as_bytes();
    if !bytes.iter().any(u8::is_ascii_uppercase) {
        Cow::Borrowed(s)
    } else {
        Cow::Owned(s.to_ascii_lowercase())
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM