Home > Mobile >  str ops into existing Vec
str ops into existing Vec

Time:04-27

Most operations on str in Rust create newly-allocated Strings. I understand that, because UTF8 is complex, one cannot generally know beforehand the size of the output, and so that output must be growable. However, I might have my own buffer , such as a Vec<u8> I'd like to grow. Is there any way to specify an existing output container to string operations?

e.g.,

let s = "my string";
let s: Vec<u8> = Vec::with_capacity(100);  // explicit allocation
s.upper_into(s);  // perhaps new allocation here, if result fits in `v`

-EDIT-

This is, of course, just for one case. I'd love to be able to treat all of the str methods this way, including for example those in sentencecase , without having to copy their internal logic.

CodePudding user response:

You can walk char-by-char and use char::to_uppercase():

let mut uppercase = String::with_capacity(100);
uppercase.extend(s.chars().flat_map(char::to_uppercase));

I think it does not handle everything correctly, but this is exactly what str::to_uppercase() does too, so I assume it's OK.

  • Related