use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CnFormat {
RdfXml,
Turtle,
CiteProcJson,
CiteProcJsonIsh,
Ris,
BibTex,
CrossrefXml,
CrossrefTdm,
Bibliography {
style: String,
locale: Option<String>,
},
}
impl CnFormat {
pub fn bibliography(style: impl Into<String>) -> Self {
CnFormat::Bibliography {
style: style.into(),
locale: None,
}
}
pub fn accept(&self) -> Cow<'_, str> {
let simple = match self {
CnFormat::RdfXml => "application/rdf+xml",
CnFormat::Turtle => "text/turtle",
CnFormat::CiteProcJson => "application/vnd.citationstyles.csl+json",
CnFormat::CiteProcJsonIsh => "application/citeproc+json",
CnFormat::Ris => "application/x-research-info-systems",
CnFormat::BibTex => "application/x-bibtex",
CnFormat::CrossrefXml => "application/vnd.crossref.unixref+xml",
CnFormat::CrossrefTdm => "application/vnd.crossref.unixsd+xml",
CnFormat::Bibliography { style, locale } => {
let mut accept = format!("text/x-bibliography; style={style}");
if let Some(locale) = locale {
accept.push_str("; locale=");
accept.push_str(locale);
}
return Cow::Owned(accept);
}
};
Cow::Borrowed(simple)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn one_of_each() -> Vec<CnFormat> {
vec![
CnFormat::RdfXml,
CnFormat::Turtle,
CnFormat::CiteProcJson,
CnFormat::CiteProcJsonIsh,
CnFormat::Ris,
CnFormat::BibTex,
CnFormat::CrossrefXml,
CnFormat::CrossrefTdm,
CnFormat::bibliography("apa"),
]
}
#[test]
fn no_two_formats_ask_for_the_same_thing() {
let mut accepts: Vec<_> = one_of_each()
.iter()
.map(|f| f.accept().to_string())
.collect();
let total = accepts.len();
accepts.sort();
accepts.dedup();
assert_eq!(
total,
accepts.len(),
"duplicate `Accept` values: {accepts:?}"
);
}
#[test]
fn a_style_and_locale_become_accept_parameters() {
assert_eq!(
"text/x-bibliography; style=apa",
CnFormat::bibliography("apa").accept()
);
assert_eq!(
"text/x-bibliography; style=apa; locale=de-DE",
CnFormat::Bibliography {
style: "apa".to_string(),
locale: Some("de-DE".to_string()),
}
.accept()
);
}
}