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
use std::{fmt, str::FromStr};
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct EchomailAddress {
pub zone: u16,
pub net: u16,
pub node: u16,
pub point: u16,
}
impl EchomailAddress {
pub fn new(zone: u16, net: u16, node: u16, point: u16) -> Self {
EchomailAddress {
zone,
net,
node,
point,
}
}
pub fn parse(input: &str) -> Option<Self> {
let mut state = EchoParser::Zone;
let mut result = EchomailAddress::default();
let mut got_number = false;
for c in input.chars() {
match state {
EchoParser::Zone => {
if c == ':' {
state = EchoParser::Net;
if !got_number {
return None;
}
got_number = false;
continue;
}
if c.is_ascii_digit() {
if let Some(next) = result
.zone
.checked_mul(10)
.and_then(|z| z.checked_add((c as u8 - b'0') as u16))
{
result.zone = next;
} else {
return None;
}
got_number = true;
} else {
return None;
}
}
EchoParser::Net => {
if c == '/' {
state = EchoParser::Node;
if !got_number {
return None;
}
got_number = false;
continue;
}
if c.is_ascii_digit() {
if let Some(next) = result
.net
.checked_mul(10)
.and_then(|z| z.checked_add((c as u8 - b'0') as u16))
{
result.net = next;
} else {
return None;
}
got_number = true;
} else {
return None;
}
}
EchoParser::Node => {
if c == '.' {
state = EchoParser::Point;
if !got_number {
return None;
}
got_number = false;
continue;
}
if c.is_ascii_digit() {
if let Some(next) = result
.node
.checked_mul(10)
.and_then(|z| z.checked_add((c as u8 - b'0') as u16))
{
result.node = next;
} else {
return None;
}
got_number = true;
} else {
return None;
}
}
EchoParser::Point => {
if c == '.' {
return None;
}
if c.is_ascii_digit() {
if let Some(next) = result
.point
.checked_mul(10)
.and_then(|z| z.checked_add((c as u8 - b'0') as u16))
{
result.point = next;
} else {
return None;
}
got_number = true;
} else {
return None;
}
}
}
}
if got_number && (state == EchoParser::Point || state == EchoParser::Node) {
Some(result)
} else {
None
}
}
}
#[derive(Debug, PartialEq)]
enum EchoParser {
Zone,
Net,
Node,
Point,
}
impl fmt::Display for EchomailAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.point == 0 {
return write!(f, "{}:{}/{}", self.zone, self.net, self.node);
}
write!(f, "{}:{}/{}.{}", self.zone, self.net, self.node, self.point)
}
}
impl FromStr for EchomailAddress {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s).ok_or_else(|| format!("'{}' is not a zone:net/node[.point] address", s))
}
}