use crate::types::{AnnotationBodies, AnnotationId, Motivation, ResourceId};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ring::digest::{SHA256, digest};
use serde_json::{Value, json};
const DIGITS: usize = 21;
fn write_string(string: &str, into: &mut String) {
into.push('"');
for character in string.chars() {
match character {
'"' => into.push_str("\\\""),
'\\' => into.push_str("\\\\"),
'\u{8}' => into.push_str("\\b"),
'\t' => into.push_str("\\t"),
'\n' => into.push_str("\\n"),
'\u{c}' => into.push_str("\\f"),
'\r' => into.push_str("\\r"),
below if below < '\u{20}' => into.push_str(&format!("\\u{:04x}", u32::from(below))),
itself => into.push(itself),
}
}
into.push('"');
}
fn write(value: &Value, into: &mut String) {
match value {
Value::Null => into.push_str("null"),
Value::Bool(true) => into.push_str("true"),
Value::Bool(false) => into.push_str("false"),
Value::Number(number) => into.push_str(&number.to_string()),
Value::String(string) => write_string(string, into),
Value::Array(items) => {
into.push('[');
for (nth, item) in items.iter().enumerate() {
if nth > 0 {
into.push(',');
}
write(item, into);
}
into.push(']');
}
Value::Object(members) => {
let mut members: Vec<(&String, &Value)> = members.iter().collect();
members.sort_unstable_by_key(|(name, _)| *name);
into.push('{');
for (nth, (name, member)) in members.into_iter().enumerate() {
if nth > 0 {
into.push(',');
}
write_string(name, into);
into.push(':');
write(member, into);
}
into.push('}');
}
}
}
fn derived_id(resource_id: &str, motivation: &str, anchor: &str, body: Option<&Value>) -> String {
let mut what = json!({ "resourceId": resource_id, "motivation": motivation, "anchor": anchor });
if let Some(body) = body {
what["body"] = body.clone();
}
let mut canonical = String::new();
write(&what, &mut canonical);
let mut digits = URL_SAFE_NO_PAD.encode(digest(&SHA256, canonical.as_bytes()));
digits.truncate(DIGITS);
digits
}
pub(crate) fn annotation_id(
resource_id: &ResourceId,
motivation: Motivation,
anchor: &str,
body: Option<&AnnotationBodies>,
) -> AnnotationId {
let body = body.map(|body| match serde_json::to_value(body) {
Ok(written) => written,
Err(refused) => unreachable!("a body is written as JSON: {refused}"),
});
let digits = derived_id(resource_id, motivation.as_str(), anchor, body.as_ref());
match AnnotationId::new(digits) {
Ok(id) => id,
Err(refused) => unreachable!("21 base64url digits are an annotation's id: {refused}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_annotation_of_the_table_has_the_id_the_table_says() {
let table: Value =
serde_json::from_str(include_str!("../../specs/annotations/id-cases.json"))
.expect("the table is JSON");
let cases = table["cases"].as_array().expect("cases");
assert!(!cases.is_empty());
let (mut with_a_body, mut with_none) = (0, 0);
for case in cases {
let why = case["why"].as_str().expect("why");
let stated = |member: &str| {
case[member]
.as_str()
.unwrap_or_else(|| panic!("{why}: no {member}"))
};
let body = case.get("body");
assert_eq!(
derived_id(
stated("resourceId"),
stated("motivation"),
stated("anchor"),
body
),
stated("id"),
"{why}"
);
let typed: Option<AnnotationBodies> = match body {
None => None,
Some(body) => match serde_json::from_value(body.clone()) {
Ok(typed) if serde_json::to_value(&typed).ok().as_ref() == Some(body) => {
Some(typed)
}
_ => continue,
},
};
let resource: ResourceId = stated("resourceId").parse().expect("a resource's id");
let motivation: Motivation =
serde_json::from_value(case["motivation"].clone()).expect("a motivation");
assert_eq!(
annotation_id(&resource, motivation, stated("anchor"), typed.as_ref()),
stated("id"),
"{why}: given as this crate's types"
);
match typed {
Some(_) => with_a_body += 1,
None => with_none += 1,
}
}
assert!(with_a_body > 0 && with_none > 0);
}
}