#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::Path;
use std::sync::Arc;
use embedmind_core::api::{MemoryDraft, Store, StoreOptions};
use embedmind_core::storage::sim::SimVfs;
use embedmind_core::storage::vfs::Vfs;
const STORE: &str = "memory.mind";
const OFF_MAGIC: usize = 0;
const OFF_FORMAT_VERSION: usize = 8;
const OFF_PAGE_SIZE: usize = 12;
const OFF_PAGE_COUNT: usize = 16;
const OFF_FTS_ROOT: usize = 156;
const MAGIC: &[u8; 8] = b"MINDFMT1";
fn header_bytes() -> Vec<u8> {
let sim = Arc::new(SimVfs::new());
let vfs: Arc<dyn Vfs> = Arc::clone(&sim) as Arc<dyn Vfs>;
let opts = StoreOptions {
page_size: 4096,
..StoreOptions::default()
};
let mut store = Store::create_with(vfs, Path::new(STORE), opts).unwrap();
store
.remember(MemoryDraft::new("portable memory one"))
.unwrap();
store
.remember(MemoryDraft::new("portable memory two"))
.unwrap();
store.close().unwrap();
let snapshot = sim
.snapshot(Path::new(STORE))
.expect("store file exists in the VFS");
assert!(
snapshot.len() >= 4096,
"page 0 must be a full page: got {} bytes",
snapshot.len()
);
snapshot
}
fn le_u32(bytes: &[u8], off: usize) -> u32 {
u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap())
}
fn le_u64(bytes: &[u8], off: usize) -> u64 {
u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap())
}
#[test]
fn header_is_fixed_little_endian_per_format_spec() {
let header = header_bytes();
assert_eq!(
&header[OFF_MAGIC..OFF_MAGIC + 8],
MAGIC,
"magic must be ASCII MINDFMT1 at offset 0 (FORMAT §4)"
);
assert_eq!(
&header[OFF_FORMAT_VERSION..OFF_FORMAT_VERSION + 4],
&[0x08, 0x00, 0x00, 0x00],
"format_version must be little-endian 8"
);
assert_eq!(le_u32(&header, OFF_FORMAT_VERSION), 8);
assert_eq!(
&header[OFF_PAGE_SIZE..OFF_PAGE_SIZE + 4],
&[0x00, 0x10, 0x00, 0x00],
"page_size must be little-endian 4096"
);
assert_eq!(le_u32(&header, OFF_PAGE_SIZE), 4096);
let page_count = le_u64(&header, OFF_PAGE_COUNT);
assert!(
(2..1024).contains(&page_count),
"page_count read little-endian must be a small sane value, got {page_count}"
);
let fts_root = le_u64(&header, OFF_FTS_ROOT);
assert!(
(2..1024).contains(&fts_root),
"fts_root_page read little-endian must be a small sane page number, got {fts_root}"
);
}
#[test]
fn written_store_reopens_with_identical_content() {
let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
let opts = StoreOptions {
page_size: 4096,
..StoreOptions::default()
};
let mut store = Store::create_with(Arc::clone(&vfs), Path::new(STORE), opts.clone()).unwrap();
let id = store
.remember(MemoryDraft::new("survives a reopen unchanged").project("portability"))
.unwrap()
.id;
store.close().unwrap();
let store = Store::open_with(Arc::clone(&vfs), Path::new(STORE), opts).unwrap();
let got = store.get(id).unwrap().expect("memory must survive reopen");
assert_eq!(got.content, "survives a reopen unchanged");
assert_eq!(got.project.as_deref(), Some("portability"));
}