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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use core::fmt;
use enum_map::Enum;
use memchr::memmem;
use std::path::PathBuf;

#[derive(PartialEq, Debug, Clone, Copy, Enum)]
pub enum Method {
    GET,
    POST,
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Version {
    V0_9,
    V1_0,
    V1_1,
    V2_0,
}

/*
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum StatusCode {
    Continue = 100,
    OK = 200,
    MultipleChoices = 300,
    MovedPermanetly = 301,
    Found = 302,
    SeeOther = 303,
    TempRedirect = 307,
    PermanentRedirect = 308,
    ErrBadRequest = 400,
    ErrUnathorized = 401,
    ErrForbidden = 403,
    ErrNotFound = 404,
    ErrInternalServer = 500,
}
*/
pub type StatusCode = http::StatusCode;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MimeType {
    HTML,
    PlainText,
    JavaScript,
    Json,
    CSS,
    SVG,
    Icon,
    Binary,
    JPEG,
}

impl TryFrom<&[u8]> for Method {
    type Error = String;
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        match value {
            b"GET" => Ok(Method::GET),
            b"POST" => Ok(Method::POST),
            _ => Err("Invalid Method".to_owned()),
        }
    }
}

impl TryFrom<&[u8]> for Version {
    type Error = String;
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        match value {
            b"HTTP/1.0" => Ok(Version::V1_0),
            b"HTTP/1.1" => Ok(Version::V1_1),
            b"HTTP/2.2" => Ok(Version::V2_0),
            _ => Err("invalid version".to_owned()),
        }
    }
}

/// HTTP headers are simple key value pairs both strings
#[derive(Debug, PartialEq, Clone)]
pub struct Header {
    pub key: String,
    pub value: String,
}

pub trait IntoHeader {
    fn into_header(self) -> Header;
}

impl IntoHeader for Header {
    fn into_header(self) -> Header {
        self
    }
}

impl IntoHeader for &Header {
    fn into_header(self) -> Header {
        self.clone()
    }
}

impl IntoHeader for (&str, &str) {
    fn into_header(self) -> Header {
        let (key, value) = self;
        Header::new(key, value)
    }
}

impl IntoHeader for (&str, &String) {
    fn into_header(self) -> Header {
        let (key, value) = self;
        Header::new(key, value)
    }
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::GET => write!(f, "GET"),
            Self::POST => write!(f, "POST"),
        }
    }
}
impl From<&MimeType> for String {
    fn from(mime: &MimeType) -> String {
        let media_type = mime.media_type();
        let charset = mime.charset();
        let boundary = mime.boundary();
        if let (Some(boundary), Some(charset)) = (boundary, charset) {
            format!("{}; charset={}; boundary={}", media_type, charset, boundary)
        } else if let (None, Some(charset)) = (boundary, charset) {
            format!("{}; charset={}", media_type, charset)
        } else {
            format!("{};", media_type)
        }
    }
}

impl From<MimeType> for String {
    fn from(mime: MimeType) -> String {
        String::from(&mime)
    }
}

impl From<PathBuf> for MimeType {
    fn from(value: PathBuf) -> Self {
        if let Some(ext) = value.extension() {
            return MimeType::from_extension(&ext.to_string_lossy());
        } else {
            MimeType::PlainText
        }
    }
}

impl MimeType {
    pub fn media_type(&self) -> &str {
        match self {
            Self::PlainText => "text/plain",
            Self::HTML => "text/html",
            Self::JavaScript => "text/javascript",
            Self::Json => "application/json",
            Self::CSS => "text/css",
            Self::SVG => "image/svg+xml",
            Self::Icon => "image/vnd.microsoft.icon",
            Self::Binary => "application/octet-stream",
            Self::JPEG => "image/jpeg",
        }
    }

    pub fn charset(&self) -> Option<&str> {
        match self {
            Self::SVG | Self::Icon | Self::Binary | Self::JPEG => None,
            _ => Some("utf-8"),
        }
    }

    pub fn boundary(&self) -> Option<&str> {
        None
    }

    pub fn from_extension(extension: &str) -> Self {
        match extension {
            "json" => Self::Json,
            "js" => Self::JavaScript,
            "css" => Self::CSS,
            "svg" => Self::SVG,
            "ico" => Self::Icon,
            "bin" => Self::Binary,
            "html" => Self::HTML,
            "jpeg" | "jpg" => Self::JPEG,
            _ => Self::PlainText,
        }
    }
}

impl TryFrom<String> for Header {
    type Error = &'static str;
    fn try_from(string: String) -> Result<Self, Self::Error> {
        let split: Vec<&str> = string.split(": ").collect();
        match split.len().cmp(&2) {
            std::cmp::Ordering::Equal => {
                let key = split[0].to_lowercase();
                let value = split[1].to_string();
                Ok(Self { key, value })
            }
            std::cmp::Ordering::Greater => Err("Too many ': '"),
            std::cmp::Ordering::Less => Err("Invalid Key Value Pair"),
        }
    }
}

impl TryFrom<&String> for Header {
    type Error = &'static str;
    fn try_from(string: &String) -> Result<Self, Self::Error> {
        let split: Vec<&str> = string.split(": ").collect();
        match split.len().cmp(&2) {
            std::cmp::Ordering::Equal => {
                let key = split[0].to_lowercase();
                let value = split[1].to_string();
                Ok(Self { key, value })
            }
            std::cmp::Ordering::Greater => Err("Too many ': '"),
            std::cmp::Ordering::Less => Err("Invalid Key Value Pair"),
        }
    }
}

impl TryFrom<&str> for Header {
    type Error = &'static str;
    fn try_from(string: &str) -> Result<Self, Self::Error> {
        let split: Vec<&str> = string.split(": ").collect();
        match split.len().cmp(&2) {
            std::cmp::Ordering::Equal => {
                let key = split[0].to_lowercase();
                let value = split[1].to_string();
                Ok(Self { key, value })
            }
            std::cmp::Ordering::Greater => Err("Too many ': '"),
            std::cmp::Ordering::Less => Err("Invalid Key Value Pair"),
        }
    }
}

impl TryFrom<&[u8]> for Header {
    type Error = &'static str;
    fn try_from(h_str: &[u8]) -> Result<Self, Self::Error> {
        let sep = b": ";
        let key_end = memmem::find(h_str, sep).ok_or("missing ': '")?;
        let value_start = key_end + sep.len();
        let key = &h_str[0..key_end];
        let value = &h_str[value_start..h_str.len()];
        Ok(Self {
            key: String::from_utf8_lossy(key).to_string().to_lowercase(),
            value: String::from_utf8_lossy(value).to_string(),
        })
    }
}

impl From<&Header> for String {
    fn from(header: &Header) -> String {
        format!("{}: {}", header.key, header.value)
    }
}

impl From<Header> for String {
    fn from(header: Header) -> String {
        format!("{}: {}", header.key, header.value)
    }
}

impl Header {
    pub fn new(key: &str, value: &str) -> Header {
        Header {
            key: key.to_lowercase(),
            value: value.to_string(),
        }
    }
    /// Create new vector of headers for server
    pub fn new_server() -> Vec<Header> {
        const VERSION: &str = env!("CARGO_PKG_VERSION");
        const NAME: &str = env!("CARGO_PKG_NAME");
        vec![Header {
            key: "Server".to_string(),
            value: format!("{NAME} {VERSION}"),
        }]
    }
}

/*
impl From<StatusCode> for &str {
    fn from(status: StatusCode) -> &'static str {
        match status {
            StatusCode::Continue => "100 Continue",
            StatusCode::OK => "200 OK",
            StatusCode::MultipleChoices => "300 Multiple Choices",
            StatusCode::MovedPermanetly => "301 Moved Permantely",
            StatusCode::Found => "302 Found",
            StatusCode::SeeOther => "303 See Other",
            StatusCode::TempRedirect => "307 Temporarily Moved",
            StatusCode::PermanentRedirect => "308 Permanent Redirect",
            StatusCode::ErrUnathorized => "401 Unathorized",
            StatusCode::ErrForbidden => "403 Forbidden",
            StatusCode::ErrNotFound => "404 Not Found",
            StatusCode::ErrBadRequest => "400 Bad Request",
            StatusCode::ErrInternalServer => "500 Internal Server Error",
        }
    }
}

impl From<StatusCode> for String {
    fn from(status: StatusCode) -> String {
        let status_str: &str = status.into();
        status_str.to_owned()
    }
}
*/
impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Version::V0_9 => "",
            Version::V1_0 => "HTTP/1.0",
            Version::V1_1 => "HTTP/1.1",
            Version::V2_0 => "HTTP/2",
        };
        write!(f, "{}", s)
    }
}

impl From<Version> for &str {
    fn from(version: Version) -> &'static str {
        match version {
            Version::V0_9 => "",
            Version::V1_0 => "HTTP/1.0",
            Version::V1_1 => "HTTP/1.1",
            Version::V2_0 => "HTTP/2",
        }
    }
}

impl From<Version> for String {
    fn from(version: Version) -> String {
        version.to_string()
    }
}