uuid-rs / uuid

Generate and parse UUIDs.

Home Page:https://www.crates.io/crates/uuid

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add `.as_str()` for Uuid

photino opened this issue · comments

Is there a cheap method .as_str() for the Uuid type? Currenly, we use uuid.to_string().as_str(), but it is not economic. std::str::from_utf8(uuid.as_bytes()).unwrap() also works, but the panic should be avoided since the uuid bytes are guaranteed to be valid ascii chars.

A possible implementation can be

pub fn as_str(&self) -> &str {
    let bytes = self.as_bytes();
    unsafe { std::str::from_utf8_unchecked(bytes) }
}

Hi @photino! 👋

This is actually something you can already do using the types in the fmt module. As an example, you can efficiently encode a UUID in its hyphenated format using the Hyphenated::encode_lower method. We should add an example to the repo to make that easier to find.

Unfortunately the example using from_utf8_unchecked is unsound and shouldn't be used; a UUID can contain any arbitrary bytes, they're not guaranteed to be valid UTF8.

@KodrAus Thanks! It solved my problem.