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