use std::fmt;
use crate::error::{Error, Result};
const MAX_COMPONENT: usize = 64;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PersonName {
groups: Vec<String>,
}
impl PersonName {
pub fn parse(text: &str) -> Result<Self> {
let mut groups: Vec<&str> = text.split('=').collect();
while groups.last().is_some_and(|group| group.is_empty()) {
groups.pop();
}
for group in &groups {
validate_group(group, false)?;
}
Ok(Self {
groups: groups.into_iter().map(str::to_owned).collect(),
})
}
pub fn from_named_components(
family: &str,
given: &str,
middle: &str,
prefix: &str,
suffix: &str,
) -> Result<Self> {
let mut name = Self::default();
name.push_group(&[family, given, middle, prefix, suffix])?;
Ok(name)
}
pub fn with_group(mut self, components: &[&str]) -> Result<Self> {
self.push_group(components)?;
Ok(self)
}
pub fn groups(&self) -> &[String] {
&self.groups
}
pub fn alphabetic(&self) -> &str {
self.groups.first().map_or("", String::as_str)
}
pub fn ideographic(&self) -> &str {
self.groups.get(1).map_or("", String::as_str)
}
pub fn phonetic(&self) -> &str {
self.groups.get(2).map_or("", String::as_str)
}
pub fn component(&self, group: usize, index: usize) -> &str {
self.groups
.get(group)
.and_then(|text| text.split('^').nth(index))
.unwrap_or("")
}
pub fn family_name(&self) -> &str {
self.component(0, 0)
}
pub fn given_name(&self) -> &str {
self.component(0, 1)
}
pub fn middle_name(&self) -> &str {
self.component(0, 2)
}
pub fn name_prefix(&self) -> &str {
self.component(0, 3)
}
pub fn name_suffix(&self) -> &str {
self.component(0, 4)
}
pub fn is_empty(&self) -> bool {
self.groups.iter().all(|group| group.is_empty())
}
pub fn to_value(&self) -> String {
self.groups.join("=")
}
fn push_group(&mut self, components: &[&str]) -> Result<()> {
let mut parts: Vec<&str> = components.to_vec();
while parts.last().is_some_and(|part| part.is_empty()) {
parts.pop();
}
for part in &parts {
validate_group(part, true)?;
}
self.groups.push(parts.join("^"));
Ok(())
}
}
fn validate_group(group: &str, from_components: bool) -> Result<()> {
if group.contains('\\') {
return Err(Error::InvalidValue(format!(
"a person name cannot contain a backslash: {group}"
)));
}
if from_components {
for delimiter in ['^', '='] {
if group.contains(delimiter) {
return Err(Error::InvalidValue(format!(
"a person name component cannot contain '{delimiter}': {group}"
)));
}
}
}
for component in group.split('^') {
if component.chars().count() > MAX_COMPONENT {
return Err(Error::InvalidValue(format!(
"a person name component exceeds {MAX_COMPONENT} characters: {component}"
)));
}
}
Ok(())
}
impl fmt::Display for PersonName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_value())
}
}
impl std::str::FromStr for PersonName {
type Err = Error;
fn from_str(text: &str) -> Result<Self> {
Self::parse(text)
}
}