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
extern crate regex;

use self::regex::Regex;
use super::{Validated, ValidatedWrapper};

use std::error::Error;
use std::fmt::{self, Display, Debug, Formatter};
use std::str::Utf8Error;
use std::ops::Deref;

lazy_static! {
    static ref BASE64_RE: Regex = {
        Regex::new("^([A-Za-z0-9+/]{4})*(([A-Za-z0-9+/]{4})|([A-Za-z0-9+/]{3}=)|([A-Za-z0-9+/]{2}==))$").unwrap()
    };
}

#[derive(Debug, PartialEq, Clone)]
pub enum Base64Error {
    IncorrectFormat,
    UTF8Error(Utf8Error),
}

impl Display for Base64Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl Error for Base64Error {}

pub type Base64Result = Result<Base64, Base64Error>;

#[derive(Debug, PartialEq)]
pub struct Base64Validator {}

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Base64 {
    base64: String,
}

impl Base64 {
    pub fn get_base64(&self) -> &str {
        &self.base64
    }

    pub fn into_string(self) -> String {
        self.base64
    }

    pub unsafe fn from_string_unchecked(base64: String) -> Base64 {
        Base64 {
            base64
        }
    }
}

impl Deref for Base64 {
    type Target = str;

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

impl Validated for Base64 {}

impl Debug for Base64 {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_fmt(format_args!("Base64({})", self.base64))?;
        Ok(())
    }
}

impl Display for Base64 {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.base64)?;
        Ok(())
    }
}

impl Base64Validator {
    pub fn is_base64(&self, base64: &str) -> bool {
        self.parse_inner(base64).is_ok()
    }

    pub fn parse_string(&self, base64: String) -> Base64Result {
        let mut base64_inner = self.parse_inner(&base64)?;

        base64_inner.base64 = base64;

        Ok(base64_inner)
    }

    pub fn parse_str(&self, base64: &str) -> Base64Result {
        let mut base64_inner = self.parse_inner(base64)?;

        base64_inner.base64.push_str(base64);

        Ok(base64_inner)
    }

    fn parse_inner(&self, base64: &str) -> Base64Result {
        if BASE64_RE.is_match(base64) {
            Ok(Base64 {
                base64: String::new(),
            })
        } else {
            Err(Base64Error::IncorrectFormat)
        }
    }
}

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

    #[test]
    fn test_base64_methods() {
        let base64 = "IHRlc3QgbWVzc2FnZQoK".to_string();

        let bv = Base64Validator {};

        let base64 = bv.parse_string(base64).unwrap();

        assert_eq!("IHRlc3QgbWVzc2FnZQoK", base64.get_base64());
    }

    #[test]
    fn test_base64_lv1() {
        let base64 = "IHRlc3QgbWVzc2FnZQoK".to_string();

        let bv = Base64Validator {};

        bv.parse_string(base64).unwrap();
    }
}

// Base64's wrapper struct is itself
impl ValidatedWrapper for Base64 {
    type Error = Base64Error;

    fn from_string(base64: String) -> Result<Self, Self::Error> {
        Base64::from_string(base64)
    }

    fn from_str(base64: &str) -> Result<Self, Self::Error> {
        Base64::from_str(base64)
    }
}

impl Base64 {
    pub fn from_string(base64: String) -> Result<Self, Base64Error> {
        Base64::create_validator().parse_string(base64)
    }

    pub fn from_str(base64: &str) -> Result<Self, Base64Error> {
        Base64::create_validator().parse_str(base64)
    }

    fn create_validator() -> Base64Validator {
        Base64Validator {}
    }
}

#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromFormValue<'a> for Base64 {
    type Error = Base64Error;

    fn from_form_value(form_value: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        Base64::from_string(form_value.url_decode().map_err(|err| Base64Error::UTF8Error(err))?)
    }
}

#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromParam<'a> for Base64 {
    type Error = Base64Error;

    fn from_param(param: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        Base64::from_string(param.url_decode().map_err(|err| Base64Error::UTF8Error(err))?)
    }
}

#[cfg(feature = "serdely")]
struct StringVisitor;

#[cfg(feature = "serdely")]
impl<'de> ::serde::de::Visitor<'de> for StringVisitor {
    type Value = Base64;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a Base64 string")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: ::serde::de::Error {
        Base64::from_str(v).map_err(|err| {
            E::custom(err.to_string())
        })
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: ::serde::de::Error {
        Base64::from_string(v).map_err(|err| {
            E::custom(err.to_string())
        })
    }
}

#[cfg(feature = "serdely")]
impl<'de> ::serde::Deserialize<'de> for Base64 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de> {
        deserializer.deserialize_string(StringVisitor)
    }
}

#[cfg(feature = "serdely")]
impl ::serde::Serialize for Base64 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
        serializer.serialize_str(&self.base64)
    }
}