//! A space's address (`spec/SPACES.md`, "Addressing"): its authority, a DID; //! its type, an NSID; and its key, with the syntax of a record key. use pds_repo::data::{valid_did, valid_nsid, valid_rkey}; /// The longest `skey`, in bytes. pub const MAX_SKEY: usize = 512; /// A space, as a `space-ref` names it. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SpaceRef { pub authority: String, pub typ: String, pub skey: String, } impl SpaceRef { /// A string in the format `space-ref`: `at://{authority}/space/{type}/{skey}` /// and no more, each part valid. pub fn parse(s: &str) -> Option { let mut parts = s.strip_prefix("at://")?.split('/'); let (Some(authority), Some("space"), Some(typ), Some(skey), None) = ( parts.next(), parts.next(), parts.next(), parts.next(), parts.next(), ) else { return None; }; (valid_did(authority) && valid_nsid(typ) && valid_rkey(skey) && skey.len() <= MAX_SKEY) .then(|| SpaceRef { authority: authority.into(), typ: typ.into(), skey: skey.into(), }) } /// The space's URI. pub fn uri(&self) -> String { format!("at://{}/space/{}/{}", self.authority, self.typ, self.skey) } } #[cfg(test)] mod tests { use super::*; #[test] fn space_refs() { let s = SpaceRef::parse("at://did:plc:abc/space/com.example.forum/main").unwrap(); assert_eq!( (s.authority.as_str(), s.typ.as_str(), s.skey.as_str()), ("did:plc:abc", "com.example.forum", "main") ); assert_eq!(s.uri(), "at://did:plc:abc/space/com.example.forum/main"); assert!( SpaceRef::parse(&format!( "at://did:web:example.com/space/com.example.x/{}", "k".repeat(512) )) .is_some() ); for bad in [ "at://did:plc:abc/space/com.example.forum", "at://did:plc:abc/space/com.example.forum/main/", "at://did:plc:abc/space/com.example.forum/main/did:plc:x/a.b.c/k", "at://did:plc:abc/spaces/com.example.forum/main", "at://alice.test/space/com.example.forum/main", "at://did:plc:abc/space/forum/main", "at://did:plc:abc/space/com.example.forum/a b", "at://did:plc:abc/space/com.example.forum/..", "did:plc:abc/space/com.example.forum/main", "", ] { assert!(SpaceRef::parse(bad).is_none(), "{bad}"); } assert!( SpaceRef::parse(&format!( "at://did:plc:abc/space/com.example.x/{}", "k".repeat(513) )) .is_none() ); } }