4 ms·
Was hoping I could find something on changing a string in place (and efficiently) why is this such a difficult thing to do in rust? I am trying to build a pars
by pixel_tracing 6y ago
Was hoping I could find something on changing a string in place (and efficiently) why is this such a difficult thing to do in rust?
I am trying to build a parser combinator library in rust
- deleted 6y ago[deleted]
- tupshin 6y agoRust strings are UTF-8, and UTF-8 characters vary in byte length, therefore replacing same length character sequences don't guarantee that they will fit in the same number of bytes.
- jessegrosjean 6y agoRust uses very similar API to other languages for this: https://doc.rust-lang.org/std/string/struct.String.html#method.replace_range https://doc.rust-lang.org/std/string/struct.String.html#meth... The problems you are likely running into are higher level mutability issues. The above linked function requires &mut self, which means you need a mutable string. The above linked documentation has an example of using the `mut` keyword to declare a mutable string that you can replace_range on.
- bluejekyll 6y agoYou can modify strings in place, but not their length, which makes what your talking about complex if you need to support utf8. Here’s the str method: https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes_mut https://doc.rust-lang.org/std/primitive.str.html#method.as_b... If you want an string that is mutable, can be extended, etc. You want to use String, and that has plenty of methods for mutation. Remember, Rust strings are all utf8, and part of the safety contract is that they’re always valid.
- the8472 6y agoclear() + push_str() to reuse the storage to assemble a new string. replace_range() to splice something in the middle. This may require the tail to be moved around when lengths don't match. Note that Strings are stored as utf8, so a substring with the same number of characters can still result in a different number of bytes and thus require memmoves.