use super::types::TenantPath;
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ScopedName {
tenant: TenantPath,
name: String,
}
impl ScopedName {
pub fn new(tenant: TenantPath, name: impl Into<String>) -> Self {
Self {
tenant,
name: name.into(),
}
}
pub fn tenant(&self) -> &TenantPath {
&self.tenant
}
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn renamed(&self, name: impl Into<String>) -> Self {
Self::new(self.tenant.clone(), name)
}
}
impl fmt::Display for ScopedName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.tenant, self.name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_same_name_in_two_tenants_is_two_keys() {
let a = ScopedName::new(TenantPath::new(vec![5, 7]), "alice");
let b = ScopedName::new(TenantPath::new(vec![6, 7]), "alice");
assert_ne!(a, b);
}
#[test]
fn a_rename_keeps_the_tenant() {
let a = ScopedName::new(TenantPath::new(vec![5, 7]), "alice");
let r = a.renamed("alicia");
assert_eq!(r.tenant(), a.tenant());
assert_eq!(r.name(), "alicia");
}
#[test]
fn it_round_trips_through_serde() {
let a = ScopedName::new(TenantPath::new(vec![0, 7]), "root");
let json = serde_json::to_string(&a).unwrap();
assert_eq!(json, r#"{"tenant":"0/7","name":"root"}"#);
assert_eq!(serde_json::from_str::<ScopedName>(&json).unwrap(), a);
}
#[test]
fn it_displays_tenant_then_name() {
let a = ScopedName::new(TenantPath::new(vec![5, 7]), "alice");
assert_eq!(a.to_string(), "5/7:alice");
}
}