use std::fmt;
use std::str::FromStr;
use canvist_model::BlockId;
use canvist_model::IdGenerator;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(u64);
impl NodeId {
pub const ROOT: Self = Self(u64::MAX);
#[must_use]
pub const fn new(client: u32, seq: u32) -> Self {
Self(BlockId::new(client, seq).as_u64())
}
#[must_use]
pub const fn client(self) -> u32 {
(self.0 >> 32) as u32
}
#[must_use]
pub const fn seq(self) -> u32 {
self.0 as u32
}
#[must_use]
pub const fn is_root(self) -> bool {
self.0 == u64::MAX
}
#[must_use]
pub const fn as_u64(self) -> u64 {
self.0
}
#[must_use]
pub const fn from_u64(raw: u64) -> Self {
Self(raw)
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_root() {
return f.write_str("root");
}
BlockId::from_u64(self.0).fmt(f)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("invalid node id `{0}`: expected `root` or `client.seq` in base 36")]
pub struct ParseNodeIdError(String);
impl FromStr for NodeId {
type Err = ParseNodeIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s == "root" {
return Ok(Self::ROOT);
}
let id = s
.parse::<BlockId>()
.map_err(|_| ParseNodeIdError(s.to_owned()))?;
if id.client() == u32::MAX {
return Err(ParseNodeIdError(s.to_owned()));
}
Ok(Self(id.as_u64()))
}
}
#[derive(Clone, Debug)]
pub struct NodeIdGenerator(IdGenerator);
impl NodeIdGenerator {
#[must_use]
pub const fn new(client: u32) -> Self {
assert!(client != u32::MAX, "client id u32::MAX is reserved");
Self(IdGenerator::new(client))
}
#[must_use]
pub const fn client(&self) -> u32 {
self.0.client()
}
pub fn next_id(&mut self) -> Option<NodeId> {
self.0.next_id().map(|id| NodeId(id.as_u64()))
}
pub fn observe(&mut self, id: NodeId) {
self.0.observe(BlockId::from_u64(id.as_u64()));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_and_parses() {
let id = NodeId::new(123_456, 7);
assert_eq!(id.to_string(), "2n9c.7");
assert_eq!("2n9c.7".parse::<NodeId>(), Ok(id));
assert_eq!(NodeId::ROOT.to_string(), "root");
assert_eq!("root".parse::<NodeId>(), Ok(NodeId::ROOT));
assert!("nope".parse::<NodeId>().is_err());
}
#[test]
fn the_root_client_is_reserved() {
let reserved = BlockId::new(u32::MAX, 3).to_string();
assert!(reserved.parse::<NodeId>().is_err());
}
#[test]
fn generator_skips_observed_ids() {
let mut ids = NodeIdGenerator::new(4);
ids.observe(NodeId::new(4, 10));
assert_eq!(ids.next_id(), Some(NodeId::new(4, 11)));
}
}