简体   繁体   中英

str ops into existing Vec

Most operations on str in Rust create newly-allocated String s. 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?

eg,

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.

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.

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