3 ms·
Yeah, when working with ascii, I just use `Vec<u8>`/`&[u8]`. There's also the `ascii` crate which encodes ascii into the type system (enums), but I find it easi
by ibraheemdev 5y ago
Yeah, when working with ascii, I just use `Vec<u8>`/`&[u8]`. There's also the `ascii` crate which encodes ascii into the type system (enums), but I find it easier to work with raw bytes. The equivalent code in Rust would be:
let mut bytes = c.as_bytes();
bytes[0].make_ascii_uppercase();
- Arnavion 5y agoYour code will not compile. `str::as_bytes` returns a `&[u8]` and indexing that gives a `&u8`, but `u8::make_ascii_uppercase` requires `&mut u8`. There is no safe way to get a `&mut [u8]` from a `&mut str` or a `&mut String` (because it would violate str's utf-8 invariant). You don't need to downgrade to `[u8]` in the first place. `&mut str` already has its own `make_ascii_uppercase`
- ibraheemdev 5y agoI assumed `c` was a `String` - my code should be `c.into_bytes()`. If you have a str, then of course mutating the bytes directly is unsafe. Also, `str::make_ascii_uppercase` would require using `get_mut` which does utf-8 checks.