use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Identifier {
Doi(String),
Pmid(String),
Pmcid(String),
Omid(String),
Issn(String),
Isbn(String),
OpenAlex(String),
Orcid(String),
Ror(String),
Crossref(String),
Other {
scheme: String,
value: String,
},
}
impl Identifier {
pub fn doi(doi: impl Into<String>) -> Self {
Identifier::Doi(doi.into())
}
pub fn pmid(pmid: impl Into<String>) -> Self {
Identifier::Pmid(pmid.into())
}
pub fn omid(omid: impl Into<String>) -> Self {
Identifier::Omid(omid.into())
}
pub fn issn(issn: impl Into<String>) -> Self {
Identifier::Issn(issn.into())
}
pub fn scheme(&self) -> &str {
match self {
Identifier::Doi(_) => "doi",
Identifier::Pmid(_) => "pmid",
Identifier::Pmcid(_) => "pmcid",
Identifier::Omid(_) => "omid",
Identifier::Issn(_) => "issn",
Identifier::Isbn(_) => "isbn",
Identifier::OpenAlex(_) => "openalex",
Identifier::Orcid(_) => "orcid",
Identifier::Ror(_) => "ror",
Identifier::Crossref(_) => "crossref",
Identifier::Other { scheme, .. } => scheme,
}
}
pub fn value(&self) -> &str {
match self {
Identifier::Doi(value)
| Identifier::Pmid(value)
| Identifier::Pmcid(value)
| Identifier::Omid(value)
| Identifier::Issn(value)
| Identifier::Isbn(value)
| Identifier::OpenAlex(value)
| Identifier::Orcid(value)
| Identifier::Ror(value)
| Identifier::Crossref(value)
| Identifier::Other { value, .. } => value,
}
}
pub fn as_doi(&self) -> Option<&str> {
match self {
Identifier::Doi(doi) => Some(doi),
_ => None,
}
}
pub fn parse_bag(bag: &str) -> Result<Vec<Identifier>> {
bag.split_whitespace().map(Identifier::from_str).collect()
}
}
impl FromStr for Identifier {
type Err = Error;
fn from_str(id: &str) -> Result<Self> {
let id = id.trim();
let Some((scheme, value)) = id.split_once(':') else {
return Err(Error::UnprefixedIdentifier {
given: id.to_string(),
});
};
if scheme.is_empty() {
return Err(Error::InvalidIdentifier {
given: id.to_string(),
why: "it has no scheme before the `:`",
});
}
if value.is_empty() {
return Err(Error::InvalidIdentifier {
given: id.to_string(),
why: "it has no value after the `:`",
});
}
let value = value.to_string();
Ok(match scheme.to_ascii_lowercase().as_str() {
"doi" => Identifier::Doi(value),
"pmid" => Identifier::Pmid(value),
"pmcid" => Identifier::Pmcid(value),
"omid" => Identifier::Omid(value),
"issn" => Identifier::Issn(value),
"isbn" => Identifier::Isbn(value),
"openalex" => Identifier::OpenAlex(value),
"orcid" => Identifier::Orcid(value),
"ror" => Identifier::Ror(value),
"crossref" => Identifier::Crossref(value),
other => Identifier::Other {
scheme: other.to_string(),
value,
},
})
}
}
impl fmt::Display for Identifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.scheme(), self.value())
}
}
impl Serialize for Identifier {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Identifier {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Identifier::from_str(&raw).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Oci {
citing: String,
cited: String,
}
impl Oci {
pub fn citing(&self) -> &str {
&self.citing
}
pub fn cited(&self) -> &str {
&self.cited
}
}
impl FromStr for Oci {
type Err = Error;
fn from_str(oci: &str) -> Result<Self> {
let bare = oci.trim().strip_prefix("oci:").unwrap_or(oci.trim());
let Some((citing, cited)) = bare.split_once('-') else {
return Err(Error::InvalidOci {
given: oci.to_string(),
why: "it is two omids joined by a `-`",
});
};
let numeric = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
if !numeric(citing) || !numeric(cited) {
return Err(Error::InvalidOci {
given: oci.to_string(),
why: "both halves are numbers",
});
}
Ok(Oci {
citing: citing.to_string(),
cited: cited.to_string(),
})
}
}
impl fmt::Display for Oci {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}", self.citing, self.cited)
}
}
impl Serialize for Oci {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Oci {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Oci::from_str(&raw).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_identifier_keeps_its_scheme_and_value() {
let id: Identifier = "doi:10.1016/j.marpol.2021.104855".parse().unwrap();
assert_eq!(id, Identifier::doi("10.1016/j.marpol.2021.104855"));
assert_eq!(id.scheme(), "doi");
assert_eq!(id.value(), "10.1016/j.marpol.2021.104855");
assert_eq!(id.as_doi(), Some("10.1016/j.marpol.2021.104855"));
assert_eq!(id.to_string(), "doi:10.1016/j.marpol.2021.104855");
}
#[test]
fn only_the_first_colon_separates() {
let omid: Identifier = "omid:br/06220256775".parse().unwrap();
assert_eq!(omid, Identifier::omid("br/06220256775"));
let url: Identifier = "url:https://example.com/a".parse().unwrap();
assert_eq!(url.value(), "https://example.com/a");
}
#[test]
fn an_unprefixed_identifier_is_refused_with_the_form_it_should_take() {
let err = "10.1016/j.marpol.2021.104855"
.parse::<Identifier>()
.unwrap_err();
assert!(err.to_string().contains("doi:10.1016"), "{err}");
assert!("doi:".parse::<Identifier>().is_err());
assert!(":10.1016".parse::<Identifier>().is_err());
}
#[test]
fn an_unknown_scheme_is_kept_rather_than_refused() {
let id: Identifier = "wikidata:Q42".parse().unwrap();
assert_eq!(id.scheme(), "wikidata");
assert_eq!(id.value(), "Q42");
assert_eq!(id.as_doi(), None);
}
#[test]
fn a_bag_of_identifiers_reads_as_all_of_them() {
let bag = Identifier::parse_bag(
"omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
)
.unwrap();
assert_eq!(bag.len(), 3);
assert_eq!(
bag.iter().find_map(Identifier::as_doi),
Some("10.1016/j.marpol.2021.104855")
);
}
#[test]
fn an_oci_is_the_two_omids_it_joins() {
let oci: Oci = "06024047477-06220256775".parse().unwrap();
assert_eq!(oci.citing(), "06024047477");
assert_eq!(oci.cited(), "06220256775");
assert_eq!(oci.to_string(), "06024047477-06220256775");
assert_eq!("oci:06024047477-06220256775".parse::<Oci>().unwrap(), oci);
}
#[test]
fn something_that_is_not_an_oci_is_refused() {
assert!("06024047477".parse::<Oci>().is_err());
assert!("abc-def".parse::<Oci>().is_err());
assert!("-06220256775".parse::<Oci>().is_err());
}
}