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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use std::{
	borrow::Borrow,
	fmt,
	ops::{Deref, DerefMut},
	str::FromStr,
};

use crate::{
	lexical::{self, LexicalFormOf},
	Datatype, ParseRdf, XsdDatatype,
};

const CHARS: [char; 16] = [
	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
];

#[derive(Debug, thiserror::Error)]
#[error("invalid hexadecimal")]
pub struct InvalidHex;

#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HexBinaryBuf(Vec<u8>);

impl HexBinaryBuf {
	pub fn new() -> Self {
		Self::default()
	}

	pub fn from_bytes(bytes: Vec<u8>) -> Self {
		Self(bytes)
	}

	pub fn decode(input: impl AsRef<[u8]>) -> Result<Self, InvalidHex> {
		let input = input.as_ref();
		let mut bytes = Vec::with_capacity(input.len() / 2);

		let mut iter = input.iter();
		while let Some(&a) = iter.next() {
			let a = decode_char(a)?;

			match iter.next() {
				Some(&b) => {
					let b = decode_char(b)?;
					bytes.push(a << 4 | b)
				}
				None => return Err(InvalidHex),
			}
		}

		Ok(Self(bytes))
	}

	pub fn into_bytes(self) -> Vec<u8> {
		self.0
	}

	pub fn as_bytes(&self) -> &[u8] {
		&self.0
	}

	pub fn as_hex_binary(&self) -> &HexBinary {
		HexBinary::new(&self.0)
	}

	pub fn as_hex_binary_mut(&mut self) -> &mut HexBinary {
		HexBinary::new_mut(&mut self.0)
	}
}

fn decode_char(c: u8) -> Result<u8, InvalidHex> {
	match c {
		b'0'..=b'9' => Ok(c - b'0'),
		b'A'..=b'F' => Ok(0xa + (c - b'A')),
		b'a'..=b'f' => Ok(0xa + (c - b'a')),
		_ => Err(InvalidHex),
	}
}

impl fmt::Display for HexBinaryBuf {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.as_hex_binary().fmt(f)
	}
}

impl From<Vec<u8>> for HexBinaryBuf {
	fn from(value: Vec<u8>) -> Self {
		HexBinaryBuf::from_bytes(value)
	}
}

impl FromStr for HexBinaryBuf {
	type Err = InvalidHex;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::decode(s)
	}
}

impl AsRef<[u8]> for HexBinaryBuf {
	fn as_ref(&self) -> &[u8] {
		self.as_bytes()
	}
}

impl AsRef<HexBinary> for HexBinaryBuf {
	fn as_ref(&self) -> &HexBinary {
		self.as_hex_binary()
	}
}

impl Borrow<HexBinary> for HexBinaryBuf {
	fn borrow(&self) -> &HexBinary {
		self.as_hex_binary()
	}
}

impl Deref for HexBinaryBuf {
	type Target = HexBinary;

	fn deref(&self) -> &Self::Target {
		self.as_hex_binary()
	}
}

impl DerefMut for HexBinaryBuf {
	fn deref_mut(&mut self) -> &mut Self::Target {
		self.as_hex_binary_mut()
	}
}

impl XsdDatatype for HexBinaryBuf {
	fn type_(&self) -> Datatype {
		Datatype::HexBinary
	}
}

impl ParseRdf for HexBinaryBuf {
	type LexicalForm = lexical::HexBinary;
}

impl LexicalFormOf<HexBinaryBuf> for lexical::HexBinary {
	type ValueError = std::convert::Infallible;

	fn try_as_value(&self) -> Result<HexBinaryBuf, Self::ValueError> {
		Ok(self.value())
	}
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HexBinary([u8]);

impl HexBinary {
	pub fn new(bytes: &[u8]) -> &Self {
		unsafe { std::mem::transmute(bytes) }
	}

	pub fn new_mut(bytes: &mut [u8]) -> &mut Self {
		unsafe { std::mem::transmute(bytes) }
	}

	pub fn chars(&self) -> Chars {
		Chars {
			pending: None,
			bytes: self.0.iter(),
		}
	}

	pub fn as_bytes(&self) -> &[u8] {
		&self.0
	}
}

impl<'a> From<&'a [u8]> for &'a HexBinary {
	fn from(value: &'a [u8]) -> Self {
		HexBinary::new(value)
	}
}

impl<'a> From<&'a mut [u8]> for &'a HexBinary {
	fn from(value: &'a mut [u8]) -> Self {
		HexBinary::new(value)
	}
}

impl<'a> From<&'a mut [u8]> for &'a mut HexBinary {
	fn from(value: &'a mut [u8]) -> Self {
		HexBinary::new_mut(value)
	}
}

impl fmt::Display for HexBinary {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		for c in self.chars() {
			c.fmt(f)?
		}

		Ok(())
	}
}

impl ToOwned for HexBinary {
	type Owned = HexBinaryBuf;

	fn to_owned(&self) -> Self::Owned {
		HexBinaryBuf::from_bytes(self.as_bytes().to_vec())
	}
}

impl XsdDatatype for HexBinary {
	fn type_(&self) -> Datatype {
		Datatype::HexBinary
	}
}

pub struct Chars<'a> {
	pending: Option<char>,
	bytes: std::slice::Iter<'a, u8>,
}

impl<'a> Iterator for Chars<'a> {
	type Item = char;

	fn next(&mut self) -> Option<Self::Item> {
		self.pending.take().or_else(|| {
			self.bytes.next().map(|v| {
				let a = v >> 4;
				let b = v & 0x0f;

				self.pending = Some(CHARS[b as usize]);
				CHARS[a as usize]
			})
		})
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	const TESTS: [(&'static [u8], &'static str); 9] = [
		(b"M", "4D"),
		(b"Ma", "4D61"),
		(b"Man", "4D616E"),
		(b"light w", "6C696768742077"),
		(b"light wo", "6C6967687420776F"),
		(b"light wor", "6C6967687420776F72"),
		(b"light work", "6C6967687420776F726B"),
		(b"light work.", "6C6967687420776F726B2E"),
		(
			b"Many hands make light work.",
			"4D616E792068616E6473206D616B65206C6967687420776F726B2E",
		),
	];

	#[test]
	fn encoding() {
		for (input, expected) in TESTS {
			let output = HexBinary::new(input).to_string();
			assert_eq!(output, expected)
		}
	}

	#[test]
	fn decoding() {
		for (expected, input) in TESTS {
			let output = HexBinaryBuf::decode(input).unwrap();
			assert_eq!(output.as_bytes(), expected)
		}
	}
}