stellar / rs-soroban-env

Rust environment for Soroban contracts.
Apache License 2.0
59 stars 40 forks source link

Add an `as_bytes` or `to_bytes` to the `String` type #1337

Open kalepail opened 6 months ago

kalepail commented 6 months ago

As far as I'm aware it's currently not possible to convert the String type into it's Bytes counterpart. This limits the usefulness of String significantly. Would love to see this feature added.

Discord context: https://discord.com/channels/897514728459468821/1201650246573367407

Xand6r commented 4 months ago

For anyone who later runs into this issue.

pub fn string_to_bytes(str1: String) -> Bytes {
    let env = Env::default();
    let str_len = str1.len() as usize;

    // how large should this buffer be?
    let mut slice: [u8; 100000] = [0; 100000];

    str1.copy_into_slice(&mut slice[..str_len]);
    Bytes::from_slice(&env, &slice[0..str_len])
}
tupui commented 1 week ago

Oh that would be handy! I needed this like now and this snippet works great. I just added some input validation in it to check for a max length of like 64.