Skip to main content

kanon/
request.rs

1use std::{str::FromStr, string::FromUtf8Error};
2use url::{ParseError, Url};
3
4#[derive(Debug)]
5pub struct Request {
6    url: Result<Url, RequestError>,
7}
8
9#[derive(Debug)]
10pub enum RequestError {
11    StringError(FromUtf8Error),
12    UrlError(ParseError),
13}
14
15impl Request {
16    pub fn into_url(self) -> Result<Url, RequestError> {
17        self.into()
18    }
19    pub fn from_buf(buf: &[u8]) -> Self {
20        Self::from(buf)
21    }
22}
23
24impl From<&[u8]> for Request {
25    fn from(value: &[u8]) -> Self {
26        let buf = Vec::from(value);
27        let url = match String::from_utf8(buf) {
28            Ok(s) => s,
29            Err(e) => {
30                return Request {
31                    url: Err(RequestError::StringError(e)),
32                }
33            }
34        };
35        let url = match Url::from_str(&url) {
36            Ok(u) => Ok(u),
37            Err(e) => Err(RequestError::UrlError(e)),
38        };
39        Request { url }
40    }
41}
42
43impl From<String> for Request {
44    fn from(value: String) -> Self {
45        let url = match Url::from_str(&String::from_iter(
46            value
47                .bytes()
48                .filter(|b| *b != b'\0')
49                .map(|b| <u8 as Into<char>>::into(b)),
50        )) {
51            Ok(url) => Ok(url),
52            Err(e) => Err(RequestError::UrlError(e)),
53        };
54        Request { url }
55    }
56}
57
58impl Into<Result<Url, RequestError>> for Request {
59    fn into(self) -> Result<Url, RequestError> {
60        self.url
61    }
62}