use std::fmt::Display;
pub(crate) fn fingerprint(text: &str) -> String {
let mut value = 0xcbf29ce484222325u64;
for byte in text.bytes() {
value ^= u64::from(byte);
value = value.wrapping_mul(0x100000001b3);
}
format!("{value:016x}")
}
pub(crate) fn is_fingerprint(value: &str) -> bool {
value.len() == 16
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
pub(crate) fn open_header([schema, kind, engine]: [&str; 3]) -> String {
let mut output = String::from("{\"schema\":");
push_ascii(&mut output, schema);
output.push_str(",\"kind\":");
push_ascii(&mut output, kind);
output.push_str(",\"engine\":");
push_ascii(&mut output, engine);
output
}
pub(crate) fn seal(mut body: String, fingerprint: &str) -> String {
body.push_str(",\"fingerprint\":\"");
body.push_str(fingerprint);
body.push_str("\"}");
body
}
pub(crate) fn push_list<T>(
output: &mut String,
items: &[T],
mut push_item: impl FnMut(&mut String, &T),
) {
output.push('[');
for (index, item) in items.iter().enumerate() {
if index != 0 {
output.push(',');
}
push_item(output, item);
}
output.push(']');
}
pub(crate) fn push_numbers<T: Display>(output: &mut String, values: &[T]) {
push_list(output, values, |output, value| {
output.push_str(&value.to_string());
});
}
pub(crate) fn push_number_object<T: Display>(output: &mut String, fields: &[(&str, T)]) {
output.push('{');
for (index, (key, value)) in fields.iter().enumerate() {
if index != 0 {
output.push(',');
}
output.push('"');
output.push_str(key);
output.push_str("\":");
output.push_str(&value.to_string());
}
output.push('}');
}
pub(crate) fn push_number_fields<T: Display>(output: &mut String, fields: &[(&str, T)]) {
for (key, value) in fields {
output.push_str(",\"");
output.push_str(key);
output.push_str("\":");
output.push_str(&value.to_string());
}
}
pub(crate) fn push_tagged_numbers<T: Display>(
output: &mut String,
kind: &str,
fields: &[(&str, T)],
) {
output.push_str("{\"kind\":");
push_ascii(output, kind);
push_number_fields(output, fields);
output.push('}');
}
pub(crate) fn push_escaped(output: &mut String, bytes: &[u8]) {
output.push('"');
for &byte in bytes {
if matches!(byte, b'"' | b'\\') {
output.push('\\');
}
output.push(byte as char);
}
output.push('"');
}
pub(crate) fn push_ascii(output: &mut String, value: &str) {
assert!(
value
.bytes()
.all(|byte| (0x20..=0x7e).contains(&byte) && byte != b'"' && byte != b'\\'),
"portable strings must be printable ASCII without quotes or backslashes"
);
output.push('"');
output.push_str(value);
output.push('"');
}