KokaKiwi / rust-hex

A basic crate to encode values to hexadecimal representation. Originally extracted from rustc-serialize.
https://crates.io/crates/hex
Apache License 2.0
201 stars 55 forks source link

to_slice and output buffer length #41

Closed lucab closed 3 years ago

lucab commented 4 years ago

Currently, encode_to_slice documentation says:

The output buffer, has to be able to hold at least input.len() * 2 bytes, otherwise this function will return an error.

However the code checks for an exact size: https://github.com/KokaKiwi/rust-hex/blob/be0c32f9c8938ca0359bbb0d1477e31b07cb3358/src/lib.rs#L349

Which side of the doc-vs-code split should be fixed? (I'm inclined to just clarify the docs, as the resulting/current API is quite ergonomic)

Luro02 commented 4 years ago

I also prefer the current version, which does prevent (unnoticed) trailing bytes

let mut result = [0; 16];

// this would error
hex::encode_to_slice(b"hi", &mut result).unwrap();

// this should be done instead:
hex::encode_to_slice(b"hi", &mut result[..2]).unwrap();

This is especially important, when someone wants to convert the slice to an &str with str::from_utf8, which would error if there are trailing zeroes.