Ushering out strlcpy()
Ushering out strlcpy()
Posted Aug 26, 2022 10:30 UTC (Fri) by tialaramex (subscriber, #21167)In reply to: Ushering out strlcpy() by wtarreau
Parent article: Ushering out strlcpy()
However, the byte-oriented code you've written can indeed be expressed in Rust, from Rust's point of view these are just bytes (type u8) in a mutable slice of some sort. Rust knows how big the slice is, (the unforgivable mistake in C is that it doesn't know how big whatever char *hdr is pointing at is) and so we can safely change the bytes within it.
I assume you don't consider the behaviour if hdr is in fact pointing at something that is not a zero-terminated string (ie a buffer overflow with undefined behaviour) to be desirable, and so we don't need Rust's unsafe which is the only way to duplicate that.
https://gist.github.com/rust-play/59883fd0aecbfa0c988f2bf...
[ I have not tested this code, but I believe it does what your C does ]
One very obvious difference is that Rust doesn't have pointer arithmetic, so we're writing the Rust in terms of indexing into the slice. The compiler, of course, is free to implement this with identical machine code.
Rust doesn't think that "any slice of bytes" is a string, but, on the other hand, it also thinks most of C's "string" features are reasonable things to do to a slice of bytes, so this is mostly a matter of terminology. You can for example call make_ascii_lowercase() on a slice. If it wasn't actually ASCII text before then what this does is well defined but probably not very useful.
