diff --git a/Cargo.toml b/Cargo.toml index b25d8dd..7a6c55d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hex" -version = "0.4.3" +version = "0.5.0" authors = ["KokaKiwi "] description = "Encoding and decoding data into/from hexadecimal representation." license = "MIT OR Apache-2.0" diff --git a/src/lib.rs b/src/lib.rs index bc6a69d..7297e71 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,10 +19,7 @@ //! # let mut output = [0; 0x18]; //! # //! # #[cfg(not(feature = "alloc"))] -//! # hex::encode_to_slice(b"Hello world!", &mut output).unwrap(); -//! # -//! # #[cfg(not(feature = "alloc"))] -//! # let hex_string = ::core::str::from_utf8(&output).unwrap(); +//! # let hex_string = hex::encode_to_slice(b"Hello world!", &mut output).unwrap(); //! # //! # #[cfg(feature = "alloc")] //! let hex_string = hex::encode("Hello world!"); @@ -359,7 +356,8 @@ const fn byte2hex(byte: u8, table: &[u8; 16]) -> (u8, u8) { /// # fn main() -> Result<(), FromHexError> { /// let mut bytes = [0u8; 4 * 2]; /// -/// hex::encode_to_slice(b"kiwi", &mut bytes)?; +/// let hex_str = hex::encode_to_slice(b"kiwi", &mut bytes)?; +/// assert_eq!(hex_str, "6b697769"); /// assert_eq!(&bytes, b"6b697769"); /// # Ok(()) /// # } @@ -375,12 +373,16 @@ const fn byte2hex(byte: u8, table: &[u8; 16]) -> (u8, u8) { /// assert_eq!(hex::encode_to_slice(b"kiwi", &mut bytes), Err(FromHexError::InvalidStringLength)); /// /// // you can do this instead: -/// hex::encode_to_slice(b"kiwi", &mut bytes[..4 * 2])?; +/// let hex_str = hex::encode_to_slice(b"kiwi", &mut bytes[..4 * 2])?; +/// assert_eq!(hex_str, "6b697769"); /// assert_eq!(&bytes, b"6b697769\0\0"); /// # Ok(()) /// # } /// ``` -pub fn encode_to_slice>(input: T, output: &mut [u8]) -> Result<(), FromHexError> { +pub fn encode_to_slice>( + input: T, + output: &mut [u8], +) -> Result<&mut str, FromHexError> { if input.as_ref().len() * 2 != output.len() { return Err(FromHexError::InvalidStringLength); } @@ -395,7 +397,12 @@ pub fn encode_to_slice>(input: T, output: &mut [u8]) -> Result<() output[j] = low; } - Ok(()) + if cfg!(debug_assertions) { + Ok(core::str::from_utf8_mut(output).unwrap()) + } else { + // Saftey: We just wrote valid utf8 hex string into the output + Ok(unsafe { core::str::from_utf8_unchecked_mut(output) }) + } } #[cfg(test)] @@ -418,11 +425,13 @@ mod test { #[test] fn test_encode_to_slice() { let mut output_1 = [0; 4 * 2]; - encode_to_slice(b"kiwi", &mut output_1).unwrap(); + let encoded = encode_to_slice(b"kiwi", &mut output_1).unwrap(); + assert_eq!(encoded, "6b697769"); assert_eq!(&output_1, b"6b697769"); let mut output_2 = [0; 5 * 2]; - encode_to_slice(b"kiwis", &mut output_2).unwrap(); + let encoded = encode_to_slice(b"kiwis", &mut output_2).unwrap(); + assert_eq!(encoded, "6b69776973"); assert_eq!(&output_2, b"6b69776973"); let mut output_3 = [0; 100];