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
#[cfg(any(test, feature = "base64"))]
#[macro_export]
macro_rules! impl_base64 {
($t:ident) => {
impl $t {
#[cfg(all(feature = "alloc", not(feature = "std")))]
pub fn encode_base64(&self) -> ::alloc::string::String {
::base64::encode(&self.to_bytes()[..])
}
#[cfg(all(feature = "std"))]
pub fn encode_base64(&self) -> ::std::string::String {
::base64::encode(&self.to_bytes()[..])
}
pub fn decode_base64(s: &str) -> Result<Self, TokenError> {
let bytes =
::base64::decode(s).or(Err(TokenError(InternalError::DecodingError)))?;
$t::from_bytes(&bytes)
}
}
};
}
#[cfg(feature = "serde")]
#[macro_export]
macro_rules! impl_serde {
($t:ident) => {
impl ::serde::Serialize for $t {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
serializer.serialize_bytes(&self.to_bytes())
}
}
impl<'d> ::serde::Deserialize<'d> for $t {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'d>,
{
use core::fmt::Debug;
struct TVisitor;
impl<'d> ::serde::de::Visitor<'d> for TVisitor {
type Value = $t;
fn expecting(
&self,
formatter: &mut ::core::fmt::Formatter,
) -> ::core::fmt::Result {
$t::bytes_length_error().fmt(formatter)
}
fn visit_bytes<E>(self, bytes: &[u8]) -> Result<$t, E>
where
E: ::serde::de::Error,
{
$t::from_bytes(bytes)
.or(Err(::serde::de::Error::invalid_length(bytes.len(), &self)))
}
}
deserializer.deserialize_bytes(TVisitor)
}
}
};
}