1use crate::error::{Error, Result};
9use serde::{Deserialize, Serialize};
10use std::fmt;
11use std::str::FromStr;
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
21#[non_exhaustive]
22pub enum Identifier {
23 Doi(String),
25 Pmid(String),
27 Pmcid(String),
29 Omid(String),
32 Issn(String),
34 Isbn(String),
36 OpenAlex(String),
38 Orcid(String),
41 Ror(String),
43 Crossref(String),
45 Other {
47 scheme: String,
49 value: String,
51 },
52}
53
54impl Identifier {
55 pub fn doi(doi: impl Into<String>) -> Self {
57 Identifier::Doi(doi.into())
58 }
59
60 pub fn pmid(pmid: impl Into<String>) -> Self {
62 Identifier::Pmid(pmid.into())
63 }
64
65 pub fn omid(omid: impl Into<String>) -> Self {
68 Identifier::Omid(omid.into())
69 }
70
71 pub fn issn(issn: impl Into<String>) -> Self {
73 Identifier::Issn(issn.into())
74 }
75
76 pub fn scheme(&self) -> &str {
78 match self {
79 Identifier::Doi(_) => "doi",
80 Identifier::Pmid(_) => "pmid",
81 Identifier::Pmcid(_) => "pmcid",
82 Identifier::Omid(_) => "omid",
83 Identifier::Issn(_) => "issn",
84 Identifier::Isbn(_) => "isbn",
85 Identifier::OpenAlex(_) => "openalex",
86 Identifier::Orcid(_) => "orcid",
87 Identifier::Ror(_) => "ror",
88 Identifier::Crossref(_) => "crossref",
89 Identifier::Other { scheme, .. } => scheme,
90 }
91 }
92
93 pub fn value(&self) -> &str {
95 match self {
96 Identifier::Doi(value)
97 | Identifier::Pmid(value)
98 | Identifier::Pmcid(value)
99 | Identifier::Omid(value)
100 | Identifier::Issn(value)
101 | Identifier::Isbn(value)
102 | Identifier::OpenAlex(value)
103 | Identifier::Orcid(value)
104 | Identifier::Ror(value)
105 | Identifier::Crossref(value)
106 | Identifier::Other { value, .. } => value,
107 }
108 }
109
110 pub fn as_doi(&self) -> Option<&str> {
116 match self {
117 Identifier::Doi(doi) => Some(doi),
118 _ => None,
119 }
120 }
121
122 pub fn parse_bag(bag: &str) -> Result<Vec<Identifier>> {
129 bag.split_whitespace().map(Identifier::from_str).collect()
130 }
131}
132
133impl FromStr for Identifier {
134 type Err = Error;
135
136 fn from_str(id: &str) -> Result<Self> {
137 let id = id.trim();
138 let Some((scheme, value)) = id.split_once(':') else {
139 return Err(Error::UnprefixedIdentifier {
140 given: id.to_string(),
141 });
142 };
143 if scheme.is_empty() {
144 return Err(Error::InvalidIdentifier {
145 given: id.to_string(),
146 why: "it has no scheme before the `:`",
147 });
148 }
149 if value.is_empty() {
150 return Err(Error::InvalidIdentifier {
151 given: id.to_string(),
152 why: "it has no value after the `:`",
153 });
154 }
155
156 let value = value.to_string();
157 Ok(match scheme.to_ascii_lowercase().as_str() {
158 "doi" => Identifier::Doi(value),
159 "pmid" => Identifier::Pmid(value),
160 "pmcid" => Identifier::Pmcid(value),
161 "omid" => Identifier::Omid(value),
162 "issn" => Identifier::Issn(value),
163 "isbn" => Identifier::Isbn(value),
164 "openalex" => Identifier::OpenAlex(value),
165 "orcid" => Identifier::Orcid(value),
166 "ror" => Identifier::Ror(value),
167 "crossref" => Identifier::Crossref(value),
168 other => Identifier::Other {
169 scheme: other.to_string(),
170 value,
171 },
172 })
173 }
174}
175
176impl fmt::Display for Identifier {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 write!(f, "{}:{}", self.scheme(), self.value())
179 }
180}
181
182impl Serialize for Identifier {
183 fn serialize<S: serde::Serializer>(
184 &self,
185 serializer: S,
186 ) -> std::result::Result<S::Ok, S::Error> {
187 serializer.collect_str(self)
188 }
189}
190
191impl<'de> Deserialize<'de> for Identifier {
192 fn deserialize<D: serde::Deserializer<'de>>(
193 deserializer: D,
194 ) -> std::result::Result<Self, D::Error> {
195 let raw = String::deserialize(deserializer)?;
196 Identifier::from_str(&raw).map_err(serde::de::Error::custom)
197 }
198}
199
200#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
207pub struct Oci {
208 citing: String,
209 cited: String,
210}
211
212impl Oci {
213 pub fn citing(&self) -> &str {
215 &self.citing
216 }
217
218 pub fn cited(&self) -> &str {
220 &self.cited
221 }
222}
223
224impl FromStr for Oci {
225 type Err = Error;
226
227 fn from_str(oci: &str) -> Result<Self> {
228 let bare = oci.trim().strip_prefix("oci:").unwrap_or(oci.trim());
231
232 let Some((citing, cited)) = bare.split_once('-') else {
233 return Err(Error::InvalidOci {
234 given: oci.to_string(),
235 why: "it is two omids joined by a `-`",
236 });
237 };
238 let numeric = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
239 if !numeric(citing) || !numeric(cited) {
240 return Err(Error::InvalidOci {
241 given: oci.to_string(),
242 why: "both halves are numbers",
243 });
244 }
245
246 Ok(Oci {
247 citing: citing.to_string(),
248 cited: cited.to_string(),
249 })
250 }
251}
252
253impl fmt::Display for Oci {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 write!(f, "{}-{}", self.citing, self.cited)
256 }
257}
258
259impl Serialize for Oci {
260 fn serialize<S: serde::Serializer>(
261 &self,
262 serializer: S,
263 ) -> std::result::Result<S::Ok, S::Error> {
264 serializer.collect_str(self)
265 }
266}
267
268impl<'de> Deserialize<'de> for Oci {
269 fn deserialize<D: serde::Deserializer<'de>>(
270 deserializer: D,
271 ) -> std::result::Result<Self, D::Error> {
272 let raw = String::deserialize(deserializer)?;
273 Oci::from_str(&raw).map_err(serde::de::Error::custom)
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280
281 #[test]
282 fn an_identifier_keeps_its_scheme_and_value() {
283 let id: Identifier = "doi:10.1016/j.marpol.2021.104855".parse().unwrap();
284 assert_eq!(id, Identifier::doi("10.1016/j.marpol.2021.104855"));
285 assert_eq!(id.scheme(), "doi");
286 assert_eq!(id.value(), "10.1016/j.marpol.2021.104855");
287 assert_eq!(id.as_doi(), Some("10.1016/j.marpol.2021.104855"));
288 assert_eq!(id.to_string(), "doi:10.1016/j.marpol.2021.104855");
289 }
290
291 #[test]
294 fn only_the_first_colon_separates() {
295 let omid: Identifier = "omid:br/06220256775".parse().unwrap();
296 assert_eq!(omid, Identifier::omid("br/06220256775"));
297
298 let url: Identifier = "url:https://example.com/a".parse().unwrap();
299 assert_eq!(url.value(), "https://example.com/a");
300 }
301
302 #[test]
306 fn an_unprefixed_identifier_is_refused_with_the_form_it_should_take() {
307 let err = "10.1016/j.marpol.2021.104855"
308 .parse::<Identifier>()
309 .unwrap_err();
310 assert!(err.to_string().contains("doi:10.1016"), "{err}");
311
312 assert!("doi:".parse::<Identifier>().is_err());
313 assert!(":10.1016".parse::<Identifier>().is_err());
314 }
315
316 #[test]
317 fn an_unknown_scheme_is_kept_rather_than_refused() {
318 let id: Identifier = "wikidata:Q42".parse().unwrap();
319 assert_eq!(id.scheme(), "wikidata");
320 assert_eq!(id.value(), "Q42");
321 assert_eq!(id.as_doi(), None);
322 }
323
324 #[test]
325 fn a_bag_of_identifiers_reads_as_all_of_them() {
326 let bag = Identifier::parse_bag(
327 "omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
328 )
329 .unwrap();
330
331 assert_eq!(bag.len(), 3);
332 assert_eq!(
333 bag.iter().find_map(Identifier::as_doi),
334 Some("10.1016/j.marpol.2021.104855")
335 );
336 }
337
338 #[test]
339 fn an_oci_is_the_two_omids_it_joins() {
340 let oci: Oci = "06024047477-06220256775".parse().unwrap();
341 assert_eq!(oci.citing(), "06024047477");
342 assert_eq!(oci.cited(), "06220256775");
343 assert_eq!(oci.to_string(), "06024047477-06220256775");
344
345 assert_eq!("oci:06024047477-06220256775".parse::<Oci>().unwrap(), oci);
347 }
348
349 #[test]
350 fn something_that_is_not_an_oci_is_refused() {
351 assert!("06024047477".parse::<Oci>().is_err());
352 assert!("abc-def".parse::<Oci>().is_err());
353 assert!("-06220256775".parse::<Oci>().is_err());
354 }
355}