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

make read_exact_into function unsafe #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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