1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Hex binary-to-text encoding
15 /// A trait for converting a value to hexadecimal encoding
17 /// Converts the value of `self` to a hex value, returning the owned
19 fn to_hex(&self) -> String;
22 static CHARS: &'static[u8] = bytes!("0123456789abcdef");
24 impl<'a> ToHex for &'a [u8] {
26 * Turn a vector of `u8` bytes into a hexadecimal string.
31 * extern crate serialize;
32 * use serialize::hex::ToHex;
35 * let str = [52,32].to_hex();
36 * println!("{}", str);
40 fn to_hex(&self) -> String {
41 let mut v = Vec::with_capacity(self.len() * 2);
42 for &byte in self.iter() {
43 v.push(CHARS[(byte >> 4) as uint]);
44 v.push(CHARS[(byte & 0xf) as uint]);
48 str::raw::from_utf8(v.as_slice()).to_string()
53 /// A trait for converting hexadecimal encoded values
55 /// Converts the value of `self`, interpreted as hexadecimal encoded data,
56 /// into an owned vector of bytes, returning the vector.
57 fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
60 /// Errors that can occur when decoding a hex encoded string
61 pub enum FromHexError {
62 /// The input contained a character not part of the hex format
63 InvalidHexCharacter(char, uint),
64 /// The input had an invalid length
68 impl fmt::Show for FromHexError {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 InvalidHexCharacter(ch, idx) =>
72 write!(f, "Invalid character '{}' at position {}", ch, idx),
73 InvalidHexLength => write!(f, "Invalid input length"),
78 impl<'a> FromHex for &'a str {
80 * Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
81 * to the byte values it encodes.
83 * You can use the `String::from_utf8` function in `std::string` to turn a
84 * `Vec<u8>` into a string with characters corresponding to those values.
88 * This converts a string literal to hexadecimal and back.
91 * extern crate serialize;
92 * use serialize::hex::{FromHex, ToHex};
95 * let hello_str = "Hello, World".as_bytes().to_hex();
96 * println!("{}", hello_str);
97 * let bytes = hello_str.as_slice().from_hex().unwrap();
98 * println!("{}", bytes);
99 * let result_str = String::from_utf8(bytes).unwrap();
100 * println!("{}", result_str);
104 fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
105 // This may be an overestimate if there is any whitespace
106 let mut b = Vec::with_capacity(self.len() / 2);
110 for (idx, byte) in self.bytes().enumerate() {
114 'A'..'F' => buf |= byte - ('A' as u8) + 10,
115 'a'..'f' => buf |= byte - ('a' as u8) + 10,
116 '0'..'9' => buf |= byte - ('0' as u8),
117 ' '|'\r'|'\n'|'\t' => {
121 _ => return Err(InvalidHexCharacter(self.char_at(idx), idx)),
132 0 => Ok(b.move_iter().collect()),
133 _ => Err(InvalidHexLength),
141 use self::test::Bencher;
142 use hex::{FromHex, ToHex};
145 pub fn test_to_hex() {
146 assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172".to_string());
150 pub fn test_from_hex_okay() {
151 assert_eq!("666f6f626172".from_hex().unwrap().as_slice(),
152 "foobar".as_bytes());
153 assert_eq!("666F6F626172".from_hex().unwrap().as_slice(),
154 "foobar".as_bytes());
158 pub fn test_from_hex_odd_len() {
159 assert!("666".from_hex().is_err());
160 assert!("66 6".from_hex().is_err());
164 pub fn test_from_hex_invalid_char() {
165 assert!("66y6".from_hex().is_err());
169 pub fn test_from_hex_ignores_whitespace() {
170 assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap().as_slice(),
171 "foobar".as_bytes());
175 pub fn test_to_hex_all_bytes() {
176 for i in range(0, 256) {
177 assert_eq!([i as u8].to_hex(),
178 format_strbuf!("{:02x}", i as uint));
183 pub fn test_from_hex_all_bytes() {
184 for i in range(0, 256) {
185 assert_eq!(format!("{:02x}", i as uint).as_slice()
190 assert_eq!(format!("{:02X}", i as uint).as_slice()
199 pub fn bench_to_hex(b: &mut Bencher) {
200 let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
201 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
203 s.as_bytes().to_hex();
205 b.bytes = s.len() as u64;
209 pub fn bench_from_hex(b: &mut Bencher) {
210 let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
211 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
212 let sb = s.as_bytes().to_hex();
214 sb.as_slice().from_hex().unwrap();
216 b.bytes = sb.len() as u64;