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
pub mod encodings;
use crate::{
HttpError,
data::encodings::{ Encoding, Utf8Subset, Integer }
};
use std::{
str, u128, convert::TryFrom, marker::PhantomData, num::ParseIntError, ops::Deref,
hash::{ Hash, Hasher }, fmt::{ self, Display, Formatter }
};
#[macro_export] macro_rules! data {
($str:expr) => ({
let str: &'static str = $str;
::std::convert::TryInto::try_into(str).unwrap()
});
}
#[derive(Clone, Debug)]
pub struct Data<E: Encoding> {
bytes: Vec<u8>,
_encoding: PhantomData<E>
}
impl<E: Encoding> Data<E> {
pub fn validate(bytes: &[u8]) -> bool {
E::is_valid(bytes)
}
}
impl<E: Encoding> Deref for Data<E> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.bytes
}
}
impl<E: Encoding> AsRef<[u8]> for Data<E> {
fn as_ref(&self) -> &[u8] {
self
}
}
impl<E: Encoding + Utf8Subset> AsRef<str> for Data<E> {
fn as_ref(&self) -> &str {
str::from_utf8(self).unwrap()
}
}
impl<E: Encoding + Utf8Subset> Display for Data<E> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(self.as_ref())
}
}
impl<E: Encoding> PartialEq for Data<E> {
fn eq(&self, other: &Data<E>) -> bool {
E::is_eq(self, other)
}
}
impl<E: Encoding> PartialEq<&str> for Data<E> {
fn eq(&self, other: &&str) -> bool {
E::is_eq(self, other.as_bytes())
}
}
impl<E: Encoding> PartialEq<Data<E>> for &str {
fn eq(&self, other: &Data<E>) -> bool {
E::is_eq(self.as_bytes(), other)
}
}
impl<E: Encoding> Eq for Data<E> {}
impl<E: Encoding> Hash for Data<E> {
fn hash<H: Hasher>(&self, state: &mut H) {
E::hash(self, state)
}
}
impl<E: Encoding> TryFrom<&str> for Data<E> {
type Error = HttpError;
fn try_from(source: &str) -> Result<Self, Self::Error> {
Self::try_from(source.as_bytes())
}
}
impl<E: Encoding> TryFrom<&[u8]> for Data<E> {
type Error = HttpError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
Self::try_from(bytes.to_vec())
}
}
impl<E: Encoding> TryFrom<Vec<u8>> for Data<E> {
type Error = HttpError;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
match Self::validate(&bytes) {
true => Ok(Self{ bytes, _encoding: PhantomData }),
false => Err(HttpError::InvalidEncoding)
}
}
}
impl<E: Encoding> From<Data<E>> for Vec<u8> {
fn from(data: Data<E>) -> Self {
data.bytes
}
}
impl TryFrom<Data<Integer>> for u128 {
type Error = ParseIntError;
fn try_from(data: Data<Integer>) -> Result<Self, Self::Error> {
Self::from_str_radix(data.as_ref(), 10)
}
}
impl<'a> TryFrom<Data<Integer>> for u16 {
type Error = ParseIntError;
fn try_from(data: Data<Integer>) -> Result<Self, Self::Error> {
Self::from_str_radix(data.as_ref(), 10)
}
}