chiark / gitweb /
server: introduce RoutedPacket
[hippotat.git] / src / types.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 #[derive(Debug,Copy,Clone)]
8 pub enum LinkEnd { Server, Client }
9
10 #[derive(Debug,Clone,Hash,Eq,PartialEq,Ord,PartialOrd)]
11 pub struct ServerName(pub String);
12
13 #[derive(Debug,Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd)]
14 pub struct ClientName(pub Ipv4Addr);
15
16 #[derive(Debug,Clone,Hash,Eq,PartialEq,Ord,PartialOrd)]
17 pub struct LinkName {
18   pub server: ServerName,
19   pub client: ClientName,
20 }
21
22 impl FromStr for ClientName {
23   type Err = AE;
24   #[throws(AE)]
25   fn from_str(s: &str) -> Self {
26     let v4addr: Ipv4Addr = s.parse()
27       .context("invalid client name (IPv4 address)")?;
28     if s != v4addr.to_string() {
29       throw!(anyhow!("invalid client name (unusual IPv4 address syntax)"));
30     }
31     ClientName(v4addr)
32   }
33 }
34
35 impl FromStr for ServerName {
36   type Err = AE;
37   #[throws(AE)]
38   fn from_str(s: &str) -> Self {
39     if ! regex_is_match!(r"
40         ^ (?: SERVER
41             | [0-9a-z][-0-9a-z]* (:? \.
42               [0-9a-z][-0-9a-z]*        )*
43           ) $"x, s) {
44       throw!(anyhow!("bad syntax for server name"));
45     }
46     if ! regex_is_match!(r"[A-Za-z-]", s) {
47       throw!(anyhow!("bad syntax for server name \
48                       (too much like an IPv4 address)"));
49     }
50     ServerName(s.into())
51   }
52 }
53
54 impl Display for ServerName {
55   #[throws(fmt::Error)]
56   fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.0, f)?; }
57 }
58 impl Display for ClientName {
59   #[throws(fmt::Error)]
60   fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.0, f)?; }
61 }
62 impl Display for LinkName {
63   #[throws(fmt::Error)]
64   fn fmt(&self, f: &mut fmt::Formatter) {
65     write!(f, "[{} {}]", &self.server, &self.client)?;
66   }
67 }