use crate::bson::{self, ARRAY, DOCUMENT, STRING};
use crate::error::{Error, Result};
pub const ID_KEYS: [&str; 3] = ["ID", "Persistent-ID", "persistent-ID"];
pub fn is_id_key(key: &str) -> bool {
ID_KEYS.contains(&key)
}
pub fn new_guid() -> Result<String> {
let mut b = [0u8; 16];
getrandom::getrandom(&mut b).map_err(|e| Error::Invalid(format!("random: {e}")))?;
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
Ok(format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
))
}
pub fn visit_defined<'a>(buf: &'a [u8], doc_off: usize, f: &mut impl FnMut(&'a str)) -> Result<()> {
for el in bson::elements(buf, doc_off)? {
if el.ty == STRING && is_id_key(el.key) {
f(bson::decode_string(el.value)?);
} else if el.ty == DOCUMENT || el.ty == ARRAY {
visit_defined(buf, el.value_at, f)?;
}
}
Ok(())
}
pub fn visit_strings<'a>(buf: &'a [u8], doc_off: usize, f: &mut impl FnMut(&'a str)) -> Result<()> {
for el in bson::elements(buf, doc_off)? {
if el.ty == STRING {
if !is_id_key(el.key) {
f(bson::decode_string(el.value)?);
}
} else if el.ty == DOCUMENT || el.ty == ARRAY {
visit_strings(buf, el.value_at, f)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guid_is_dashed_version_four() {
let id = new_guid().unwrap();
assert_eq!(id.len(), 36);
let parts: Vec<&str> = id.split('-').collect();
assert_eq!(
parts.iter().map(|p| p.len()).collect::<Vec<_>>(),
vec![8, 4, 4, 4, 12]
);
assert!(parts[2].starts_with('4'));
assert!(matches!(&parts[3][..1], "8" | "9" | "a" | "b"));
assert!(id
.chars()
.all(|c| c == '-' || c.is_ascii_digit() || ('a'..='f').contains(&c)));
}
}