1 //! Hex binary-to-text encoding
3 pub use self::FromHexError::*;
8 /// A trait for converting a value to hexadecimal encoding
10 /// Converts the value of `self` to a hex value, returning the owned
12 fn to_hex(&self) -> String;
15 const CHARS: &[u8] = b"0123456789abcdef";
18 /// Turn a vector of `u8` bytes into a hexadecimal string.
23 /// #![feature(rustc_private)]
25 /// extern crate serialize;
26 /// use serialize::hex::ToHex;
29 /// let str = [52,32].to_hex();
30 /// println!("{}", str);
33 fn to_hex(&self) -> String {
34 let mut v = Vec::with_capacity(self.len() * 2);
36 v.push(CHARS[(byte >> 4) as usize]);
37 v.push(CHARS[(byte & 0xf) as usize]);
41 String::from_utf8_unchecked(v)
46 /// A trait for converting hexadecimal encoded values
48 /// Converts the value of `self`, interpreted as hexadecimal encoded data,
49 /// into an owned vector of bytes, returning the vector.
50 fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
53 /// Errors that can occur when decoding a hex encoded string
54 #[derive(Copy, Clone, Debug)]
55 pub enum FromHexError {
56 /// The input contained a character not part of the hex format
57 InvalidHexCharacter(char, usize),
58 /// The input had an invalid length
62 impl fmt::Display for FromHexError {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 InvalidHexCharacter(ch, idx) =>
66 write!(f, "Invalid character '{}' at position {}", ch, idx),
67 InvalidHexLength => write!(f, "Invalid input length"),
72 impl error::Error for FromHexError {
73 fn description(&self) -> &str {
75 InvalidHexCharacter(..) => "invalid character",
76 InvalidHexLength => "invalid length",
82 impl FromHex for str {
83 /// Converts any hexadecimal encoded string (literal, `@`, `&`, or `~`)
84 /// to the byte values it encodes.
86 /// You can use the `String::from_utf8` function to turn a
87 /// `Vec<u8>` into a string with characters corresponding to those values.
91 /// This converts a string literal to hexadecimal and back.
94 /// #![feature(rustc_private)]
96 /// extern crate serialize;
97 /// use serialize::hex::{FromHex, ToHex};
100 /// let hello_str = "Hello, World".as_bytes().to_hex();
101 /// println!("{}", hello_str);
102 /// let bytes = hello_str.from_hex().unwrap();
103 /// println!("{:?}", bytes);
104 /// let result_str = String::from_utf8(bytes).unwrap();
105 /// println!("{}", result_str);
108 fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
109 // This may be an overestimate if there is any whitespace
110 let mut b = Vec::with_capacity(self.len() / 2);
114 for (idx, byte) in self.bytes().enumerate() {
118 b'A'..=b'F' => buf |= byte - b'A' + 10,
119 b'a'..=b'f' => buf |= byte - b'a' + 10,
120 b'0'..=b'9' => buf |= byte - b'0',
121 b' '|b'\r'|b'\n'|b'\t' => {
126 let ch = self[idx..].chars().next().unwrap();
127 return Err(InvalidHexCharacter(ch, idx))
140 _ => Err(InvalidHexLength),
149 use crate::hex::{FromHex, ToHex};
152 pub fn test_to_hex() {
153 assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
157 pub fn test_from_hex_okay() {
158 assert_eq!("666f6f626172".from_hex().unwrap(),
160 assert_eq!("666F6F626172".from_hex().unwrap(),
165 pub fn test_from_hex_odd_len() {
166 assert!("666".from_hex().is_err());
167 assert!("66 6".from_hex().is_err());
171 pub fn test_from_hex_invalid_char() {
172 assert!("66y6".from_hex().is_err());
176 pub fn test_from_hex_ignores_whitespace() {
177 assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
182 pub fn test_to_hex_all_bytes() {
184 assert_eq!([i as u8].to_hex(), format!("{:02x}", i as usize));
189 pub fn test_from_hex_all_bytes() {
191 let ii: &[u8] = &[i as u8];
192 assert_eq!(format!("{:02x}", i as usize).from_hex()
195 assert_eq!(format!("{:02X}", i as usize).from_hex()
202 pub fn bench_to_hex(b: &mut Bencher) {
203 let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
204 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
206 s.as_bytes().to_hex();
208 b.bytes = s.len() as u64;
212 pub fn bench_from_hex(b: &mut Bencher) {
213 let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
214 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
215 let sb = s.as_bytes().to_hex();
217 sb.from_hex().unwrap();
219 b.bytes = sb.len() as u64;