use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Identity {
Email(String),
KeyId(String),
Hash(String),
}
impl Identity {
pub fn from_kind(kind: &str, value: &str) -> Self {
match kind {
"email" => Identity::Email(value.to_string()),
"key-id" => Identity::KeyId(value.to_string()),
_ => Identity::Hash(value.to_string()),
}
}
pub fn canonical(&self) -> String {
match self {
Identity::Email(v) => format!("email:{v}"),
Identity::KeyId(v) => format!("key-id:{v}"),
Identity::Hash(v) => format!("hash:{v}"),
}
}
pub fn value(&self) -> &str {
match self {
Identity::Email(v) | Identity::KeyId(v) | Identity::Hash(v) => v,
}
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.canonical())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn email_canonicalises_with_prefix() {
let id = Identity::Email("alice@example.com".to_string());
assert_eq!(id.canonical(), "email:alice@example.com");
assert_eq!(id.value(), "alice@example.com");
}
#[test]
fn from_kind_routes_known_prefixes() {
assert_eq!(
Identity::from_kind("email", "b@b"),
Identity::Email("b@b".to_string())
);
assert_eq!(
Identity::from_kind("key-id", "deadbeef"),
Identity::KeyId("deadbeef".to_string())
);
}
#[test]
fn from_kind_defaults_unknown_to_hash() {
assert_eq!(
Identity::from_kind("fingerprint", "abcd"),
Identity::Hash("abcd".to_string())
);
}
#[test]
fn distinct_kinds_are_distinct_keys() {
let a = Identity::Email("x".to_string());
let b = Identity::KeyId("x".to_string());
assert_ne!(a.canonical(), b.canonical());
}
}