use indicatrix_net::library::DesignSummary;
use indicatrix_vault::db::sqlite::Database;
use sha2::{Digest, Sha256};
fn hash_str(hasher: &mut Sha256, s: &str) {
hasher.update((s.len() as u64).to_le_bytes());
hasher.update(s.as_bytes());
}
fn hash_opt_str(hasher: &mut Sha256, s: Option<&str>) {
match s {
Some(s) => {
hasher.update([1u8]);
hash_str(hasher, s);
}
None => hasher.update([0u8]),
}
}
pub(super) fn hash_summary(s: &DesignSummary) -> [u8; 32] {
let mut hasher = Sha256::new();
hash_str(&mut hasher, &s.title);
hash_str(&mut hasher, &s.url);
hash_opt_str(&mut hasher, s.design_id.as_deref());
hash_opt_str(&mut hasher, s.shape.as_deref());
hash_opt_str(&mut hasher, s.index_gear.as_deref());
hash_opt_str(&mut hasher, s.facets_count.as_deref());
hash_opt_str(&mut hasher, s.designer_info.as_deref());
hash_opt_str(&mut hasher, s.lw_ratio.as_deref());
hash_opt_str(&mut hasher, s.refractive_index.as_deref());
hash_opt_str(&mut hasher, s.volume.as_deref());
hash_opt_str(&mut hasher, s.competition_diagram.as_deref());
hasher.update([u8::from(s.ignored)]);
hasher.finalize().into()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Revision {
Stamped(Option<i64>),
Unreadable,
}
impl Revision {
pub(super) fn read(db: &Database, entry_id: i64) -> Self {
match db.entry_updated_at(entry_id) {
Ok(stamp) => Self::Stamped(stamp),
Err(e) => {
tracing::debug!("library: no readable revision stamp for entry {entry_id}: {e:#}");
Self::Unreadable
}
}
}
}
pub(super) fn revision_token(url: &str, revision: Revision) -> [u8; 32] {
let Revision::Stamped(stamp) = revision else {
return [0u8; 32];
};
let mut hasher = Sha256::new();
hash_str(&mut hasher, "indicatrix/design-revision/1");
hash_str(&mut hasher, url);
match stamp {
Some(t) => {
hasher.update([1u8]);
hasher.update(t.to_le_bytes());
}
None => hasher.update([0u8]),
}
hasher.finalize().into()
}
#[cfg(test)]
mod tests {
use super::{Revision, revision_token};
#[test]
fn the_token_follows_the_url_and_the_stamp_only() {
let a = revision_token("https://example.test/1", Revision::Stamped(Some(100)));
assert_eq!(
a,
revision_token("https://example.test/1", Revision::Stamped(Some(100)))
);
assert_ne!(
a,
revision_token("https://example.test/1", Revision::Stamped(Some(101)))
);
assert_ne!(
a,
revision_token("https://example.test/2", Revision::Stamped(Some(100)))
);
assert_ne!(
revision_token("https://example.test/1", Revision::Stamped(None)),
revision_token("https://example.test/1", Revision::Stamped(Some(0)))
);
assert_ne!(a, [0u8; 32]);
}
#[test]
fn an_unreadable_revision_is_the_all_zero_token() {
assert_eq!(
revision_token("https://example.test/1", Revision::Unreadable),
[0u8; 32]
);
}
}