Does this allocate on the heap?

If I do this:

let message = "abcdef";
if message == message.to_uppercase() {

does the call to to_uppercase() allocate on the heap? Also, how can I find out other than asking here?

It returns a String, which is always heap allocated (unless empty).

you can learn that by reading the documentation for to_uppercase, and the documentation for the std::string module and the String type.

You can also check (for things in std) whether or not they're defined in core or alloc; if they're in core they won't allocate, and if they're in alloc they (probably) will.

In Unicode you can't compare with a upper/lowercased string to get case-insensitive comparison! This approach doesn't work, because of case rules in the Turkish language.

For ASCII there's eq_ignore_ascii_case for case-insensitive ASCII comparisons.

And non-allocating version for Unicode is:


:man_facepalming: I for some reason missed that it returns a String (or I forgot that the str method is different than the char method, because the compiler warned me that I can't compare char to std::char::ToUppercase.); I thought it returned a ToUppercase type for some reason.

So would this do the same job without allocating?

if message.chars().all(|c| !c.is_alphabetic() || c.is_uppercase() {
1 Like

Yes, iterators and is_ checks will compile to a simple loop.

BTW, char returns ToUppercase, because uppercase of some letters changes to multiple chars (e.g. ß -> SS).