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.
|
|
|
|
|
|
|
|
|
|
//! Hex binary-to-text encoding
|
|
|
|
|
use std::str;
|
2014-03-08 17:11:52 -06:00
|
|
|
|
use std::slice;
|
2014-02-19 20:56:33 -06:00
|
|
|
|
use std::fmt;
|
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.
|
|
|
|
|
fn to_hex(&self) -> ~str;
|
|
|
|
|
}
|
|
|
|
|
|
2013-08-04 22:51:26 -05:00
|
|
|
|
static CHARS: &'static[u8] = bytes!("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
|
|
|
|
*/
|
|
|
|
|
fn to_hex(&self) -> ~str {
|
2014-03-08 17:11:52 -06:00
|
|
|
|
let mut v = slice::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 {
|
2013-09-05 07:17:24 -05:00
|
|
|
|
str::raw::from_utf8_owned(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-01-16 01:15:04 -06:00
|
|
|
|
fn from_hex(&self) -> Result<~[u8], FromHexError>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 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-02-19 20:56:33 -06:00
|
|
|
|
write!(f.buf, "Invalid character '{}' at position {}", ch, idx),
|
|
|
|
|
InvalidHexLength => write!(f.buf, "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.
|
|
|
|
|
*
|
2013-11-28 06:52:11 -06:00
|
|
|
|
* You can use the `from_utf8_owned` function in `std::str`
|
2013-08-05 00:25:15 -05:00
|
|
|
|
* to turn a `[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-05 00:25:15 -05:00
|
|
|
|
* use std::str;
|
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);
|
2013-08-06 12:42:06 -05:00
|
|
|
|
* let bytes = hello_str.from_hex().unwrap();
|
2013-09-25 00:16:43 -05:00
|
|
|
|
* println!("{:?}", bytes);
|
2013-12-23 10:45:01 -06:00
|
|
|
|
* let result_str = str::from_utf8_owned(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-01-16 01:15:04 -06:00
|
|
|
|
fn from_hex(&self) -> Result<~[u8], FromHexError> {
|
2013-08-04 13:42:39 -05:00
|
|
|
|
// This may be an overestimate if there is any whitespace
|
2014-03-08 17:11:52 -06:00
|
|
|
|
let mut b = slice::with_capacity(self.len() / 2);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
let mut modulus = 0;
|
|
|
|
|
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;
|
|
|
|
|
|
|
|
|
|
match byte as char {
|
|
|
|
|
'A'..'F' => buf |= byte - ('A' as u8) + 10,
|
|
|
|
|
'a'..'f' => buf |= byte - ('a' as u8) + 10,
|
|
|
|
|
'0'..'9' => buf |= byte - ('0' as u8),
|
2013-08-04 15:09:04 -05:00
|
|
|
|
' '|'\r'|'\n'|'\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 {
|
|
|
|
|
0 => Ok(b),
|
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;
|
|
|
|
|
use self::test::BenchHarness;
|
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() {
|
2013-08-05 00:25:15 -05:00
|
|
|
|
assert_eq!("foobar".as_bytes().to_hex(), ~"666f6f626172");
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_from_hex_okay() {
|
2013-08-06 12:42:06 -05:00
|
|
|
|
assert_eq!("666f6f626172".from_hex().unwrap(),
|
2013-08-04 13:42:39 -05:00
|
|
|
|
"foobar".as_bytes().to_owned());
|
2013-08-06 12:42:06 -05:00
|
|
|
|
assert_eq!("666F6F626172".from_hex().unwrap(),
|
2013-08-04 13:42:39 -05:00
|
|
|
|
"foobar".as_bytes().to_owned());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[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() {
|
2013-08-06 12:42:06 -05:00
|
|
|
|
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
|
2013-08-04 13:42:39 -05:00
|
|
|
|
"foobar".as_bytes().to_owned());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
pub fn test_to_hex_all_bytes() {
|
|
|
|
|
for i in range(0, 256) {
|
2013-09-27 22:18:50 -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() {
|
|
|
|
|
for i in range(0, 256) {
|
2013-09-27 22:18:50 -05:00
|
|
|
|
assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap(), ~[i as u8]);
|
|
|
|
|
assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap(), ~[i as u8]);
|
2013-08-04 13:42:39 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[bench]
|
|
|
|
|
pub fn bench_to_hex(bh: & mut BenchHarness) {
|
|
|
|
|
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
|
|
|
|
|
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
|
2013-11-21 21:20:48 -06:00
|
|
|
|
bh.iter(|| {
|
2013-08-05 00:25:15 -05:00
|
|
|
|
s.as_bytes().to_hex();
|
2013-11-21 21:20:48 -06:00
|
|
|
|
});
|
2013-08-04 13:42:39 -05:00
|
|
|
|
bh.bytes = s.len() as u64;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[bench]
|
|
|
|
|
pub fn bench_from_hex(bh: & mut BenchHarness) {
|
|
|
|
|
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
|
|
|
|
|
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
|
2013-08-05 00:25:15 -05:00
|
|
|
|
let b = s.as_bytes().to_hex();
|
2013-11-21 21:20:48 -06:00
|
|
|
|
bh.iter(|| {
|
2014-01-30 16:28:20 -06:00
|
|
|
|
b.from_hex().unwrap();
|
2013-11-21 21:20:48 -06:00
|
|
|
|
});
|
2013-08-04 13:42:39 -05:00
|
|
|
|
bh.bytes = b.len() as u64;
|
|
|
|
|
}
|
|
|
|
|
}
|