use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
#[cfg(any(test, feature = "failpoints"))]
pub(crate) mod failpoints {
use std::cell::Cell;
thread_local! {
static WRITES_UNTIL_FAIL: Cell<i64> = const { Cell::new(-1) };
static FAILS_LEFT: Cell<u32> = const { Cell::new(1) };
static WRITES_SEEN: Cell<u64> = const { Cell::new(0) };
static FAILING: std::cell::RefCell<Vec<u64>> = const { std::cell::RefCell::new(Vec::new()) };
}
pub fn set_writes_failing(ns: &[u64]) {
WRITES_SEEN.with(|c| c.set(0));
FAILING.with(|f| *f.borrow_mut() = ns.to_vec());
}
pub fn writes_seen() -> u64 {
WRITES_SEEN.with(|c| c.get())
}
pub fn set_writes_until_fail(n: i64) {
WRITES_UNTIL_FAIL.with(|c| c.set(n));
FAILS_LEFT.with(|c| c.set(1));
}
pub fn set_writes_until_fail_n(n: i64, count: u32) {
WRITES_UNTIL_FAIL.with(|c| c.set(n));
FAILS_LEFT.with(|c| c.set(count.max(1)));
}
pub(crate) fn check() -> std::io::Result<()> {
let n = WRITES_SEEN.with(|c| {
let n = c.get();
c.set(n + 1);
n
});
if FAILING.with(|f| f.borrow().contains(&n)) {
return Err(std::io::Error::other(
"injected crash (REKEY-2 failpoint set)",
));
}
WRITES_UNTIL_FAIL.with(|c| {
let v = c.get();
if v == 0 {
let left = FAILS_LEFT.with(|f| f.get());
if left > 1 {
FAILS_LEFT.with(|f| f.set(left - 1));
} else {
c.set(-1);
}
Err(std::io::Error::other(
"injected crash (Phase 1.3 failpoint)",
))
} else if v > 0 {
c.set(v - 1);
Ok(())
} else {
Ok(())
}
})
}
}
#[cfg(not(any(test, feature = "failpoints")))]
#[inline(always)]
pub(crate) fn __failpoint_check() -> std::io::Result<()> {
Ok(())
}
#[cfg(any(test, feature = "failpoints"))]
#[inline(always)]
pub(crate) fn __failpoint_check() -> std::io::Result<()> {
failpoints::check()
}
use zeroize::Zeroizing;
use crate::cache::PageCache;
use crate::crypto::{self, KEY_LEN, NONCE_LEN};
use crate::error::{MnemoError, Result};
use crate::format::{PAGE_SIZE, PAYLOAD};
pub const PARALLEL_DECRYPT_MIN_PAGES: usize = 64;
const STREAM_PAGES: usize = 15;
pub(crate) struct PageBatch {
disk: Vec<u8>,
slots: Vec<Slot>,
}
enum Slot {
Disk(usize),
Cached(Vec<u8>),
}
impl PageBatch {
pub(crate) fn payload(&self, i: usize) -> &[u8] {
match &self.slots[i] {
Slot::Disk(j) => {
let at = j * PAGE_SIZE + NONCE_LEN;
&self.disk[at..at + PAYLOAD]
}
Slot::Cached(v) => v,
}
}
pub(crate) fn len(&self) -> usize {
self.slots.len()
}
pub(crate) fn into_images(self) -> Vec<u8> {
let in_place = self
.slots
.iter()
.enumerate()
.all(|(i, s)| matches!(s, Slot::Disk(j) if *j == i));
if in_place {
return self.disk;
}
let mut out = vec![0u8; self.slots.len() * PAGE_SIZE];
for i in 0..self.slots.len() {
let at = i * PAGE_SIZE + NONCE_LEN;
out[at..at + PAYLOAD].copy_from_slice(self.payload(i));
}
out
}
}
fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::FileExt;
file.read_exact_at(buf, offset)
}
#[cfg(windows)]
{
use std::os::windows::fs::FileExt;
let mut done = 0;
while done < buf.len() {
match file.seek_read(&mut buf[done..], offset + done as u64) {
Ok(0) => {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"failed to fill whole buffer",
))
}
Ok(n) => done += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
}
pub(crate) struct LockedFile(File);
impl LockedFile {
pub(crate) fn new(file: File) -> Self {
Self(file)
}
}
impl std::ops::Deref for LockedFile {
type Target = File;
fn deref(&self) -> &File {
&self.0
}
}
impl std::ops::DerefMut for LockedFile {
fn deref_mut(&mut self) -> &mut File {
&mut self.0
}
}
impl Drop for LockedFile {
fn drop(&mut self) {
let _ = fs4::fs_std::FileExt::unlock(&self.0);
}
}
pub const DEFAULT_CACHE_PAGES: usize = 1024;
pub const V9_DEFAULT_CACHE_PAGES: usize = 256;
const DETACHED: &str = "the brain's file isn't open outside a shared-mode call";
pub struct Pager {
file: Option<LockedFile>,
dek: Zeroizing<[u8; KEY_LEN]>,
pub write_counter: u64,
session_random: u64,
session_counter: u32,
version: u16,
cache: PageCache,
dirty_gens: std::collections::HashMap<u64, u64>,
}
impl Pager {
pub(crate) fn new(
file: LockedFile,
dek: Zeroizing<[u8; KEY_LEN]>,
write_counter: u64,
version: u16,
) -> Self {
Self {
file: Some(file),
dek,
write_counter,
session_random: crypto::random_u64(),
session_counter: 0,
version,
cache: PageCache::new(if version >= crate::format::VERSION_V9 {
V9_DEFAULT_CACHE_PAGES
} else {
DEFAULT_CACHE_PAGES
}),
dirty_gens: std::collections::HashMap::new(),
}
}
fn next_nonce(&mut self) -> [u8; NONCE_LEN] {
if self.session_counter == u32::MAX {
self.session_random = crypto::random_u64();
self.session_counter = 0;
}
self.session_counter += 1;
crypto::session_page_nonce(self.session_random, self.session_counter)
}
pub(crate) fn set_version(&mut self, version: u16) {
self.version = version;
}
#[inline]
fn page_aad(&self, page_no: u64, gen: u64) -> Vec<u8> {
if self.version >= crate::format::VERSION_V9 {
let mut aad = Vec::with_capacity(16);
aad.extend_from_slice(&page_no.to_le_bytes());
aad.extend_from_slice(&gen.to_le_bytes());
aad
} else if self.version >= 6 {
page_no.to_le_bytes().to_vec()
} else {
Vec::new()
}
}
pub(crate) fn version(&self) -> u16 {
self.version
}
pub fn dek(&self) -> &[u8; KEY_LEN] {
&self.dek
}
pub fn file(&self) -> &File {
self.file.as_deref().expect(DETACHED)
}
pub fn file_mut(&mut self) -> &mut File {
self.file.as_deref_mut().expect(DETACHED)
}
fn f(&mut self) -> std::io::Result<&mut File> {
self.file
.as_deref_mut()
.ok_or_else(|| std::io::Error::other(DETACHED))
}
pub(crate) fn attach_file(&mut self, file: LockedFile) {
self.file = Some(file);
}
pub(crate) fn detach_file(&mut self) -> Option<LockedFile> {
self.file.take()
}
pub fn set_cache_capacity(&mut self, pages: usize) {
self.cache.set_capacity(pages);
}
pub fn cache_stats(&self) -> (usize, usize) {
(self.cache.len(), self.cache.capacity())
}
pub fn write_raw(&mut self, page_no: u64, data: &[u8; PAGE_SIZE]) -> Result<()> {
__failpoint_check()?;
self.f()?
.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
self.f()?.write_all(data)?;
Ok(())
}
#[allow(dead_code)]
pub fn read_raw(&mut self, page_no: u64) -> Result<[u8; PAGE_SIZE]> {
let mut buf = [0u8; PAGE_SIZE];
self.f()?
.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
self.f()?.read_exact(&mut buf)?;
Ok(buf)
}
pub fn seal_page(&mut self, page_no: u64, gen: u64, payload: &[u8]) -> Result<[u8; PAGE_SIZE]> {
if payload.len() > PAYLOAD {
return Err(MnemoError::Invalid(format!(
"payload {} exceeds page capacity {}",
payload.len(),
PAYLOAD
)));
}
let mut padded = vec![0u8; PAYLOAD];
padded[..payload.len()].copy_from_slice(payload);
self.write_counter += 1;
let nonce = self.next_nonce();
let aad = self.page_aad(page_no, gen);
let ciphertext = crypto::aead_encrypt(&self.dek, &nonce, &padded, &aad)?;
let mut disk = [0u8; PAGE_SIZE];
disk[..NONCE_LEN].copy_from_slice(&nonce);
disk[NONCE_LEN..].copy_from_slice(&ciphertext);
self.cache.insert(page_no, padded, false);
Ok(disk)
}
pub fn write_sealed(&mut self, page_no: u64, bytes: &[u8; PAGE_SIZE]) -> Result<()> {
__failpoint_check()?;
self.f()?
.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
self.f()?.write_all(bytes)?;
Ok(())
}
pub fn sync(&mut self) -> Result<()> {
self.f()?.sync_all()?;
crate::bump_fsync();
Ok(())
}
pub fn read_page(&mut self, page_no: u64, gen: u64) -> Result<Vec<u8>> {
if let Some(p) = self.cache.get(page_no) {
return Ok(p);
}
let mut disk = [0u8; PAGE_SIZE];
self.f()?
.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
self.f()?.read_exact(&mut disk)?;
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&disk[0..NONCE_LEN]);
let ciphertext = &disk[NONCE_LEN..];
let aad = self.page_aad(page_no, gen);
let payload = crypto::aead_decrypt(&self.dek, &nonce, ciphertext, &aad)
.map_err(|_| MnemoError::PageAuthFailed(page_no))?;
self.cache.insert(page_no, payload.clone(), false);
Ok(payload)
}
pub fn read_page_uncached(&mut self, page_no: u64, gen: u64) -> Result<Vec<u8>> {
if let Some(p) = self.cache.peek(page_no) {
return Ok(p.to_vec());
}
let mut disk = [0u8; PAGE_SIZE];
self.f()?
.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
self.f()?.read_exact(&mut disk)?;
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&disk[0..NONCE_LEN]);
let aad = self.page_aad(page_no, gen);
crypto::aead_decrypt(&self.dek, &nonce, &disk[NONCE_LEN..], &aad)
.map_err(|_| MnemoError::PageAuthFailed(page_no))
}
pub(crate) fn read_pages_uncached(&mut self, pages: &[(u64, u64)]) -> Result<PageBatch> {
let threads = if pages.len() >= PARALLEL_DECRYPT_MIN_PAGES {
std::thread::available_parallelism().map_or(1, |n| n.get())
} else {
1
};
#[cfg(feature = "dev-hooks")]
let threads = std::env::var("MNEMO_DEV_DECRYPT_THREADS")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.map_or(threads, |cap| threads.min(cap.max(1)));
self.read_pages_with(pages, threads)
}
pub(crate) fn for_each_page(
&mut self,
pages: &[(u64, u64)],
sink: impl FnMut(usize, &[u8]) -> Result<()>,
) -> Result<()> {
self.for_each_page_with(pages, None, sink)
}
pub(crate) fn for_each_page_with(
&mut self,
pages: &[(u64, u64)],
threads: Option<usize>,
mut sink: impl FnMut(usize, &[u8]) -> Result<()>,
) -> Result<()> {
let mut todo: Vec<usize> = Vec::with_capacity(pages.len());
for (i, &(p, _)) in pages.iter().enumerate() {
match self.cache.peek(p) {
Some(c) => {
let c = c.to_vec();
sink(i, &c)?;
}
None => todo.push(i),
}
}
if todo.is_empty() {
return Ok(());
}
todo.sort_by_key(|&i| pages[i].0);
let auto = if todo.len() >= PARALLEL_DECRYPT_MIN_PAGES {
std::thread::available_parallelism().map_or(1, |n| n.get())
} else {
1
};
#[cfg(feature = "dev-hooks")]
let auto = std::env::var("MNEMO_DEV_DECRYPT_THREADS")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.map_or(auto, |cap| auto.min(cap.max(1)));
let threads = threads
.unwrap_or(auto)
.clamp(1, todo.len().div_ceil(STREAM_PAGES));
let aads: Vec<Vec<u8>> = todo
.iter()
.map(|&i| self.page_aad(pages[i].0, pages[i].1))
.collect();
let cipher = crypto::page_cipher(&self.dek);
let file: &File = self.f()?;
let read = |lo: usize, hi: usize| -> Result<Vec<u8>> {
let mut buf = vec![0u8; (hi - lo) * PAGE_SIZE];
let mut k = lo;
while k < hi {
let first = pages[todo[k]].0;
let mut run = 1;
while k + run < hi && pages[todo[k + run]].0 == first + run as u64 {
run += 1;
}
let at = (k - lo) * PAGE_SIZE;
read_exact_at(
file,
&mut buf[at..at + run * PAGE_SIZE],
first * PAGE_SIZE as u64,
)?;
k += run;
}
for (n, img) in buf.chunks_exact_mut(PAGE_SIZE).enumerate() {
let j = lo + n;
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&img[..NONCE_LEN]);
let (body, tag) = img[NONCE_LEN..].split_at_mut(PAYLOAD);
crypto::aead_decrypt_in_place(&cipher, &nonce, &aads[j], body, tag)
.map_err(|_| MnemoError::PageAuthFailed(pages[todo[j]].0))?;
}
Ok(buf)
};
let mut deliver = |lo: usize, buf: &[u8]| -> Result<()> {
for (n, img) in buf.chunks_exact(PAGE_SIZE).enumerate() {
sink(todo[lo + n], &img[NONCE_LEN..NONCE_LEN + PAYLOAD])?;
}
Ok(())
};
if threads <= 1 {
let mut lo = 0;
while lo < todo.len() {
let hi = (lo + STREAM_PAGES).min(todo.len());
deliver(lo, &read(lo, hi)?)?;
lo = hi;
}
return Ok(());
}
let per = todo.len().div_ceil(threads);
std::thread::scope(|s| {
let (tx, rx) = std::sync::mpsc::sync_channel::<Result<(usize, Vec<u8>)>>(2 * threads);
let read = &read;
for t in 0..threads {
let tx = tx.clone();
let (start, end) = (t * per, ((t + 1) * per).min(todo.len()));
s.spawn(move || {
let mut lo = start;
while lo < end {
let hi = (lo + STREAM_PAGES).min(end);
let msg = read(lo, hi).map(|b| (lo, b));
let stop = msg.is_err();
if tx.send(msg).is_err() || stop {
return;
}
lo = hi;
}
});
}
drop(tx);
for msg in rx {
let (lo, buf) = msg?;
deliver(lo, &buf)?;
}
Ok(())
})
}
pub(crate) fn read_pages_with(
&mut self,
pages: &[(u64, u64)],
threads: usize,
) -> Result<PageBatch> {
let mut slots: Vec<Slot> = pages
.iter()
.map(|&(p, _)| match self.cache.peek(p) {
Some(c) => Slot::Cached(c.to_vec()),
None => Slot::Disk(usize::MAX),
})
.collect();
let mut todo: Vec<usize> = (0..pages.len())
.filter(|&i| matches!(slots[i], Slot::Disk(_)))
.collect();
todo.sort_by_key(|&i| pages[i].0);
for (j, &i) in todo.iter().enumerate() {
slots[i] = Slot::Disk(j);
}
let mut disk = vec![0u8; todo.len() * PAGE_SIZE];
let mut k = 0;
while k < todo.len() {
let first = pages[todo[k]].0;
let mut run = 1;
while k + run < todo.len() && pages[todo[k + run]].0 == first + run as u64 {
run += 1;
}
let buf = &mut disk[k * PAGE_SIZE..(k + run) * PAGE_SIZE];
read_exact_at(self.f()?, buf, first * PAGE_SIZE as u64)?;
k += run;
}
let cipher = crypto::page_cipher(&self.dek);
let aads: Vec<Vec<u8>> = todo
.iter()
.map(|&i| self.page_aad(pages[i].0, pages[i].1))
.collect();
let open = |first: usize, chunk: &mut [u8]| -> std::result::Result<(), usize> {
for (n, img) in chunk.chunks_exact_mut(PAGE_SIZE).enumerate() {
let j = first + n;
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&img[..NONCE_LEN]);
let (body, tag) = img[NONCE_LEN..].split_at_mut(PAYLOAD);
crypto::aead_decrypt_in_place(&cipher, &nonce, &aads[j], body, tag)
.map_err(|_| j)?;
}
Ok(())
};
let threads = threads.clamp(1, todo.len().max(1));
let failed: Option<usize> = if threads <= 1 {
open(0, &mut disk).err()
} else {
let per = todo.len().div_ceil(threads);
std::thread::scope(|s| {
let open = &open;
let parts: Vec<_> = disk
.chunks_mut(per * PAGE_SIZE)
.enumerate()
.map(|(t, chunk)| s.spawn(move || open(t * per, chunk).err()))
.collect();
parts
.into_iter()
.filter_map(|h| h.join().expect("a decrypt thread panicked"))
.min()
})
};
if let Some(j) = failed {
return Err(MnemoError::PageAuthFailed(pages[todo[j]].0));
}
Ok(PageBatch { disk, slots })
}
pub fn write_page(&mut self, page_no: u64, gen: u64, payload: &[u8]) -> Result<()> {
if payload.len() > PAYLOAD {
return Err(MnemoError::Invalid(format!(
"payload {} exceeds page capacity {}",
payload.len(),
PAYLOAD
)));
}
let mut padded = vec![0u8; PAYLOAD];
padded[..payload.len()].copy_from_slice(payload);
self.cache.insert(page_no, padded, true);
self.dirty_gens.insert(page_no, gen);
Ok(())
}
pub fn flush(&mut self) -> Result<()> {
let pages = self.cache.dirty_pages();
if pages.is_empty() {
return Ok(());
}
for page_no in pages {
let payload = self
.cache
.peek(page_no)
.expect("dirty page must be cached")
.to_vec();
self.write_counter += 1;
let nonce = self.next_nonce();
let gen = self.dirty_gens.get(&page_no).copied().unwrap_or(0);
let aad = self.page_aad(page_no, gen);
let ciphertext = crypto::aead_encrypt(&self.dek, &nonce, &payload, &aad)?;
let mut disk = Vec::with_capacity(PAGE_SIZE);
disk.extend_from_slice(&nonce);
disk.extend_from_slice(&ciphertext);
debug_assert_eq!(disk.len(), PAGE_SIZE);
__failpoint_check()?;
self.f()?
.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
self.f()?.write_all(&disk)?;
}
self.f()?.sync_all()?;
crate::bump_fsync();
self.cache.mark_all_clean();
self.dirty_gens.clear();
self.cache.trim();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
const GEN: u64 = 7;
fn pager(path: &std::path::Path) -> Pager {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
.unwrap();
Pager::new(
LockedFile::new(file),
Zeroizing::new([7u8; KEY_LEN]),
0,
crate::format::VERSION_V9,
)
}
fn write_pages(path: &std::path::Path, n: u64) {
let mut p = pager(path);
for page in 1..=n {
let body = page.to_le_bytes();
let img = p.seal_page(page, GEN, &body).unwrap();
p.write_sealed(page, &img).unwrap();
}
p.sync().unwrap();
}
#[test]
fn batched_reads_match_single_reads() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("p.bin");
let n = (PARALLEL_DECRYPT_MIN_PAGES as u64) * 2;
write_pages(&path, n);
let mut want: Vec<(u64, u64)> = (1..=n).filter(|p| p % 5 != 0).map(|p| (p, GEN)).collect();
want.reverse();
want.swap(3, 40);
let mut single = pager(&path);
let one: Vec<Vec<u8>> = want
.iter()
.map(|&(p, g)| single.read_page_uncached(p, g).unwrap())
.collect();
let all = |b: PageBatch| {
(0..b.len())
.map(|i| b.payload(i).to_vec())
.collect::<Vec<_>>()
};
for threads in [1, 4] {
let mut p = pager(&path);
assert_eq!(
all(p.read_pages_with(&want, threads).unwrap()),
one,
"{threads} threads"
);
}
assert_eq!(all(pager(&path).read_pages_uncached(&want).unwrap()), one);
for (got, &(page, _)) in one.iter().zip(&want) {
assert_eq!(&got[..8], &page.to_le_bytes());
}
let bad = 51u64;
assert!(want.iter().any(|&(p, _)| p == bad));
{
use std::io::{Seek, SeekFrom, Write};
let mut f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
f.seek(SeekFrom::Start(bad * PAGE_SIZE as u64 + 100))
.unwrap();
f.write_all(&[0xA5]).unwrap();
}
for threads in [1, 4] {
let res = pager(&path).read_pages_with(&want, threads);
assert!(
matches!(res, Err(MnemoError::PageAuthFailed(p)) if p == bad),
"{threads} threads: {:?}",
res.map(|b| b.len())
);
}
let res = pager(&path).read_pages_with(&[(1, GEN + 1)], 1);
assert!(
matches!(res, Err(MnemoError::PageAuthFailed(1))),
"{:?}",
res.map(|b| b.len())
);
assert!(pager(&path).read_pages_with(&[(n + 5, GEN)], 1).is_err());
let mut p = pager(&path);
p.write_page(2, GEN, b"in the cache").unwrap();
let got = p.read_pages_with(&[(2, GEN), (3, GEN)], 1).unwrap();
assert_eq!(&got.payload(0)[..12], b"in the cache");
assert_eq!(&got.payload(1)[..8], &3u64.to_le_bytes());
}
#[test]
fn streamed_reads_reach_the_sink_once_each() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("p.bin");
let n = (PARALLEL_DECRYPT_MIN_PAGES as u64) * 3;
write_pages(&path, n);
let want: Vec<(u64, u64)> = (1..=n)
.rev()
.filter(|p| p % 7 != 0)
.map(|p| (p, GEN))
.collect();
for threads in [Some(1), Some(4), None] {
let mut seen = vec![0u32; want.len()];
pager(&path)
.for_each_page_with(&want, threads, |i, bytes| {
seen[i] += 1;
assert_eq!(&bytes[..8], &want[i].0.to_le_bytes());
assert_eq!(bytes.len(), PAYLOAD);
Ok(())
})
.unwrap();
assert!(seen.iter().all(|&c| c == 1), "{threads:?}: {seen:?}");
}
for threads in [Some(1), Some(4)] {
let mut calls = 0;
let res = pager(&path).for_each_page_with(&want, threads, |_, _| {
calls += 1;
if calls == 10 {
Err(MnemoError::Invalid("stop".into()))
} else {
Ok(())
}
});
assert!(matches!(res, Err(MnemoError::Invalid(_))), "{threads:?}");
assert_eq!(calls, 10);
}
let mut p = pager(&path);
p.write_page(2, GEN, b"cached").unwrap();
let mut got = Vec::new();
p.for_each_page_with(&[(2, GEN), (3, GEN)], Some(1), |i, b| {
got.push((i, b[..6].to_vec()));
Ok(())
})
.unwrap();
got.sort();
assert_eq!(got[0], (0, b"cached".to_vec()));
assert_eq!(&got[1].1[..6], &3u64.to_le_bytes()[..6]);
{
use std::io::{Seek, SeekFrom, Write};
let mut f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
f.seek(SeekFrom::Start(100 * PAGE_SIZE as u64 + 64))
.unwrap();
f.write_all(&[0x5A]).unwrap();
}
for threads in [Some(1), Some(4)] {
let res = pager(&path).for_each_page_with(&want, threads, |_, _| Ok(()));
assert!(
matches!(res, Err(MnemoError::PageAuthFailed(100))),
"{threads:?}: {:?}",
res.err()
);
}
}
}