use crate::namespace::{SEP, normalize_key};
use crate::vfs::{
FileStream, OpenOptions, SharedSource, SourceCursor, VfsDirEntry, VfsMetadata, VirtualFs,
VolumeInfo, WritableFile, no_space,
};
use std::collections::HashMap;
use std::ffi::OsString;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::{Arc, Mutex, RwLock};
use std::time::SystemTime;
const DEFAULT_CAPACITY: u64 = 1 << 40;
struct Volume {
capacity: u64,
used: Mutex<u64>,
}
impl Volume {
fn new(capacity: u64) -> Arc<Self> {
Arc::new(Self {
capacity,
used: Mutex::new(0),
})
}
fn resize(&self, old: u64, new: u64) -> io::Result<()> {
let mut used = self
.used
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if new >= old {
let grow = new - old;
if used.saturating_add(grow) > self.capacity {
return Err(no_space());
}
*used += grow;
} else {
*used = used.saturating_sub(old - new);
}
Ok(())
}
fn reserve(&self, old: u64, desired_new: u64) -> u64 {
let mut used = self
.used
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let want = desired_new.saturating_sub(old);
let free = self.capacity.saturating_sub(*used);
let grant = want.min(free);
*used += grant;
old + grant
}
fn release(&self, len: u64) {
let mut used = self
.used
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*used = used.saturating_sub(len);
}
fn info(&self) -> VolumeInfo {
let used = *self
.used
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
VolumeInfo {
capacity: self.capacity,
available: self.capacity.saturating_sub(used),
block_size: 4096,
}
}
}
pub(crate) struct MemFile {
data: Mutex<Vec<u8>>,
volume: Arc<Volume>,
mtime: Mutex<Option<SystemTime>>,
}
impl MemFile {
fn new(volume: Arc<Volume>) -> Arc<Self> {
Arc::new(Self {
data: Mutex::new(Vec::new()),
volume,
mtime: Mutex::new(Some(SystemTime::now())),
})
}
fn lock_data(&self) -> std::sync::MutexGuard<'_, Vec<u8>> {
self.data
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn len(&self) -> u64 {
self.lock_data().len() as u64
}
fn mtime(&self) -> Option<SystemTime> {
*self
.mtime
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn touch(&self) {
*self
.mtime
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(SystemTime::now());
}
fn snapshot(&self) -> Vec<u8> {
self.lock_data().clone()
}
fn read_at(&self, pos: u64, buf: &mut [u8]) -> usize {
let data = self.lock_data();
let Ok(start) = usize::try_from(pos) else {
return 0;
};
let Some(src) = data.get(start..) else {
return 0;
};
let n = src.len().min(buf.len());
let (Some(dst), Some(src)) = (buf.get_mut(..n), src.get(..n)) else {
return 0;
};
dst.copy_from_slice(src);
n
}
fn write_at(&self, pos: u64, buf: &[u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0); }
let mut data = self.lock_data();
let old = data.len() as u64;
let desired_end = pos
.checked_add(buf.len() as u64)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "write offset overflow"))?;
let desired_new = desired_end.max(old);
let granted_new = self.volume.reserve(old, desired_new);
let slots = usize::try_from(granted_new.saturating_sub(pos)).unwrap_or(usize::MAX);
let n = slots.min(buf.len());
if n == 0 {
self.volume.release(granted_new.saturating_sub(old));
return Err(no_space());
}
let (Ok(new_len), Ok(start)) = (usize::try_from(granted_new), usize::try_from(pos)) else {
self.volume.release(granted_new.saturating_sub(old));
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"write offset overflow",
));
};
if data.len() < new_len {
data.resize(new_len, 0); }
if let (Some(dst), Some(src)) = (data.get_mut(start..start.saturating_add(n)), buf.get(..n))
{
dst.copy_from_slice(src);
}
drop(data);
self.touch();
Ok(n)
}
fn set_len(&self, len: u64) -> io::Result<()> {
let mut data = self.lock_data();
let old = data.len() as u64;
self.volume.resize(old, len)?;
let target = usize::try_from(len)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "length overflow"))?;
data.resize(target, 0);
drop(data);
self.touch();
Ok(())
}
}
impl Drop for MemFile {
fn drop(&mut self) {
let len = self
.data
.get_mut()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.len();
self.volume.release(len as u64);
}
}
pub(crate) struct MemFileHandle {
file: Arc<MemFile>,
pos: u64,
}
impl MemFileHandle {
fn new(file: Arc<MemFile>) -> Self {
Self { file, pos: 0 }
}
fn at_end(file: Arc<MemFile>) -> Self {
let pos = file.len();
Self { file, pos }
}
}
impl Read for MemFileHandle {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = self.file.read_at(self.pos, buf);
self.pos = self.pos.saturating_add(n as u64);
Ok(n)
}
}
impl Write for MemFileHandle {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let n = self.file.write_at(self.pos, buf)?;
self.pos = self.pos.saturating_add(n as u64);
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
Ok(()) }
}
impl Seek for MemFileHandle {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
let size = self.file.len();
let target: i128 = match pos {
SeekFrom::Start(off) => i128::from(off),
SeekFrom::End(off) => i128::from(size) + i128::from(off),
SeekFrom::Current(off) => i128::from(self.pos) + i128::from(off),
};
if target < 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"seek to a negative position",
));
}
self.pos = u64::try_from(target)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "seek offset overflow"))?;
Ok(self.pos)
}
fn stream_position(&mut self) -> io::Result<u64> {
Ok(self.pos)
}
}
impl WritableFile for MemFileHandle {
fn set_len(&mut self, len: u64) -> io::Result<()> {
self.file.set_len(len)
}
}
enum Node {
File {
source: Arc<SharedSource>,
name: OsString,
mtime: Option<SystemTime>,
},
MemFile { file: Arc<MemFile>, name: OsString },
Dir { name: OsString },
}
pub struct MemoryFs {
entries: RwLock<HashMap<String, Node>>,
volume: Arc<Volume>,
}
impl std::fmt::Debug for MemoryFs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let count = self.entries.read().map_or(0, |e| e.len());
f.debug_struct("MemoryFs")
.field("entries", &count)
.field("capacity", &self.volume.capacity)
.finish()
}
}
impl MemoryFs {
#[must_use]
pub fn new() -> Arc<Self> {
Self::with_capacity(DEFAULT_CAPACITY)
}
#[must_use]
pub fn with_capacity(capacity: u64) -> Arc<Self> {
Arc::new(Self {
entries: RwLock::new(HashMap::new()),
volume: Volume::new(capacity),
})
}
pub(crate) fn insert_file(
&self,
path: &Path,
source: Arc<SharedSource>,
mtime: Option<SystemTime>,
) -> String {
let key = normalize_key(path);
let name = final_component(path);
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
debug_assert!(
!matches!(
map.get(&key),
Some(Node::File { .. } | Node::MemFile { .. })
),
"mount collision: a file is already mounted at `{key}` (caller must supply unique keys)",
);
map.insert(
key.clone(),
Node::File {
source,
name,
mtime,
},
);
insert_ancestor_dirs(&mut map, path);
key
}
pub(crate) fn insert_writable(&self, path: &Path) -> String {
let key = normalize_key(path);
let name = final_component(path);
let file = MemFile::new(self.volume.clone());
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
map.insert(key.clone(), Node::MemFile { file, name });
insert_ancestor_dirs(&mut map, path);
key
}
#[must_use]
pub fn snapshot(&self, path: &Path) -> Option<Vec<u8>> {
let key = normalize_key(path);
let map = self
.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match map.get(&key)? {
Node::MemFile { file, .. } => Some(file.snapshot()),
_ => None,
}
}
pub(crate) fn remove_subtree(&self, key: &str) {
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
map.retain(|k, _| !(k == key || k.strip_prefix(key).is_some_and(|r| r.starts_with(SEP))));
let mut ancestor = parent_key(key).map(str::to_owned);
while let Some(dir) = ancestor {
if !matches!(map.get(&dir), Some(Node::Dir { .. })) {
break;
}
if map.keys().any(|k| parent_key(k) == Some(dir.as_str())) {
break;
}
let next = parent_key(&dir).map(str::to_owned);
map.remove(&dir);
ancestor = next;
}
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.read().map_or(0, |e| e.len())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn metadata_for(map: &HashMap<String, Node>, key: &str) -> Option<VfsMetadata> {
match map.get(key)? {
Node::File { source, mtime, .. } => {
let mut meta = VfsMetadata::file(source.size());
meta.mtime = *mtime;
Some(meta)
}
Node::MemFile { file, .. } => {
let mut meta = VfsMetadata::file_rw(file.len());
meta.mtime = file.mtime();
Some(meta)
}
Node::Dir { .. } => Some(VfsMetadata::dir()),
}
}
}
impl VirtualFs for MemoryFs {
fn open(&self, path: &Path, _opts: &OpenOptions) -> Option<io::Result<Box<dyn FileStream>>> {
let key = normalize_key(path);
let map = self
.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match map.get(&key)? {
Node::File { source, .. } => Some(Ok(Box::new(SourceCursor::new(source.clone())))),
Node::MemFile { file, .. } => Some(Ok(Box::new(MemFileHandle::new(file.clone())))),
Node::Dir { .. } => Some(Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"path is a directory",
))),
}
}
fn open_write(
&self,
path: &Path,
opts: &OpenOptions,
) -> Option<io::Result<Box<dyn WritableFile>>> {
let key = normalize_key(path);
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let file = match map.get(&key) {
Some(Node::Dir { .. }) => {
return Some(Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"path is a directory",
)));
}
Some(Node::File { .. }) => {
return Some(Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"virtual file is read-only",
)));
}
Some(Node::MemFile { file, .. }) => {
if opts.create_new {
return Some(Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"file already exists",
)));
}
file.clone()
}
None => {
if !opts.creates() {
return Some(Err(io::Error::from(io::ErrorKind::NotFound)));
}
let file = MemFile::new(self.volume.clone());
let name = final_component(path);
map.insert(
key,
Node::MemFile {
file: file.clone(),
name,
},
);
insert_ancestor_dirs(&mut map, path);
file
}
};
drop(map); if opts.truncate
&& let Err(err) = file.set_len(0)
{
return Some(Err(err));
}
let handle = if opts.append {
MemFileHandle::at_end(file)
} else {
MemFileHandle::new(file)
};
Some(Ok(Box::new(handle)))
}
fn metadata(&self, path: &Path) -> Option<io::Result<VfsMetadata>> {
let key = normalize_key(path);
let map = self
.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
Self::metadata_for(&map, &key).map(Ok)
}
fn read_dir(&self, path: &Path) -> Option<io::Result<Vec<VfsDirEntry>>> {
let dir_key = normalize_key(path);
let map = self
.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !matches!(map.get(&dir_key), Some(Node::Dir { .. })) {
return None;
}
let mut out = Vec::new();
for (key, node) in map.iter() {
if parent_key(key) == Some(dir_key.as_str()) {
let (name, metadata) = match node {
Node::File {
name,
source,
mtime,
} => {
let mut meta = VfsMetadata::file(source.size());
meta.mtime = *mtime;
(name.clone(), meta)
}
Node::MemFile { name, file } => {
let mut meta = VfsMetadata::file_rw(file.len());
meta.mtime = file.mtime();
(name.clone(), meta)
}
Node::Dir { name } => (name.clone(), VfsMetadata::dir()),
};
out.push(VfsDirEntry { name, metadata });
}
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Some(Ok(out))
}
fn remove(&self, path: &Path) -> Option<io::Result<()>> {
let key = normalize_key(path);
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match map.get(&key) {
None => Some(Err(io::Error::from(io::ErrorKind::NotFound))),
Some(Node::Dir { .. }) => {
if map.keys().any(|k| parent_key(k) == Some(key.as_str())) {
return Some(Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"directory not empty",
)));
}
map.remove(&key);
Some(Ok(()))
}
Some(Node::MemFile { .. } | Node::File { .. }) => {
map.remove(&key);
Some(Ok(()))
}
}
}
fn rename(&self, from: &Path, to: &Path) -> Option<io::Result<()>> {
let from_key = normalize_key(from);
let to_key = normalize_key(to);
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(from_node) = map.get(&from_key) else {
return Some(Err(io::Error::from(io::ErrorKind::NotFound)));
};
if to_key == from_key {
return Some(Ok(())); }
let from_is_dir = matches!(from_node, Node::Dir { .. });
if from_is_dir
&& to_key
.strip_prefix(&from_key)
.is_some_and(|r| r.starts_with(SEP))
{
return Some(Err(io::Error::from(io::ErrorKind::InvalidInput)));
}
if let Some(dest) = map.get(&to_key) {
let dest_is_dir = matches!(dest, Node::Dir { .. });
match (from_is_dir, dest_is_dir) {
(false, true) => return Some(Err(io::Error::from(io::ErrorKind::IsADirectory))),
(true, false) => return Some(Err(io::Error::from(io::ErrorKind::NotADirectory))),
(true, true) => {
if map.keys().any(|k| parent_key(k) == Some(to_key.as_str())) {
return Some(Err(io::Error::from(io::ErrorKind::DirectoryNotEmpty)));
}
map.remove(&to_key);
}
(false, false) => {
map.remove(&to_key);
}
}
}
let to_move: Vec<String> = map
.keys()
.filter(|k| {
*k == &from_key
|| k.strip_prefix(&from_key)
.is_some_and(|r| r.starts_with(SEP))
})
.cloned()
.collect();
for k in to_move {
if let Some(mut node) = map.remove(&k) {
let new_key = rekey(&k, &from_key, &to_key);
if k == from_key {
rename_node(&mut node, final_component(to));
}
map.insert(new_key, node);
}
}
insert_ancestor_dirs(&mut map, to);
Some(Ok(()))
}
fn create_dir(&self, path: &Path) -> Option<io::Result<()>> {
let key = normalize_key(path);
let mut map = self
.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if map.contains_key(&key) {
return Some(Err(io::Error::from(io::ErrorKind::AlreadyExists)));
}
let name = final_component(path);
map.insert(key, Node::Dir { name });
insert_ancestor_dirs(&mut map, path);
Some(Ok(()))
}
fn set_len(&self, path: &Path, len: u64) -> Option<io::Result<()>> {
let key = normalize_key(path);
let map = self
.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match map.get(&key) {
Some(Node::MemFile { file, .. }) => Some(file.set_len(len)),
Some(_) => Some(Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"virtual file is read-only",
))),
None => Some(Err(io::Error::from(io::ErrorKind::NotFound))),
}
}
fn volume_info(&self) -> Option<VolumeInfo> {
Some(self.volume.info())
}
}
fn rekey(k: &str, from: &str, to: &str) -> String {
if k == from {
to.to_owned()
} else {
format!("{to}{}", &k[from.len()..])
}
}
fn rename_node(node: &mut Node, name: OsString) {
match node {
Node::File { name: n, .. } | Node::MemFile { name: n, .. } | Node::Dir { name: n } => {
*n = name;
}
}
}
fn insert_ancestor_dirs(map: &mut HashMap<String, Node>, path: &Path) {
let mut current = path.parent();
while let Some(dir) = current {
let key = normalize_key(dir);
if key.is_empty() {
break;
}
let name = final_component(dir);
map.entry(key).or_insert(Node::Dir { name });
if dir.parent().is_none() {
break;
}
current = dir.parent();
}
}
fn final_component(path: &Path) -> OsString {
path.file_name()
.map_or_else(|| path.as_os_str().to_owned(), std::ffi::OsStr::to_owned)
}
#[cfg(windows)]
const ROOT_LEN: usize = 3;
#[cfg(unix)]
const ROOT_LEN: usize = 1;
fn parent_key(key: &str) -> Option<&str> {
let idx = key.rfind(SEP)?;
if idx < ROOT_LEN {
key.get(..=idx)
} else {
key.get(..idx)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
mod tests {
use super::*;
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
#[cfg(windows)]
const RESERVED_PREFIX: &str = "C:\\__hookfs__";
#[cfg(unix)]
const RESERVED_PREFIX: &str = "/__hookfs__";
fn vpath(parts: &[&str]) -> PathBuf {
let mut p = PathBuf::from(RESERVED_PREFIX);
for part in parts {
p.push(part);
}
p
}
fn mount(fs: &MemoryFs, path: &Path, data: &[u8]) -> String {
let src = SharedSource::new(Cursor::new(data.to_vec())).unwrap();
fs.insert_file(path, src, None)
}
fn wt() -> OpenOptions {
OpenOptions::write_truncate()
}
fn write_err(r: Option<io::Result<Box<dyn WritableFile>>>) -> io::Error {
match r {
Some(Err(e)) => e,
_ => panic!("expected the write-open to fail"),
}
}
#[test]
fn open_metadata_and_readdir() {
let fs = MemoryFs::new();
mount(&fs, &vpath(&["id", "sample.braw"]), b"hello world");
mount(&fs, &vpath(&["id", "sample.sidecar"]), b"{}");
let meta = fs
.metadata(&vpath(&["id", "sample.braw"]))
.unwrap()
.unwrap();
assert_eq!(meta.len, 11);
assert!(!meta.is_dir);
let dir = fs.metadata(&vpath(&["id"])).unwrap().unwrap();
assert!(dir.is_dir);
let entries = fs.read_dir(&vpath(&["id"])).unwrap().unwrap();
let names: Vec<_> = entries
.iter()
.map(|e| e.name.to_string_lossy().into_owned())
.collect();
assert!(names.contains(&"sample.braw".to_string()));
assert!(names.contains(&"sample.sidecar".to_string()));
}
#[test]
fn independent_cursors_over_shared_source() {
let fs = MemoryFs::new();
let p = vpath(&["id", "a.bin"]);
mount(&fs, &p, b"0123456789");
let mut a = fs.open(&p, &OpenOptions::read_only()).unwrap().unwrap();
let mut b = fs.open(&p, &OpenOptions::read_only()).unwrap().unwrap();
a.seek(SeekFrom::Start(5)).unwrap();
let mut ba = [0u8; 3];
b.read_exact(&mut ba).unwrap();
assert_eq!(&ba, b"012"); let mut aa = [0u8; 3];
a.read_exact(&mut aa).unwrap();
assert_eq!(&aa, b"567");
}
#[test]
fn create_write_read_back() {
let fs = MemoryFs::new();
let p = vpath(&["id", "out.sidecar"]);
assert!(fs.metadata(&p).is_none());
let mut w = fs.open_write(&p, &wt()).unwrap().unwrap();
w.write_all(b"hello ").unwrap();
w.write_all(b"world").unwrap();
drop(w);
let meta = fs.metadata(&p).unwrap().unwrap();
assert_eq!(meta.len, 11);
assert!(!meta.readonly);
let mut r = fs.open(&p, &OpenOptions::read_only()).unwrap().unwrap();
let mut buf = Vec::new();
r.read_to_end(&mut buf).unwrap();
assert_eq!(buf, b"hello world");
assert_eq!(fs.snapshot(&p).unwrap(), b"hello world");
}
#[test]
fn seek_past_eof_zero_fills_then_writes() {
let fs = MemoryFs::new();
let p = vpath(&["id", "sparse.bin"]);
let mut w = fs.open_write(&p, &wt()).unwrap().unwrap();
w.seek(SeekFrom::Start(4)).unwrap();
w.write_all(b"XY").unwrap();
drop(w);
assert_eq!(fs.snapshot(&p).unwrap(), b"\0\0\0\0XY");
}
#[test]
fn truncate_grows_and_shrinks() {
let fs = MemoryFs::new();
let p = vpath(&["id", "t.bin"]);
let mut w = fs.open_write(&p, &wt()).unwrap().unwrap();
w.write_all(b"abcdef").unwrap();
w.set_len(3).unwrap();
assert_eq!(fs.snapshot(&p).unwrap(), b"abc");
w.set_len(5).unwrap(); assert_eq!(fs.snapshot(&p).unwrap(), b"abc\0\0");
}
#[test]
fn append_positions_at_end() {
let fs = MemoryFs::new();
let p = vpath(&["id", "log.txt"]);
fs.open_write(&p, &wt())
.unwrap()
.unwrap()
.write_all(b"first")
.unwrap();
let mut a = fs
.open_write(
&p,
&OpenOptions {
write: true,
create: true,
append: true,
..OpenOptions::default()
},
)
.unwrap()
.unwrap();
a.write_all(b"+second").unwrap();
assert_eq!(fs.snapshot(&p).unwrap(), b"first+second");
}
#[test]
fn independent_write_cursors_and_shared_content() {
let fs = MemoryFs::new();
let p = vpath(&["id", "shared.bin"]);
fs.open_write(&p, &wt())
.unwrap()
.unwrap()
.set_len(8)
.unwrap();
let mut a = fs
.open_write(
&p,
&OpenOptions {
write: true,
..OpenOptions::default()
},
)
.unwrap()
.unwrap();
let mut b = fs
.open_write(
&p,
&OpenOptions {
write: true,
..OpenOptions::default()
},
)
.unwrap()
.unwrap();
a.seek(SeekFrom::Start(0)).unwrap();
b.seek(SeekFrom::Start(4)).unwrap();
a.write_all(b"AAAA").unwrap();
b.write_all(b"BBBB").unwrap();
assert_eq!(fs.snapshot(&p).unwrap(), b"AAAABBBB");
}
#[test]
fn capacity_enforced_with_enospc() {
let fs = MemoryFs::with_capacity(8);
let p = vpath(&["id", "big.bin"]);
let mut w = fs.open_write(&p, &wt()).unwrap().unwrap();
w.write_all(b"12345678").unwrap(); let over = w.write_all(b"9");
let err = over.unwrap_err();
#[cfg(unix)]
assert_eq!(err.raw_os_error(), Some(28));
#[cfg(windows)]
assert_eq!(err.raw_os_error(), Some(112));
drop(w);
fs.remove(&p).unwrap().unwrap();
assert_eq!(fs.volume_info().unwrap().available, 8);
}
#[test]
fn write_past_capacity_is_a_short_write() {
let fs = MemoryFs::with_capacity(8);
let p = vpath(&["id", "short.bin"]);
let mut w = fs.open_write(&p, &wt()).unwrap().unwrap();
w.write_all(b"123456").unwrap();
let n = w.write(b"789AB").unwrap();
assert_eq!(n, 2, "only the bytes that fit are written");
assert_eq!(fs.snapshot(&p).unwrap(), b"12345678");
assert_eq!(
fs.volume_info().unwrap().available,
0,
"the volume is now exactly full"
);
let err = w.write(b"C").unwrap_err();
#[cfg(unix)]
assert_eq!(err.raw_os_error(), Some(28));
#[cfg(windows)]
assert_eq!(err.raw_os_error(), Some(112));
assert_eq!(w.write(b"").unwrap(), 0);
}
#[test]
fn remove_while_write_handle_open_releases_capacity_exactly_once() {
let fs = MemoryFs::with_capacity(64);
let p = vpath(&["id", "open.bin"]);
let mut w = fs.open_write(&p, &wt()).unwrap().unwrap();
w.write_all(b"0123456789").unwrap(); assert_eq!(fs.volume_info().unwrap().available, 64 - 10);
fs.remove(&p).unwrap().unwrap();
assert!(
fs.metadata(&p).is_none(),
"the unlinked path is gone from the tree"
);
assert_eq!(
fs.volume_info().unwrap().available,
64 - 10,
"capacity stays reserved while a handle keeps the backing alive",
);
w.write_all(b"ABCDEF").unwrap(); assert_eq!(fs.volume_info().unwrap().available, 64 - 16);
drop(w);
assert_eq!(
fs.volume_info().unwrap().available,
64,
"capacity is returned in full, exactly once, on the final drop",
);
}
#[test]
fn create_new_fails_if_exists() {
let fs = MemoryFs::new();
let p = vpath(&["id", "x.bin"]);
fs.open_write(&p, &wt()).unwrap().unwrap();
let opts = OpenOptions {
write: true,
create_new: true,
..OpenOptions::default()
};
assert_eq!(
write_err(fs.open_write(&p, &opts)).kind(),
io::ErrorKind::AlreadyExists
);
}
#[test]
fn write_open_missing_without_create_is_enoent() {
let fs = MemoryFs::new();
let p = vpath(&["id", "missing.bin"]);
let opts = OpenOptions {
write: true,
..OpenOptions::default()
};
assert_eq!(
write_err(fs.open_write(&p, &opts)).kind(),
io::ErrorKind::NotFound
);
}
#[test]
fn read_only_mount_cannot_be_written() {
let fs = MemoryFs::new();
let p = vpath(&["id", "ro.braw"]);
mount(&fs, &p, b"payload");
let opts = OpenOptions {
write: true,
..OpenOptions::default()
};
assert_eq!(
write_err(fs.open_write(&p, &opts)).kind(),
io::ErrorKind::PermissionDenied
);
}
#[test]
fn rename_moves_file_and_frees_destination() {
let fs = MemoryFs::new();
let tmp = vpath(&["id", "out.tmp"]);
let fin = vpath(&["id", "out.braw"]);
fs.open_write(&tmp, &wt())
.unwrap()
.unwrap()
.write_all(b"final-bytes")
.unwrap();
fs.rename(&tmp, &fin).unwrap().unwrap();
assert!(fs.metadata(&tmp).is_none());
assert_eq!(fs.snapshot(&fin).unwrap(), b"final-bytes");
let names: Vec<_> = fs
.read_dir(&vpath(&["id"]))
.unwrap()
.unwrap()
.iter()
.map(|e| e.name.to_string_lossy().into_owned())
.collect();
assert!(names.contains(&"out.braw".to_string()));
assert!(!names.contains(&"out.tmp".to_string()));
}
#[test]
fn rename_replaces_destination_and_releases_its_capacity() {
let fs = MemoryFs::with_capacity(64);
let src = vpath(&["id", "src.bin"]);
let dst = vpath(&["id", "dst.bin"]);
fs.open_write(&src, &wt())
.unwrap()
.unwrap()
.write_all(b"NEW")
.unwrap(); fs.open_write(&dst, &wt())
.unwrap()
.unwrap()
.write_all(b"OLD-CONTENT")
.unwrap(); assert_eq!(fs.volume_info().unwrap().available, 64 - 3 - 11);
fs.rename(&src, &dst).unwrap().unwrap();
assert!(
fs.metadata(&src).is_none(),
"the source is gone after the move"
);
assert_eq!(
fs.snapshot(&dst).unwrap(),
b"NEW",
"the destination holds the source bytes"
);
assert_eq!(fs.volume_info().unwrap().available, 64 - 3);
}
#[test]
fn rename_onto_nonempty_directory_is_enotempty() {
let fs = MemoryFs::new();
let src_dir = vpath(&["id", "srcdir"]);
fs.create_dir(&src_dir).unwrap().unwrap();
fs.open_write(&vpath(&["id", "srcdir", "a.bin"]), &wt())
.unwrap()
.unwrap()
.write_all(b"a")
.unwrap();
let dst_dir = vpath(&["id", "dstdir"]);
fs.create_dir(&dst_dir).unwrap().unwrap();
fs.open_write(&vpath(&["id", "dstdir", "keep.bin"]), &wt())
.unwrap()
.unwrap()
.write_all(b"keep")
.unwrap();
let err = fs.rename(&src_dir, &dst_dir).unwrap().unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::DirectoryNotEmpty);
assert_eq!(
fs.snapshot(&vpath(&["id", "srcdir", "a.bin"])).unwrap(),
b"a"
);
assert_eq!(
fs.snapshot(&vpath(&["id", "dstdir", "keep.bin"])).unwrap(),
b"keep",
"the destination's unrelated child is not dropped",
);
}
#[test]
fn rename_onto_empty_directory_replaces_it() {
let fs = MemoryFs::new();
let src_dir = vpath(&["id", "srcdir"]);
fs.create_dir(&src_dir).unwrap().unwrap();
fs.open_write(&vpath(&["id", "srcdir", "a.bin"]), &wt())
.unwrap()
.unwrap()
.write_all(b"a")
.unwrap();
let dst_dir = vpath(&["id", "dstdir"]);
fs.create_dir(&dst_dir).unwrap().unwrap();
fs.rename(&src_dir, &dst_dir).unwrap().unwrap();
assert!(
fs.metadata(&src_dir).is_none(),
"the source directory moved away"
);
assert_eq!(
fs.snapshot(&vpath(&["id", "dstdir", "a.bin"])).unwrap(),
b"a",
"the source's child now lives under the destination path",
);
}
#[test]
fn create_dir_and_remove() {
let fs = MemoryFs::new();
let d = vpath(&["id", "sub"]);
fs.create_dir(&d).unwrap().unwrap();
assert!(fs.metadata(&d).unwrap().unwrap().is_dir);
assert_eq!(
fs.create_dir(&d).unwrap().unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
fs.open_write(&vpath(&["id", "sub", "f.bin"]), &wt())
.unwrap()
.unwrap();
assert!(fs.remove(&d).unwrap().is_err());
}
#[cfg(windows)]
#[test]
fn lookup_is_case_insensitive_and_separator_normalized() {
let fs = MemoryFs::new();
mount(&fs, &vpath(&["id", "Sample.Braw"]), b"x");
assert!(
fs.metadata(Path::new("c:/__HOOKFS__/id/SAMPLE.BRAW"))
.is_some()
);
assert!(fs.metadata(&vpath(&["id", "missing"])).is_none());
}
#[cfg(unix)]
#[test]
fn lookup_is_case_sensitive_and_separator_collapsed() {
let fs = MemoryFs::new();
mount(&fs, &vpath(&["id", "Sample.Braw"]), b"x");
assert!(
fs.metadata(Path::new("/__hookfs__/id/Sample.Braw"))
.is_some()
);
assert!(
fs.metadata(Path::new("/__hookfs__//id//Sample.Braw"))
.is_some()
);
assert!(
fs.metadata(Path::new("/__hookfs__/id/sample.braw"))
.is_none()
);
assert!(fs.metadata(&vpath(&["id", "missing"])).is_none());
}
#[test]
fn remove_subtree_drops_entries_but_open_cursor_survives() {
let fs = MemoryFs::new();
let p = vpath(&["id", "a.bin"]);
let key = mount(&fs, &p, b"payload");
let mut open = fs.open(&p, &OpenOptions::read_only()).unwrap().unwrap();
fs.remove_subtree(&key);
assert!(fs.metadata(&p).is_none());
let mut buf = Vec::new();
open.read_to_end(&mut buf).unwrap();
assert_eq!(buf, b"payload");
}
#[test]
fn same_name_under_distinct_mount_dirs_are_independent() {
let fs = MemoryFs::new();
let a = mount(&fs, &vpath(&["inst", "clip-a", "sample.braw"]), b"AAAA");
let b = mount(&fs, &vpath(&["inst", "clip-b", "sample.braw"]), b"BBBB");
assert_ne!(a, b, "distinct sub-dirs must yield distinct keys");
fs.remove_subtree(&a);
assert!(
fs.metadata(&vpath(&["inst", "clip-a", "sample.braw"]))
.is_none()
);
let bmeta = fs
.metadata(&vpath(&["inst", "clip-b", "sample.braw"]))
.unwrap()
.unwrap();
assert_eq!(bmeta.len, 4);
let mut open = fs
.open(
&vpath(&["inst", "clip-b", "sample.braw"]),
&OpenOptions::read_only(),
)
.unwrap()
.unwrap();
let mut buf = Vec::new();
open.read_to_end(&mut buf).unwrap();
assert_eq!(buf, b"BBBB");
}
#[test]
fn remove_subtree_prunes_empty_ancestor_dirs_but_keeps_shared_ones() {
let fs = MemoryFs::new();
let a = mount(&fs, &vpath(&["inst", "clip-a", "clip.braw"]), b"x");
let _b = mount(&fs, &vpath(&["inst", "clip-b", "clip.braw"]), b"y");
assert!(
fs.metadata(&vpath(&["inst", "clip-a"]))
.unwrap()
.unwrap()
.is_dir
);
fs.remove_subtree(&a);
assert!(fs.metadata(&vpath(&["inst", "clip-a"])).is_none());
assert!(fs.metadata(&vpath(&["inst"])).unwrap().unwrap().is_dir);
assert!(
fs.metadata(&vpath(&["inst", "clip-b", "clip.braw"]))
.is_some()
);
}
#[test]
fn remove_subtree_of_last_mount_prunes_up_to_root() {
let fs = MemoryFs::new();
let key = mount(&fs, &vpath(&["inst", "clip-a", "clip.braw"]), b"x");
fs.remove_subtree(&key);
assert!(fs.metadata(&vpath(&["inst", "clip-a"])).is_none());
assert!(fs.metadata(&vpath(&["inst"])).is_none());
assert!(fs.metadata(&vpath(&[])).is_none());
assert!(
fs.len() <= 1,
"no per-clip directory nodes must leak (root aside), got {}",
fs.len()
);
}
}