]> git.lizzy.rs Git - rust.git/blob - src/libserialize/hex.rs
a11eb3f789875563904e24a1c57fb491f3dcce3a
[rust.git] / src / libserialize / hex.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! Hex binary-to-text encoding
14
15 pub use self::FromHexError::*;
16
17 use std::fmt;
18 use std::error;
19
20 /// A trait for converting a value to hexadecimal encoding
21 pub trait ToHex {
22     /// Converts the value of `self` to a hex value, returning the owned
23     /// string.
24     fn to_hex(&self) -> String;
25 }
26
27 static CHARS: &'static[u8] = b"0123456789abcdef";
28
29 impl ToHex for [u8] {
30     /// Turn a vector of `u8` bytes into a hexadecimal string.
31     ///
32     /// # Example
33     ///
34     /// ```rust
35     /// extern crate serialize;
36     /// use serialize::hex::ToHex;
37     ///
38     /// fn main () {
39     ///     let str = [52,32].to_hex();
40     ///     println!("{}", str);
41     /// }
42     /// ```
43     fn to_hex(&self) -> String {
44         let mut v = Vec::with_capacity(self.len() * 2);
45         for &byte in self.iter() {
46             v.push(CHARS[(byte >> 4) as uint]);
47             v.push(CHARS[(byte & 0xf) as uint]);
48         }
49
50         unsafe {
51             String::from_utf8_unchecked(v)
52         }
53     }
54 }
55
56 /// A trait for converting hexadecimal encoded values
57 pub trait FromHex {
58     /// Converts the value of `self`, interpreted as hexadecimal encoded data,
59     /// into an owned vector of bytes, returning the vector.
60     fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
61 }
62
63 /// Errors that can occur when decoding a hex encoded string
64 #[derive(Copy)]
65 pub enum FromHexError {
66     /// The input contained a character not part of the hex format
67     InvalidHexCharacter(char, uint),
68     /// The input had an invalid length
69     InvalidHexLength,
70 }
71
72 impl fmt::Show for FromHexError {
73     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74         match *self {
75             InvalidHexCharacter(ch, idx) =>
76                 write!(f, "Invalid character '{}' at position {}", ch, idx),
77             InvalidHexLength => write!(f, "Invalid input length"),
78         }
79     }
80 }
81
82 impl error::Error for FromHexError {
83     fn description(&self) -> &str {
84         match *self {
85             InvalidHexCharacter(_, _) => "invalid character",
86             InvalidHexLength => "invalid length",
87         }
88     }
89
90     fn detail(&self) -> Option<String> {
91         Some(format!("{:?}", self))
92     }
93 }
94
95
96 impl FromHex for str {
97     /// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
98     /// to the byte values it encodes.
99     ///
100     /// You can use the `String::from_utf8` function to turn a
101     /// `Vec<u8>` into a string with characters corresponding to those values.
102     ///
103     /// # Example
104     ///
105     /// This converts a string literal to hexadecimal and back.
106     ///
107     /// ```rust
108     /// extern crate serialize;
109     /// use serialize::hex::{FromHex, ToHex};
110     ///
111     /// fn main () {
112     ///     let hello_str = "Hello, World".as_bytes().to_hex();
113     ///     println!("{}", hello_str);
114     ///     let bytes = hello_str.as_slice().from_hex().unwrap();
115     ///     println!("{:?}", bytes);
116     ///     let result_str = String::from_utf8(bytes).unwrap();
117     ///     println!("{}", result_str);
118     /// }
119     /// ```
120     fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
121         // This may be an overestimate if there is any whitespace
122         let mut b = Vec::with_capacity(self.len() / 2);
123         let mut modulus = 0i;
124         let mut buf = 0u8;
125
126         for (idx, byte) in self.bytes().enumerate() {
127             buf <<= 4;
128
129             match byte {
130                 b'A'...b'F' => buf |= byte - b'A' + 10,
131                 b'a'...b'f' => buf |= byte - b'a' + 10,
132                 b'0'...b'9' => buf |= byte - b'0',
133                 b' '|b'\r'|b'\n'|b'\t' => {
134                     buf >>= 4;
135                     continue
136                 }
137                 _ => return Err(InvalidHexCharacter(self.char_at(idx), idx)),
138             }
139
140             modulus += 1;
141             if modulus == 2 {
142                 modulus = 0;
143                 b.push(buf);
144             }
145         }
146
147         match modulus {
148             0 => Ok(b.into_iter().collect()),
149             _ => Err(InvalidHexLength),
150         }
151     }
152 }
153
154 #[cfg(test)]
155 mod tests {
156     extern crate test;
157     use self::test::Bencher;
158     use hex::{FromHex, ToHex};
159
160     #[test]
161     pub fn test_to_hex() {
162         assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
163     }
164
165     #[test]
166     pub fn test_from_hex_okay() {
167         assert_eq!("666f6f626172".from_hex().unwrap(),
168                    b"foobar");
169         assert_eq!("666F6F626172".from_hex().unwrap(),
170                    b"foobar");
171     }
172
173     #[test]
174     pub fn test_from_hex_odd_len() {
175         assert!("666".from_hex().is_err());
176         assert!("66 6".from_hex().is_err());
177     }
178
179     #[test]
180     pub fn test_from_hex_invalid_char() {
181         assert!("66y6".from_hex().is_err());
182     }
183
184     #[test]
185     pub fn test_from_hex_ignores_whitespace() {
186         assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
187                    b"foobar");
188     }
189
190     #[test]
191     pub fn test_to_hex_all_bytes() {
192         for i in range(0u, 256) {
193             assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint));
194         }
195     }
196
197     #[test]
198     pub fn test_from_hex_all_bytes() {
199         for i in range(0u, 256) {
200             let ii: &[u8] = &[i as u8];
201             assert_eq!(format!("{:02x}", i as uint).from_hex()
202                                                    .unwrap(),
203                        ii);
204             assert_eq!(format!("{:02X}", i as uint).from_hex()
205                                                    .unwrap(),
206                        ii);
207         }
208     }
209
210     #[bench]
211     pub fn bench_to_hex(b: &mut Bencher) {
212         let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
213                  ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
214         b.iter(|| {
215             s.as_bytes().to_hex();
216         });
217         b.bytes = s.len() as u64;
218     }
219
220     #[bench]
221     pub fn bench_from_hex(b: &mut Bencher) {
222         let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
223                  ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
224         let sb = s.as_bytes().to_hex();
225         b.iter(|| {
226             sb.from_hex().unwrap();
227         });
228         b.bytes = sb.len() as u64;
229     }
230 }