summary refs log tree commit diff
path: root/src/libserialize/hex/tests.rs
blob: 471912c11d06fd69de0f204bc1acbd8bcf5f3438 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
extern crate test;
use test::Bencher;
use crate::hex::{FromHex, ToHex};

#[test]
pub fn test_to_hex() {
    assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}

#[test]
pub fn test_from_hex_okay() {
    assert_eq!("666f6f626172".from_hex().unwrap(),
               b"foobar");
    assert_eq!("666F6F626172".from_hex().unwrap(),
               b"foobar");
}

#[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() {
    assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
               b"foobar");
}

#[test]
pub fn test_to_hex_all_bytes() {
    for i in 0..256 {
        assert_eq!([i as u8].to_hex(), format!("{:02x}", i as usize));
    }
}

#[test]
pub fn test_from_hex_all_bytes() {
    for i in 0..256 {
        let ii: &[u8] = &[i as u8];
        assert_eq!(format!("{:02x}", i as usize).from_hex()
                                               .unwrap(),
                   ii);
        assert_eq!(format!("{:02X}", i as usize).from_hex()
                                               .unwrap(),
                   ii);
    }
}

#[bench]
pub fn bench_to_hex(b: &mut Bencher) {
    let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
             ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
    b.iter(|| {
        s.as_bytes().to_hex();
    });
    b.bytes = s.len() as u64;
}

#[bench]
pub fn bench_from_hex(b: &mut Bencher) {
    let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
             ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
    let sb = s.as_bytes().to_hex();
    b.iter(|| {
        sb.from_hex().unwrap();
    });
    b.bytes = sb.len() as u64;
}