Ushering out strlcpy()
Ushering out strlcpy()
Posted Aug 25, 2022 18:48 UTC (Thu) by NYKevin (subscriber, #129325)Parent article: Ushering out strlcpy()
* They call it String::replace_range(), and it's a method rather than a free function. It also takes an argument describing which range of the string you want to replace (which can be the entire string, if desired).
* Most of the actual work is in Vec::splice(), which works for arbitrary vectors (dynamic arrays).
* They resize the string if the sizes don't match.
* In general, this whole operation is a lot easier in Rust than in C, because Rust's strings are heap-allocated dynamic arrays, which can be resized in the first place. So it's not solving the same problem (e.g. in some contexts, heap allocation might be seriously problematic).
* If you don't want to use heap-allocated strings and "just want a dumb array," you can use the copy_from_slice() method on primitive slices instead, which is functionally equivalent to memcpy. It panics if the slices have different lengths, but slices know their lengths so at least it's cheap to check for that in advance.
* It is illegal to have two mutable references (or one mutable and one immutable reference) to the same slice at the same time, so you can't copy_from_slice with overlapping arguments (hence they use memcpy instead of memmove). They provide copy_within() for the possibly-overlapping use case, or if the arguments wouldn't actually overlap, you can use split_at_mut() to break it apart into two separate slices.
* There are similar memcpy/memmove-like functions for raw pointers, but Rust considers raw pointers to be inherently unsafe, and so those functions are unsafe as well.
* Rust doesn't have a notion of null-terminated u8 arrays (that I could find), and so the exact "copy a C string" problem is not really a thing that exists in Rust. There is std::ffi::CString, but it doesn't have any methods for directly manipulating its contents; it looks like it's "just" an intermediary for converting between Rust strings and raw pointers.
