use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PersonId(String);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PersonIdError {
Prefixed,
}
impl std::fmt::Display for PersonIdError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a person's id is their bare root key, with no prefix")
}
}
impl std::error::Error for PersonIdError {}
impl PersonId {
pub fn parse(id: &str) -> Result<Self, PersonIdError> {
if id.contains(':') {
return Err(PersonIdError::Prefixed);
}
Ok(Self(id.to_owned()))
}
#[must_use]
pub fn from_root(root: [u8; 32]) -> Self {
Self(hex::encode(root))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn root(&self) -> Option<[u8; 32]> {
let mut root = [0; 32];
hex::decode_to_slice(&self.0, &mut root).ok()?;
Some(root)
}
#[must_use]
#[track_caller]
#[allow(
clippy::expect_used,
reason = "an id this program mints or a fixture names: a prefixed one is a mistake here, not in data"
)]
pub fn expect(id: impl AsRef<str>) -> Self {
Self::parse(id.as_ref()).expect("a person's id is their bare root key")
}
}
impl From<String> for PersonId {
#[track_caller]
fn from(id: String) -> Self {
Self::expect(id)
}
}
impl From<&str> for PersonId {
#[track_caller]
fn from(id: &str) -> Self {
Self::expect(id)
}
}
impl From<&String> for PersonId {
#[track_caller]
fn from(id: &String) -> Self {
Self::expect(id)
}
}
impl From<&PersonId> for PersonId {
fn from(id: &PersonId) -> Self {
id.clone()
}
}
impl std::ops::Deref for PersonId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl AsRef<str> for PersonId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for PersonId {
fn borrow(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for PersonId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl PartialEq<str> for PersonId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for PersonId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl PartialEq<String> for PersonId {
fn eq(&self, other: &String) -> bool {
&self.0 == other
}
}
impl Serialize for PersonId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for PersonId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let id = String::deserialize(deserializer)?;
Self::parse(&id).map_err(D::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
tilo_test_env::scenario! {
fn a_person_id_is_its_bare_root_key;
phase a_bare_root_reads_back_as_the_same_person;
{
let id = PersonId::from_root([7; 32]);
assert_eq!(id.as_str().len(), 64);
assert_eq!(id.root(), Some([7; 32]));
assert_eq!(PersonId::parse(id.as_str()).unwrap(), id);
let json = serde_json::to_string(&id).unwrap();
assert_eq!(json, format!("\"{id}\""), "written bare");
assert_eq!(serde_json::from_str::<PersonId>(&json).unwrap(), id);
}
phase a_prefixed_id_names_no_person;
{
assert_eq!(
PersonId::parse("person:7a7a"),
Err(PersonIdError::Prefixed),
"the prefixed spelling is not a person"
);
assert_eq!(PersonId::parse("agent:helper"), Err(PersonIdError::Prefixed));
assert!(
serde_json::from_str::<PersonId>("\"person:7a\"").is_err(),
"a resource carrying the prefixed spelling does not read as a person"
);
}
}
}