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
|
#[derive(Debug, Clone)]
pub enum Protocol {
HTTP,
HTTPS,
}
impl Protocol {
pub fn serialize(string: &str) -> Option<Self> {
match string {
"http" => return Some(Self::HTTP),
"https" => return Some(Self::HTTPS),
_ => return None
}
}
pub fn deserialize(&self) -> &str {
match self {
Self::HTTP => "http",
Self::HTTPS => "https",
}
}
}
#[derive(Debug, Clone)]
pub struct URI {
pub protocol: Option<Protocol>,
pub host: Option<String>,
pub port: Option<u16>,
pub route: String
}
impl URI {
#[allow(dead_code)]
pub fn deserialize(&self) -> String {
let mut string = String::new();
if let Some(protocol) = &self.protocol {
string += protocol.deserialize();
string += "://";
}
if let Some(host) = &self.host {
string += host;
}
if let Some(port) = self.port {
string += &format!(":{port}");
}
string += &self.route;
string
}
pub fn serialize(head: &str) -> Option<Self> {
let protocol_end = match head.find("://") {
Some(i) => i,
None => 0
};
let protocol: Option<Protocol>;
let host_start: usize;
if protocol_end == 0 {
protocol = None;
host_start = 0;
} else {
let Some(p) = Protocol::serialize(&head[..protocol_end]) else {
return None
};
protocol = Some(p);
host_start = protocol_end + 3;
}
let host_route = &head[host_start..];
let host_end = host_route.find("/").unwrap_or(head.len());
let host: Option<String>;
let port: Option<u16>;
if host_start == host_end {
host = None;
port = None;
} else {
if let Some (host_split) = host_route.find(":") {
let port_start = host_split + 1;
let port_str = &head[port_start..host_end];
let Ok(p) = port_str.parse::<u16>() else {
return None
};
host = Some(head[host_start..host_split].to_owned());
port = Some(p);
} else {
host = Some(head[host_start..host_end].to_owned());
port = None;
}
}
let route = &head[host_end..];
Some(Self {
protocol,
host,
port,
route: route.to_owned()
})
}
}
|