use std::collections::BTreeMap;
use std::sync::LazyLock;
use regex::Regex;
use serde::Serialize;
use crate::model::enums::{NamePart, NameType, NomCode, Rank, State};
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Authorship {
pub authors: Vec<String>,
#[serde(rename = "exAuthors")]
pub ex_authors: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub year: Option<String>,
#[serde(rename = "imprintYear", skip_serializing_if = "Option::is_none")]
pub imprint_year: Option<String>,
}
impl Authorship {
pub fn exists(&self) -> bool {
!self.authors.is_empty() || self.year.is_some()
}
pub fn has_authors(&self) -> bool {
!self.authors.is_empty()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct CombinedAuthorship {
#[serde(rename = "combinationAuthorship")]
pub combination_authorship: Authorship,
#[serde(rename = "basionymAuthorship")]
pub basionym_authorship: Authorship,
#[serde(rename = "sanctioningAuthor", skip_serializing_if = "Option::is_none")]
pub sanctioning_author: Option<String>,
}
impl CombinedAuthorship {
pub fn has_authorship(&self) -> bool {
self.combination_authorship.exists() || self.basionym_authorship.exists()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ParsedName {
pub rank: Rank,
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<NomCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub uninomial: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub genus: Option<String>,
#[serde(rename = "genericAuthorship", skip_serializing_if = "Option::is_none")]
pub generic_authorship: Option<CombinedAuthorship>,
#[serde(
rename = "infragenericEpithet",
skip_serializing_if = "Option::is_none"
)]
pub infrageneric_epithet: Option<String>,
#[serde(rename = "specificEpithet", skip_serializing_if = "Option::is_none")]
pub specific_epithet: Option<String>,
#[serde(rename = "specificAuthorship", skip_serializing_if = "Option::is_none")]
pub specific_authorship: Option<CombinedAuthorship>,
#[serde(
rename = "infraspecificEpithet",
skip_serializing_if = "Option::is_none"
)]
pub infraspecific_epithet: Option<String>,
#[serde(rename = "cultivarEpithet", skip_serializing_if = "Option::is_none")]
pub cultivar_epithet: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phrase: Option<String>,
pub candidatus: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub notho: Option<Vec<NamePart>>,
#[serde(rename = "originalSpelling", skip_serializing_if = "Option::is_none")]
pub original_spelling: Option<bool>,
#[serde(rename = "epithetQualifier", skip_serializing_if = "Option::is_none")]
pub epithet_qualifier: Option<BTreeMap<NamePart, String>>,
#[serde(rename = "type")]
pub type_: NameType,
pub extinct: bool,
#[serde(rename = "taxonomicNote", skip_serializing_if = "Option::is_none")]
pub taxonomic_note: Option<String>,
#[serde(rename = "nomenclaturalNote", skip_serializing_if = "Option::is_none")]
pub nomenclatural_note: Option<String>,
#[serde(rename = "publishedIn", skip_serializing_if = "Option::is_none")]
pub published_in: Option<String>,
#[serde(rename = "publishedInYear", skip_serializing_if = "Option::is_none")]
pub published_in_year: Option<i32>,
#[serde(rename = "publishedInPage", skip_serializing_if = "Option::is_none")]
pub published_in_page: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unparsed: Option<String>,
pub doubtful: bool,
pub manuscript: bool,
pub state: State,
pub warnings: Vec<String>,
#[serde(rename = "combinationAuthorship")]
pub combination_authorship: Authorship,
#[serde(rename = "basionymAuthorship")]
pub basionym_authorship: Authorship,
#[serde(rename = "sanctioningAuthor", skip_serializing_if = "Option::is_none")]
pub sanctioning_author: Option<String>,
}
static PUBLISHED_IN_YEAR: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?-u:\b(1[5-9]\d{2}|20\d{2}|2100)\b)").unwrap());
impl ParsedName {
pub fn add_warning(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
pub fn set_published_in(&mut self, s: &str) {
self.published_in = Some(s.to_string());
self.published_in_year = PUBLISHED_IN_YEAR
.captures_iter(s)
.last()
.and_then(|caps| caps.get(1))
.and_then(|m| m.as_str().parse::<i32>().ok());
}
pub fn add_published_in(&mut self, reference: &str) {
let combined = match self.published_in.take() {
None => reference.to_string(),
Some(existing) => format!("{existing} {reference}"),
};
self.set_published_in(&combined);
}
pub fn add_nomenclatural_note(&mut self, note: &str) {
self.nomenclatural_note = Some(match self.nomenclatural_note.take() {
None => note.to_string(),
Some(existing) => format!("{existing} {note}"),
});
}
pub fn add_taxonomic_note(&mut self, note: &str) {
self.taxonomic_note = Some(match self.taxonomic_note.take() {
None => note.to_string(),
Some(existing) => format!("{existing} {note}"),
});
}
pub fn add_notho(&mut self, part: NamePart) {
match &mut self.notho {
None => self.notho = Some(vec![part]),
Some(set) => {
if !set.contains(&part) {
set.push(part);
set.sort();
}
}
}
}
pub fn set_notho(&mut self, part: NamePart) {
self.notho = Some(vec![part]);
}
pub fn set_epithet_qualifier(&mut self, part: NamePart, q: &str) {
self.epithet_qualifier
.get_or_insert_with(BTreeMap::new)
.insert(part, q.to_string());
}
pub fn is_autonym(&self) -> bool {
self.specific_epithet.is_some() && self.specific_epithet == self.infraspecific_epithet
}
pub fn has_authorship(&self) -> bool {
self.combination_authorship.exists() || self.basionym_authorship.exists()
}
}
impl Default for ParsedName {
fn default() -> Self {
ParsedName {
rank: Rank::Unranked,
code: None,
uninomial: None,
genus: None,
generic_authorship: None,
infrageneric_epithet: None,
specific_epithet: None,
specific_authorship: None,
infraspecific_epithet: None,
cultivar_epithet: None,
phrase: None,
candidatus: false,
notho: None,
original_spelling: None,
epithet_qualifier: None,
type_: NameType::Scientific,
extinct: false,
taxonomic_note: None,
nomenclatural_note: None,
published_in: None,
published_in_year: None,
published_in_page: None,
unparsed: None,
doubtful: false,
manuscript: false,
state: State::Complete,
warnings: Vec::new(),
combination_authorship: Authorship::default(),
basionym_authorship: Authorship::default(),
sanctioning_author: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wire_matches_reference_row_1_vulpes_vulpes_silaceus() {
let pn = ParsedName {
rank: Rank::Subspecies,
code: Some(NomCode::Zoological),
genus: Some("Vulpes".to_string()),
specific_epithet: Some("vulpes".to_string()),
infraspecific_epithet: Some("silaceus".to_string()),
combination_authorship: Authorship {
authors: vec!["Miller".to_string()],
year: Some("1907".to_string()),
..Default::default()
},
..Default::default()
};
let expected = r#"{"rank":"SUBSPECIES","code":"ZOOLOGICAL","genus":"Vulpes","specificEpithet":"vulpes","infraspecificEpithet":"silaceus","candidatus":false,"type":"SCIENTIFIC","extinct":false,"doubtful":false,"manuscript":false,"state":"COMPLETE","warnings":[],"combinationAuthorship":{"authors":["Miller"],"exAuthors":[],"year":"1907"},"basionymAuthorship":{"authors":[],"exAuthors":[]}}"#;
assert_eq!(serde_json::to_string(&pn).unwrap(), expected);
}
#[test]
fn wire_matches_reference_row_2_abies_alba() {
let pn = ParsedName {
rank: Rank::Species,
genus: Some("Abies".to_string()),
specific_epithet: Some("alba".to_string()),
combination_authorship: Authorship {
authors: vec!["Mill.".to_string()],
..Default::default()
},
..Default::default()
};
let expected = r#"{"rank":"SPECIES","genus":"Abies","specificEpithet":"alba","candidatus":false,"type":"SCIENTIFIC","extinct":false,"doubtful":false,"manuscript":false,"state":"COMPLETE","warnings":[],"combinationAuthorship":{"authors":["Mill."],"exAuthors":[]},"basionymAuthorship":{"authors":[],"exAuthors":[]}}"#;
assert_eq!(serde_json::to_string(&pn).unwrap(), expected);
}
#[test]
fn parsed_name_default_seeds_match_parse_context() {
let pn = ParsedName::default();
assert_eq!(pn.rank, Rank::Unranked);
assert_eq!(pn.type_, NameType::Scientific);
assert_eq!(pn.state, State::Complete);
assert_eq!(pn.code, None);
assert!(!pn.candidatus);
assert!(!pn.extinct);
assert!(!pn.doubtful);
assert!(!pn.manuscript);
assert!(pn.warnings.is_empty());
assert_eq!(pn.combination_authorship, Authorship::default());
assert_eq!(pn.basionym_authorship, Authorship::default());
}
#[test]
fn default_parsed_name_serializes_with_all_optionals_omitted() {
let expected = r#"{"rank":"UNRANKED","candidatus":false,"type":"SCIENTIFIC","extinct":false,"doubtful":false,"manuscript":false,"state":"COMPLETE","warnings":[],"combinationAuthorship":{"authors":[],"exAuthors":[]},"basionymAuthorship":{"authors":[],"exAuthors":[]}}"#;
assert_eq!(
serde_json::to_string(&ParsedName::default()).unwrap(),
expected
);
}
#[test]
fn epithet_qualifier_btreemap_key_renders_as_name_and_sorts_ordinally() {
let mut map = BTreeMap::new();
map.insert(NamePart::Specific, "cf.".to_string());
map.insert(NamePart::Generic, "aff.".to_string());
let pn = ParsedName {
epithet_qualifier: Some(map),
..Default::default()
};
let json = serde_json::to_string(&pn).unwrap();
assert!(json.contains(r#""epithetQualifier":{"GENERIC":"aff.","SPECIFIC":"cf."}"#));
}
#[test]
fn notho_serializes_as_array_when_present_and_is_omitted_when_none() {
assert!(!serde_json::to_string(&ParsedName::default())
.unwrap()
.contains("notho"));
let pn = ParsedName {
notho: Some(vec![NamePart::Specific]),
..Default::default()
};
assert!(serde_json::to_string(&pn)
.unwrap()
.contains(r#""notho":["SPECIFIC"]"#));
}
#[test]
fn add_warning_dedups_like_javas_hashset() {
let mut pn = ParsedName::default();
pn.add_warning("some warning");
pn.add_warning("some warning");
assert_eq!(pn.warnings, vec!["some warning".to_string()]);
}
#[test]
fn set_published_in_stores_the_reference_verbatim_and_derives_the_year() {
let mut pn = ParsedName::default();
pn.set_published_in("Annals and Magazine of Natural History 1988");
assert_eq!(
pn.published_in,
Some("Annals and Magazine of Natural History 1988".to_string())
);
assert_eq!(pn.published_in_year, Some(1988));
}
#[test]
fn set_published_in_with_no_year_leaves_published_in_year_none() {
let mut pn = ParsedName::default();
pn.set_published_in("no year here");
assert_eq!(pn.published_in, Some("no year here".to_string()));
assert_eq!(pn.published_in_year, None);
}
#[test]
fn set_published_in_takes_the_last_year_shaped_match_not_a_page_number() {
let mut pn = ParsedName::default();
pn.set_published_in("75: 1658-1662 fig. 1988");
assert_eq!(pn.published_in_year, Some(1988));
}
#[test]
fn set_published_in_recomputes_the_year_on_every_call_not_just_the_first() {
let mut pn = ParsedName::default();
pn.set_published_in("Author, 1988");
assert_eq!(pn.published_in_year, Some(1988));
pn.set_published_in("Author, no year this time");
assert_eq!(
pn.published_in,
Some("Author, no year this time".to_string())
);
assert_eq!(
pn.published_in_year, None,
"must be cleared, not left stale from the previous call"
);
}
#[test]
fn add_published_in_stores_verbatim_and_derives_the_year_on_first_call() {
let mut pn = ParsedName::default();
pn.add_published_in("Fourcroy, 1785");
assert_eq!(pn.published_in, Some("Fourcroy, 1785".to_string()));
assert_eq!(pn.published_in_year, Some(1785));
}
#[test]
fn add_published_in_appends_with_a_space_separator_and_rederives_the_year() {
let mut pn = ParsedName::default();
pn.add_published_in("Fourcroy, 1785");
pn.add_published_in("Smith, 1900");
assert_eq!(
pn.published_in,
Some("Fourcroy, 1785 Smith, 1900".to_string())
);
assert_eq!(pn.published_in_year, Some(1900));
}
#[test]
fn add_published_in_on_a_reference_with_no_year_clears_a_stale_year() {
let mut pn = ParsedName::default();
pn.set_published_in("Author, 1988");
assert_eq!(pn.published_in_year, Some(1988));
let mut pn2 = ParsedName::default();
pn2.add_published_in("Fleisch.");
assert_eq!(pn2.published_in, Some("Fleisch.".to_string()));
assert_eq!(pn2.published_in_year, None);
}
#[test]
fn add_nomenclatural_note_appends_with_a_space_separator() {
let mut pn = ParsedName::default();
assert_eq!(pn.nomenclatural_note, None);
pn.add_nomenclatural_note("a");
assert_eq!(pn.nomenclatural_note, Some("a".to_string()));
pn.add_nomenclatural_note("b");
assert_eq!(pn.nomenclatural_note, Some("a b".to_string()));
}
#[test]
fn add_taxonomic_note_appends_with_a_space_separator() {
let mut pn = ParsedName::default();
assert_eq!(pn.taxonomic_note, None);
pn.add_taxonomic_note("a");
assert_eq!(pn.taxonomic_note, Some("a".to_string()));
pn.add_taxonomic_note("b");
assert_eq!(pn.taxonomic_note, Some("a b".to_string()));
}
#[test]
fn authorship_exists_ignores_ex_authors_like_java() {
let a = Authorship {
authors: vec![],
ex_authors: vec!["hort.".into()],
year: None,
imprint_year: None,
};
assert!(
!a.exists(),
"only ex-authors present must be exists()==false, matching Java isEmpty()"
);
let b = Authorship {
authors: vec!["L.".into()],
..Default::default()
};
assert!(b.exists());
}
#[test]
fn published_in_year_ignores_non_ascii_digits_like_java() {
let mut pn = ParsedName::default();
pn.set_published_in("Author, 1900, republished ref. 19\u{0668}8 variant");
assert_eq!(pn.published_in_year, Some(1900));
}
#[test]
fn add_notho_inserts_and_dedups_like_javas_enumset() {
let mut pn = ParsedName::default();
pn.add_notho(NamePart::Specific);
assert_eq!(pn.notho, Some(vec![NamePart::Specific]));
pn.add_notho(NamePart::Specific);
assert_eq!(
pn.notho,
Some(vec![NamePart::Specific]),
"adding the same part twice must not duplicate it"
);
}
#[test]
fn add_notho_keeps_ordinal_order_regardless_of_insertion_order() {
let mut pn = ParsedName::default();
pn.add_notho(NamePart::Infraspecific);
pn.add_notho(NamePart::Generic);
assert_eq!(
pn.notho,
Some(vec![NamePart::Generic, NamePart::Infraspecific]),
"Java's EnumSet always iterates in ordinal order regardless of insertion order"
);
}
#[test]
fn set_notho_overwrites_rather_than_adds() {
let mut pn = ParsedName::default();
pn.add_notho(NamePart::Generic);
pn.set_notho(NamePart::Infraspecific);
assert_eq!(
pn.notho,
Some(vec![NamePart::Infraspecific]),
"set_notho must REPLACE the whole set, erasing the earlier add_notho result — \
the load-bearing overwrite asymmetry"
);
}
#[test]
fn set_epithet_qualifier_creates_the_map_on_first_use() {
let mut pn = ParsedName::default();
assert_eq!(pn.epithet_qualifier, None);
pn.set_epithet_qualifier(NamePart::Specific, "cf.");
let mut expected = BTreeMap::new();
expected.insert(NamePart::Specific, "cf.".to_string());
assert_eq!(pn.epithet_qualifier, Some(expected));
}
#[test]
fn set_epithet_qualifier_inserts_additional_parts_into_the_existing_map() {
let mut pn = ParsedName::default();
pn.set_epithet_qualifier(NamePart::Specific, "cf.");
pn.set_epithet_qualifier(NamePart::Infraspecific, "aff.");
let mut expected = BTreeMap::new();
expected.insert(NamePart::Specific, "cf.".to_string());
expected.insert(NamePart::Infraspecific, "aff.".to_string());
assert_eq!(pn.epithet_qualifier, Some(expected));
}
#[test]
fn set_epithet_qualifier_overwrites_an_existing_part() {
let mut pn = ParsedName::default();
pn.set_epithet_qualifier(NamePart::Specific, "cf.");
pn.set_epithet_qualifier(NamePart::Specific, "aff.");
let mut expected = BTreeMap::new();
expected.insert(NamePart::Specific, "aff.".to_string());
assert_eq!(pn.epithet_qualifier, Some(expected));
}
}