2014-01-30 12:29:35 -06:00
|
|
|
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
2013-08-04 13:42:39 -05:00
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
|
//
|
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
|
// except according to those terms.
|
2014-07-14 22:46:04 -05:00
|
|
|
|
//
|
|
|
|
|
// ignore-lexer-test FIXME #15679
|
2013-08-04 13:42:39 -05:00
|
|
|
|
|
|
|
|
|
//! Hex binary-to-text encoding
|
2014-02-19 20:56:33 -06:00
|
|
|
|
use std::fmt;
|
2014-07-19 05:23:47 -05:00
|
|
|
|
use std::string;
|
2013-08-04 13:42:39 -05:00
|
|
|
|
|
|
|
|
|
/// A trait for converting a value to hexadecimal encoding
|
|
|
|
|
pub trait ToHex {
|
|
|
|
|
/// Converts the value of `self` to a hex value, returning the owned
|
|
|
|
|
/// string.
|
2014-05-22 18:57:53 -05:00
|
|
|
|
fn to_hex(&self) -> String;
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
|
static CHARS: &'static[u8] = b"0123456789abcdef";
|
2013-08-04 13:42:39 -05:00
|
|
|
|
|
2013-12-10 01:16:18 -06:00
|
|
|
|
impl<'a> ToHex for &'a [u8] {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
/**
|
|
|
|
|
* Turn a vector of `u8` bytes into a hexadecimal string.
|
|
|
|
|
*
|
|
|
|
|
* # Example
|
|
|
|
|
*
|
2013-09-23 19:20:36 -05:00
|
|
|
|
* ```rust
|
2014-02-14 12:10:06 -06:00
|
|
|
|
* extern crate serialize;
|
2014-02-11 18:40:52 -06:00
|
|
|
|
* use serialize::hex::ToHex;
|
2013-08-04 13:42:39 -05:00
|
|
|
|
*
|
|
|
|
|
* fn main () {
|
|
|
|
|
* let str = [52,32].to_hex();
|
2013-09-25 00:16:43 -05:00
|
|
|
|
* println!("{}", str);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
* }
|
2013-09-23 19:20:36 -05:00
|
|
|
|
* ```
|
2013-08-04 13:42:39 -05:00
|
|
|
|
*/
|
2014-05-22 18:57:53 -05:00
|
|
|
|
fn to_hex(&self) -> String {
|
2014-04-17 17:59:07 -05:00
|
|
|
|
let mut v = Vec::with_capacity(self.len() * 2);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
for &byte in self.iter() {
|
2014-04-01 22:39:26 -05:00
|
|
|
|
v.push(CHARS[(byte >> 4) as uint]);
|
|
|
|
|
v.push(CHARS[(byte & 0xf) as uint]);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
2013-08-04 22:51:26 -05:00
|
|
|
|
unsafe {
|
2014-07-19 05:23:47 -05:00
|
|
|
|
string::raw::from_utf8(v)
|
2013-08-04 22:51:26 -05:00
|
|
|
|
}
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A trait for converting hexadecimal encoded values
|
|
|
|
|
pub trait FromHex {
|
2013-08-04 15:09:04 -05:00
|
|
|
|
/// Converts the value of `self`, interpreted as hexadecimal encoded data,
|
|
|
|
|
/// into an owned vector of bytes, returning the vector.
|
2014-05-04 01:34:26 -05:00
|
|
|
|
fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
|
2014-01-16 01:15:04 -06:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Errors that can occur when decoding a hex encoded string
|
|
|
|
|
pub enum FromHexError {
|
|
|
|
|
/// The input contained a character not part of the hex format
|
|
|
|
|
InvalidHexCharacter(char, uint),
|
2014-01-30 12:29:35 -06:00
|
|
|
|
/// The input had an invalid length
|
2014-01-16 01:15:04 -06:00
|
|
|
|
InvalidHexLength,
|
|
|
|
|
}
|
|
|
|
|
|
2014-02-19 20:56:33 -06:00
|
|
|
|
impl fmt::Show for FromHexError {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2014-01-16 01:15:04 -06:00
|
|
|
|
match *self {
|
|
|
|
|
InvalidHexCharacter(ch, idx) =>
|
2014-05-10 16:05:06 -05:00
|
|
|
|
write!(f, "Invalid character '{}' at position {}", ch, idx),
|
|
|
|
|
InvalidHexLength => write!(f, "Invalid input length"),
|
2014-01-16 01:15:04 -06:00
|
|
|
|
}
|
|
|
|
|
}
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
2013-12-10 01:16:18 -06:00
|
|
|
|
impl<'a> FromHex for &'a str {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
/**
|
2013-08-05 00:25:15 -05:00
|
|
|
|
* Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
|
|
|
|
|
* to the byte values it encodes.
|
|
|
|
|
*
|
2014-05-22 18:57:53 -05:00
|
|
|
|
* You can use the `String::from_utf8` function in `std::string` to turn a
|
2014-05-14 18:55:24 -05:00
|
|
|
|
* `Vec<u8>` into a string with characters corresponding to those values.
|
2013-08-04 13:42:39 -05:00
|
|
|
|
*
|
|
|
|
|
* # Example
|
|
|
|
|
*
|
2013-08-05 00:25:15 -05:00
|
|
|
|
* This converts a string literal to hexadecimal and back.
|
|
|
|
|
*
|
2013-09-23 19:20:36 -05:00
|
|
|
|
* ```rust
|
2014-02-14 12:10:06 -06:00
|
|
|
|
* extern crate serialize;
|
2014-02-11 18:40:52 -06:00
|
|
|
|
* use serialize::hex::{FromHex, ToHex};
|
2013-08-04 13:42:39 -05:00
|
|
|
|
*
|
|
|
|
|
* fn main () {
|
2013-12-22 15:31:37 -06:00
|
|
|
|
* let hello_str = "Hello, World".as_bytes().to_hex();
|
2013-09-25 00:16:43 -05:00
|
|
|
|
* println!("{}", hello_str);
|
2014-05-14 23:16:44 -05:00
|
|
|
|
* let bytes = hello_str.as_slice().from_hex().unwrap();
|
2014-05-22 13:28:01 -05:00
|
|
|
|
* println!("{}", bytes);
|
2014-05-22 18:57:53 -05:00
|
|
|
|
* let result_str = String::from_utf8(bytes).unwrap();
|
2013-09-25 00:16:43 -05:00
|
|
|
|
* println!("{}", result_str);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
* }
|
2013-09-23 19:20:36 -05:00
|
|
|
|
* ```
|
2013-08-04 13:42:39 -05:00
|
|
|
|
*/
|
2014-05-04 01:34:26 -05:00
|
|
|
|
fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
// This may be an overestimate if there is any whitespace
|
2014-04-17 17:59:07 -05:00
|
|
|
|
let mut b = Vec::with_capacity(self.len() / 2);
|
2014-06-27 14:30:25 -05:00
|
|
|
|
let mut modulus = 0i;
|
2013-08-04 13:42:39 -05:00
|
|
|
|
let mut buf = 0u8;
|
|
|
|
|
|
2013-11-23 04:18:51 -06:00
|
|
|
|
for (idx, byte) in self.bytes().enumerate() {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
buf <<= 4;
|
|
|
|
|
|
2014-08-06 11:23:21 -05:00
|
|
|
|
match byte {
|
|
|
|
|
b'A'..b'F' => buf |= byte - b'A' + 10,
|
|
|
|
|
b'a'..b'f' => buf |= byte - b'a' + 10,
|
|
|
|
|
b'0'..b'9' => buf |= byte - b'0',
|
|
|
|
|
b' '|b'\r'|b'\n'|b'\t' => {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
buf >>= 4;
|
2013-10-01 16:31:03 -05:00
|
|
|
|
continue
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
2014-01-16 01:15:04 -06:00
|
|
|
|
_ => return Err(InvalidHexCharacter(self.char_at(idx), idx)),
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
modulus += 1;
|
|
|
|
|
if modulus == 2 {
|
|
|
|
|
modulus = 0;
|
|
|
|
|
b.push(buf);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match modulus {
|
2014-04-17 17:59:07 -05:00
|
|
|
|
0 => Ok(b.move_iter().collect()),
|
2014-01-16 01:15:04 -06:00
|
|
|
|
_ => Err(InvalidHexLength),
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests {
|
2014-02-13 19:49:11 -06:00
|
|
|
|
extern crate test;
|
2014-03-31 20:16:35 -05:00
|
|
|
|
use self::test::Bencher;
|
2014-02-11 18:40:52 -06:00
|
|
|
|
use hex::{FromHex, ToHex};
|
2013-08-04 13:42:39 -05:00
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_to_hex() {
|
2014-05-25 05:17:19 -05:00
|
|
|
|
assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172".to_string());
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_from_hex_okay() {
|
2014-05-04 01:34:26 -05:00
|
|
|
|
assert_eq!("666f6f626172".from_hex().unwrap().as_slice(),
|
|
|
|
|
"foobar".as_bytes());
|
|
|
|
|
assert_eq!("666F6F626172".from_hex().unwrap().as_slice(),
|
|
|
|
|
"foobar".as_bytes());
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_from_hex_odd_len() {
|
|
|
|
|
assert!("666".from_hex().is_err());
|
|
|
|
|
assert!("66 6".from_hex().is_err());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_from_hex_invalid_char() {
|
|
|
|
|
assert!("66y6".from_hex().is_err());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_from_hex_ignores_whitespace() {
|
2014-05-04 01:34:26 -05:00
|
|
|
|
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap().as_slice(),
|
|
|
|
|
"foobar".as_bytes());
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_to_hex_all_bytes() {
|
2014-04-21 16:58:52 -05:00
|
|
|
|
for i in range(0u, 256) {
|
2014-05-27 22:44:58 -05:00
|
|
|
|
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint));
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_from_hex_all_bytes() {
|
2014-04-21 16:58:52 -05:00
|
|
|
|
for i in range(0u, 256) {
|
2014-08-04 07:19:02 -05:00
|
|
|
|
let ii: &[u8] = &[i as u8];
|
2014-05-20 01:19:56 -05:00
|
|
|
|
assert_eq!(format!("{:02x}", i as uint).as_slice()
|
|
|
|
|
.from_hex()
|
|
|
|
|
.unwrap()
|
|
|
|
|
.as_slice(),
|
2014-08-04 07:19:02 -05:00
|
|
|
|
ii);
|
2014-05-20 01:19:56 -05:00
|
|
|
|
assert_eq!(format!("{:02X}", i as uint).as_slice()
|
|
|
|
|
.from_hex()
|
|
|
|
|
.unwrap()
|
|
|
|
|
.as_slice(),
|
2014-08-04 07:19:02 -05:00
|
|
|
|
ii);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[bench]
|
2014-03-31 20:16:35 -05:00
|
|
|
|
pub fn bench_to_hex(b: &mut Bencher) {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
|
|
|
|
|
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
|
2014-03-31 20:16:35 -05:00
|
|
|
|
b.iter(|| {
|
2013-08-05 00:25:15 -05:00
|
|
|
|
s.as_bytes().to_hex();
|
2013-11-21 21:20:48 -06:00
|
|
|
|
});
|
2014-03-31 20:16:35 -05:00
|
|
|
|
b.bytes = s.len() as u64;
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[bench]
|
2014-03-31 20:16:35 -05:00
|
|
|
|
pub fn bench_from_hex(b: &mut Bencher) {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
|
|
|
|
|
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
|
2014-03-31 20:16:35 -05:00
|
|
|
|
let sb = s.as_bytes().to_hex();
|
|
|
|
|
b.iter(|| {
|
2014-05-14 23:16:44 -05:00
|
|
|
|
sb.as_slice().from_hex().unwrap();
|
2013-11-21 21:20:48 -06:00
|
|
|
|
});
|
2014-03-31 20:16:35 -05:00
|
|
|
|
b.bytes = sb.len() as u64;
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
}
|