use crate::core::hash::{
HANDLE_ABI_STAMP_KEY, compute_file_hash, extract_hash, extract_stamp, inject_hash_line, strip_hash_line,
};
use crate::core::template_versions::abi::HANDLE_ABI_VERSION;
pub(crate) fn assert_stamped_before_hashing(content: &str, what: &str) {
assert_eq!(
extract_stamp(content, HANDLE_ABI_STAMP_KEY).as_deref(),
Some(HANDLE_ABI_VERSION),
"{what}: emitted content must carry `alef:{HANDLE_ABI_STAMP_KEY}:{HANDLE_ABI_VERSION}`"
);
let body = strip_hash_line(content);
assert!(
body.contains(&format!("alef:{HANDLE_ABI_STAMP_KEY}:{HANDLE_ABI_VERSION}")),
"{what}: the stamp must survive hash-line stripping, i.e. be part of the hashed body"
);
let finalized = inject_hash_line(&body, &compute_file_hash(&body));
assert_eq!(
extract_stamp(&finalized, HANDLE_ABI_STAMP_KEY).as_deref(),
Some(HANDLE_ABI_VERSION),
"{what}: the stamp must stay extractable once the hash line is injected above it"
);
assert_eq!(
extract_hash(&finalized),
Some(compute_file_hash(&strip_hash_line(&finalized))),
"{what}: the embedded hash must re-verify over the stamped content"
);
}
#[cfg(test)]
mod tests {
use super::*;
fn headered(body: &str) -> String {
format!("// This file is auto-generated by alef. DO NOT EDIT.\n{body}")
}
#[test]
fn accepts_content_stamped_before_hashing() {
let stamped = inject_stamped(&headered("fn main() {}\n"));
assert_stamped_before_hashing(&stamped, "fixture");
}
#[test]
#[should_panic(expected = "must carry")]
fn rejects_unstamped_content() {
assert_stamped_before_hashing(&headered("fn main() {}\n"), "fixture");
}
#[test]
fn stamping_after_the_hash_line_hides_the_hash_from_verify() {
let unstamped = headered("fn main() {}\n");
let hashed = inject_hash_line(&unstamped, &compute_file_hash(&unstamped));
assert!(extract_hash(&hashed).is_some(), "control: hashing alone is readable");
assert_eq!(
extract_hash(&inject_stamped(&hashed)),
None,
"a stamp injected after the hash line pushes it out of the marker-adjacent slot"
);
}
fn inject_stamped(content: &str) -> String {
crate::core::hash::inject_stamp_line(content, HANDLE_ABI_STAMP_KEY, HANDLE_ABI_VERSION)
}
}