Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an as_bytes or to_bytes to the String type #1337

Open
kalepail opened this issue Jan 30, 2024 · 2 comments
Open

Add an as_bytes or to_bytes to the String type #1337

kalepail opened this issue Jan 30, 2024 · 2 comments
Assignees
Labels
bug Something isn't working protocol

Comments

@kalepail
Copy link

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

@anupsdf anupsdf added bug Something isn't working protocol labels Feb 15, 2024
@Xand6r
Copy link

Xand6r commented Mar 22, 2024

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
Copy link

tupui commented Jul 24, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working protocol
Projects
Development

No branches or pull requests

6 participants
@kalepail @jayz22 @tupui @Xand6r @anupsdf and others