weirdnet_service/
protocol.rs1use std::fmt;
4use std::str::FromStr;
5
6use crate::ServiceError;
7
8pub const WIRE: u8 = 1;
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct ProtocolId {
19 base: String,
20 version: u32,
21 id: String,
22}
23
24impl ProtocolId {
25 pub fn new(base: &str, version: u32) -> Result<Self, ServiceError> {
28 let ok_segment = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
29 let Some(rest) = base.strip_prefix('/') else {
30 return Err(ServiceError::bad_request(format!("protocol base {base:?} must start with /")));
31 };
32 if !rest.split('/').all(ok_segment) || base.len() > 200 {
33 return Err(ServiceError::bad_request(format!("protocol base {base:?} is not valid")));
34 }
35 if version == 0 {
36 return Err(ServiceError::bad_request("protocol versions start at 1"));
37 }
38 Ok(Self { base: base.to_string(), version, id: format!("{base}/{version}") })
39 }
40
41 pub fn parse(id: &str) -> Result<Self, ServiceError> {
43 let (base, v) = id.rsplit_once('/').ok_or_else(|| ServiceError::bad_request(format!("{id:?} is not a protocol id")))?;
44 if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) || v.starts_with('0') {
45 return Err(ServiceError::bad_request(format!("{id:?} does not end in a version")));
46 }
47 let version = v.parse().map_err(|_| ServiceError::bad_request(format!("{id:?}: version too large")))?;
48 Self::new(base, version)
49 }
50
51 pub fn base(&self) -> &str {
52 &self.base
53 }
54
55 pub fn version(&self) -> u32 {
56 self.version
57 }
58
59 pub fn as_str(&self) -> &str {
61 &self.id
62 }
63
64 pub fn with_version(&self, version: u32) -> Result<Self, ServiceError> {
66 Self::new(&self.base, version)
67 }
68}
69
70impl fmt::Display for ProtocolId {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(&self.id)
73 }
74}
75
76impl FromStr for ProtocolId {
77 type Err = ServiceError;
78
79 fn from_str(s: &str) -> Result<Self, Self::Err> {
80 Self::parse(s)
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn ids_parse_print_and_validate() {
90 let p = ProtocolId::new("/myapp/api", 2).unwrap();
91 assert_eq!((p.as_str(), p.base(), p.version()), ("/myapp/api/2", "/myapp/api", 2));
92 assert_eq!(ProtocolId::parse("/myapp/api/2").unwrap(), p);
93 assert_eq!(p.with_version(1).unwrap().to_string(), "/myapp/api/1");
94 for bad in ["myapp/api/1", "/myapp//api/1", "/myapp/api/", "/myapp/api/0", "/myapp/api/v1", "/my app/1", "/myapp/api/01"] {
95 assert!(ProtocolId::parse(bad).is_err(), "{bad}");
96 }
97 assert!(ProtocolId::new("/x", 0).is_err());
98 assert!(ProtocolId::parse("/x/1").unwrap() < ProtocolId::parse("/x/2").unwrap());
99 }
100}