Skip to content

make read_exact_into function unsafe#1

Open
kitcatier wants to merge 1 commit intoaxieinfinity:masterfrom
kitcatier:master
Open

make read_exact_into function unsafe#1
kitcatier wants to merge 1 commit intoaxieinfinity:masterfrom
kitcatier:master

Conversation

@kitcatier
Copy link

@kitcatier kitcatier commented Mar 20, 2023

pub fn read_exact_into(bytes: &[u8], hex: &mut String) {
for byte in bytes {
unsafe {
hex.as_mut_vec().push(HEX_CHARS[(byte >> 4) as usize]);
hex.as_mut_vec().push(HEX_CHARS[(byte & 0xf) as usize]);
}
}
}

Hello, it is not a good choice to mark the entire function body as unsafe, which will make the caller ignore the safety requirements that the function parameters must guarantee, the developer who calls the read_exact_into function may not notice this safety requirement.
The unsafe function called needs to ensure that the parameter must be:

  • This function is unsafe because the returned &mut Vec allows writing bytes which are not valid UTF-8. If this constraint is violated, using the original String after dropping the &mut Vec may violate memory safety, as the rest of the standard library assumes that Strings are valid UTF-8.
    https://doc.rust-lang.org/std/string/struct.String.html#method.as_mut_vec
    Marking them unsafe also means that callers must make sure they know what they're doing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant