Skip to main content

opencitations_client/
id.rs

1//! The prefixed identifiers OpenCitations addresses everything by.
2//!
3//! Every id in both apis is written `scheme:value` -- `doi:10.1016/j.marpol.2021.104855`,
4//! `pmid:22683049`, `omid:br/06220256775` -- and a work is usually known by
5//! several at once, which is why the `citing`, `cited` and `id` fields arrive
6//! as a space-separated bag of them rather than as one string.
7
8use crate::error::{Error, Result};
9use serde::{Deserialize, Serialize};
10use std::fmt;
11use std::str::FromStr;
12
13/// One identifier of a bibliographic entity, in the `scheme:value` form
14/// OpenCitations writes.
15///
16/// The known schemes get a variant of their own so a caller can match on them;
17/// anything else is kept verbatim in [`Identifier::Other`] rather than being
18/// refused, because OpenCitations adds sources over time and an id this crate
19/// has not heard of is still an id worth passing back.
20#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
21#[non_exhaustive]
22pub enum Identifier {
23    /// a DOI, e.g. `doi:10.1016/j.marpol.2021.104855`
24    Doi(String),
25    /// a PubMed id, e.g. `pmid:22683049`
26    Pmid(String),
27    /// a PubMed Central id, e.g. `pmcid:PMC3339580`
28    Pmcid(String),
29    /// an OpenCitations Meta id, e.g. `omid:br/06220256775` for a work or
30    /// `omid:ra/06220760311` for an agent
31    Omid(String),
32    /// an ISSN, which identifies a venue rather than a work
33    Issn(String),
34    /// an ISBN
35    Isbn(String),
36    /// an OpenAlex id, e.g. `openalex:W3214241825`
37    OpenAlex(String),
38    /// an ORCID, which identifies a person rather than a work; Meta credits
39    /// authors by one where it has it
40    Orcid(String),
41    /// a ROR id, which identifies an institution
42    Ror(String),
43    /// a Crossref member id, e.g. `crossref:78`
44    Crossref(String),
45    /// a scheme this crate does not know, kept as it arrived
46    Other {
47        /// the scheme, lowercased
48        scheme: String,
49        /// everything after the first `:`
50        value: String,
51    },
52}
53
54impl Identifier {
55    /// A DOI identifier. The `doi:` prefix is added, not expected.
56    pub fn doi(doi: impl Into<String>) -> Self {
57        Identifier::Doi(doi.into())
58    }
59
60    /// A PubMed identifier. The `pmid:` prefix is added, not expected.
61    pub fn pmid(pmid: impl Into<String>) -> Self {
62        Identifier::Pmid(pmid.into())
63    }
64
65    /// An OpenCitations Meta identifier. The `omid:` prefix is added, not
66    /// expected, so this takes the `br/06220256775` half.
67    pub fn omid(omid: impl Into<String>) -> Self {
68        Identifier::Omid(omid.into())
69    }
70
71    /// An ISSN, which is how a venue is addressed.
72    pub fn issn(issn: impl Into<String>) -> Self {
73        Identifier::Issn(issn.into())
74    }
75
76    /// The scheme, lowercased: `doi`, `pmid`, `omid`, ...
77    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    /// Everything after the scheme, without the `:`.
94    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    /// The DOI, when this is one.
111    ///
112    /// The usual reason to reach into a `citing` or `cited` bag: a DOI is what
113    /// another api -- crossref, a bibliography, a reference manager -- can be
114    /// asked about next.
115    pub fn as_doi(&self) -> Option<&str> {
116        match self {
117            Identifier::Doi(doi) => Some(doi),
118            _ => None,
119        }
120    }
121
122    /// Reads the space-separated bag of identifiers OpenCitations writes into
123    /// its `citing`, `cited` and `id` fields.
124    ///
125    /// An id in the list that cannot be read stops the whole list, because a
126    /// silently shortened bag is indistinguishable from a work that is known by
127    /// fewer identifiers.
128    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/// An Open Citation Identifier: the citing and cited work's OMIDs, joined by a
201/// `-`, naming one citation.
202///
203/// `06024047477-06220256775` is the citation *from* `omid:br/06024047477` *to*
204/// `omid:br/06220256775`, and is the only thing `/index/v2/citation/{oci}`
205/// takes.
206#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
207pub struct Oci {
208    citing: String,
209    cited: String,
210}
211
212impl Oci {
213    /// The OMID of the citing work, without its `omid:br/` prefix.
214    pub fn citing(&self) -> &str {
215        &self.citing
216    }
217
218    /// The OMID of the cited work, without its `omid:br/` prefix.
219    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        // written `oci:0610-0620` in some of OpenCitations' own documentation,
229        // but the route takes it bare, so accept either and send the bare form
230        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    /// An omid's value carries a `/`, and a doi's carries several -- only the
292    /// first `:` separates.
293    #[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    /// A bare doi is refused rather than guessed at: OpenCitations answers an
303    /// identifier it cannot parse the same way it answers one it has never
304    /// heard of, so a guess would read as "nobody has cited this".
305    #[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        // the documented `oci:` prefix is accepted, and dropped
346        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}