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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std::{str, fmt};
use std::borrow::Borrow;
use rustc_serialize as serialize;
use rustc_serialize::Encodable;
#[derive(Eq, PartialEq, Clone, Ord, PartialOrd, Hash, Debug)]
pub struct ByteString(Vec<u8>);
impl ByteString {
pub fn from_str(s: &str) -> ByteString {
ByteString(s.as_bytes().to_vec())
}
pub fn from_slice(s: &[u8]) -> ByteString {
ByteString(s.to_vec())
}
pub fn from_vec(s: Vec<u8>) -> ByteString {
ByteString(s)
}
pub fn as_slice(&self) -> &[u8] {
match self {
&ByteString(ref v) => &v[..]
}
}
pub fn unwrap(self) -> Vec<u8> {
let ByteString(v) = self;
v
}
}
impl fmt::Display for ByteString {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use fmt_bytestring;
match self {
&ByteString(ref v) => fmt_bytestring(&v[..], fmt),
}
}
}
impl Encodable for ByteString {
fn encode<S: serialize::Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
let &ByteString(ref key) = self;
e.emit_str(unsafe { str::from_utf8_unchecked(&key[..]) })
}
}
impl Borrow<[u8]> for ByteString {
fn borrow(&self) -> &[u8] {
match self {
&ByteString(ref v) => v.borrow()
}
}
}
#[cfg(test)]
mod test {
use super::ByteString;
use super::super::encode;
#[test]
fn test_encoding_bytestring_with_invalid_utf8() {
let bs = ByteString::from_slice(&[45, 18, 128]);
let encoded = match encode(&bs) {
Ok(e) => e,
Err(err) => panic!("Unexpected failure: {}", err)
};
assert_eq!(vec![51, 58, 45, 18, 128], encoded);
}
}