use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use bstack::{BStack, BStackAllocError, BStackAllocator, BStackOwnedSlice};
use parking_lot::RwLock;
use crate::primitives::{NonNullOffset, WidePtr};
use crate::util::io_error;
use crate::{BStackRaiiAllocator, get_u64};
pub use crate::types::alloc::SyncBStackRaiiAllocator;
pub use crate::types::alloc::{BStackRaiiAllocError, BStackRaiiHost};
pub use crate::primitives::FileId;
pub struct ForeignHostAllocator {
host: Arc<dyn BStackRaiiHost + 'static>,
file_id: FileId,
}
impl ForeignHostAllocator {
pub fn new(host: Arc<dyn BStackRaiiHost + 'static>, file_id: FileId) -> Self {
Self { host, file_id }
}
}
impl BStackAllocator for ForeignHostAllocator {
type Error = io::Error;
type Allocated<'a> = BStackOwnedSlice<'a, Self>;
fn stack(&self) -> &BStack {
self.host.stack()
}
fn into_stack(self) -> BStack {
unreachable!(
"ForeignHostAllocator is a cross-file adapter over a shared host and cannot \
be consumed into its BStack"
)
}
fn alloc(&self, len: u64) -> io::Result<BStackOwnedSlice<'_, Self>> {
let r = self.host.alloc(len)?;
Ok(unsafe { BStackOwnedSlice::from_raw_range(self, r) })
}
fn realloc<'a>(
&'a self,
handle: BStackOwnedSlice<'a, Self>,
new_len: u64,
) -> Result<BStackOwnedSlice<'a, Self>, BStackAllocError<'a, Self>> {
let r = handle.as_range();
match unsafe { self.host.realloc(r, new_len) } {
Ok(nr) => Ok(unsafe { BStackOwnedSlice::from_raw_range(self, nr) }),
Err(e) => Err(foreign_to_alloc_error(self, e)),
}
}
fn dealloc<'a>(
&'a self,
handle: BStackOwnedSlice<'a, Self>,
) -> Result<(), BStackAllocError<'a, Self>> {
let r = handle.as_range();
match unsafe { self.host.dealloc(r) } {
Ok(()) => Ok(()),
Err(e) => Err(foreign_to_alloc_error(self, e)),
}
}
}
unsafe impl BStackRaiiAllocator for ForeignHostAllocator {
fn wal_anchor(&self) -> Option<NonNullOffset> {
self.host.wal_anchor()
}
fn wal_file_id(&self) -> FileId {
self.file_id
}
}
fn foreign_to_alloc_error(
alloc: &ForeignHostAllocator,
e: BStackRaiiAllocError,
) -> BStackAllocError<'_, ForeignHostAllocator> {
match e.handle {
Some(h) => BStackAllocError::with_handle(e.source, unsafe {
BStackOwnedSlice::from_raw_range(alloc, h)
}),
None => BStackAllocError::lost(e.source),
}
}
struct RegistryStore {
stack: BStack,
}
impl RegistryStore {
fn open(path: &Path) -> io::Result<(Self, Vec<PathBuf>)> {
let stack = BStack::open(path)?;
let paths = Self::load(&stack)?;
Ok((RegistryStore { stack }, paths))
}
fn load(stack: &BStack) -> io::Result<Vec<PathBuf>> {
let total = stack.len()?;
if total == 0 {
return Ok(Vec::new());
}
let buf = stack.get(0, total)?;
let mut paths = Vec::new();
let mut cur = 0usize;
while cur + 8 <= buf.len() {
let len = get_u64(&buf[cur..]) as usize;
cur += 8;
match cur.checked_add(len) {
Some(end) if end <= buf.len() => {
paths.push(bytes_to_path(&buf[cur..end]));
cur = end;
}
_ => {
break;
}
}
}
Ok(paths)
}
fn append(&self, path: &Path) -> io::Result<()> {
let bytes = path_to_bytes(path);
let mut rec = Vec::with_capacity(8 + bytes.len());
rec.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
rec.extend_from_slice(&bytes);
self.stack.push(rec)?;
Ok(())
}
}
struct RegistryInner<'h> {
paths: Vec<PathBuf>,
by_path: HashMap<PathBuf, FileId>,
live: Vec<Option<Arc<dyn BStackRaiiHost + 'h>>>,
by_stack: HashMap<usize, FileId>,
store: RegistryStore,
}
pub struct FileRegistry<'h> {
inner: RwLock<RegistryInner<'h>>,
}
impl<'h> FileRegistry<'h> {
pub(crate) fn open(path: &Path) -> io::Result<Self> {
let (store, paths) = RegistryStore::open(path)?;
let by_path = paths
.iter()
.enumerate()
.map(|(i, p)| (p.clone(), FileId::from_raw(i as u32 + 1))) .collect();
let live = (0..paths.len()).map(|_| None).collect();
Ok(FileRegistry {
inner: RwLock::new(RegistryInner {
paths,
by_path,
live,
by_stack: HashMap::new(),
store,
}),
})
}
pub fn register_path(&self, path: &Path) -> io::Result<FileId> {
let mut g = self.inner.write();
if let Some(&id) = g.by_path.get(path) {
return Ok(id);
}
let next = g.paths.len() as u32 + 1; if next >= FileId::SPECIAL_FLOOR {
return Err(io_error!(
OutOfMemory,
"file registry exhausted the ordinary id space"
));
}
let id = FileId::from_raw(next);
g.store.append(path)?;
g.paths.push(path.to_path_buf());
g.by_path.insert(path.to_path_buf(), id);
g.live.push(None);
Ok(id)
}
pub fn attach(&self, path: &Path, host: Arc<dyn BStackRaiiHost + 'h>) -> io::Result<FileId> {
let id = self.register_path(path)?;
let stack_key = core::ptr::from_ref(host.stack()) as usize;
let mut g = self.inner.write();
let idx = id
.table_index()
.expect("register_path returns a concrete 1-based id");
if let Some(&prev) = g.by_stack.get(&stack_key)
&& prev != id
&& prev.table_index().is_some_and(|p| g.live[p].is_some())
{
return Err(io_error!(
InvalidInput,
"attach: this host is already attached under a different FileId"
));
}
if let Some(old) = g.live[idx].take() {
let old_key = core::ptr::from_ref(old.stack()) as usize;
g.by_stack.remove(&old_key);
}
g.live[idx] = Some(host);
g.by_stack.insert(stack_key, id);
Ok(id)
}
pub fn detach(&self, id: FileId) {
let Some(idx) = id.table_index() else { return };
let mut g = self.inner.write();
let stack_key = g
.live
.get_mut(idx)
.and_then(|slot| slot.take())
.map(|host| core::ptr::from_ref(host.stack()) as usize);
if let Some(k) = stack_key
&& g.by_stack.get(&k) == Some(&id)
{
g.by_stack.remove(&k);
}
}
pub fn with_host<R>(&self, id: FileId, f: impl FnOnce(&dyn BStackRaiiHost) -> R) -> Option<R> {
let idx = id.table_index()?;
let g = self.inner.read_recursive();
let host = g.live.get(idx)?.as_ref()?;
Some(f(&**host))
}
pub fn host_arc(&self, id: FileId) -> Option<Arc<dyn BStackRaiiHost + 'h>> {
let idx = id.table_index()?;
self.inner.read_recursive().live.get(idx)?.clone()
}
pub fn path_of(&self, id: FileId) -> Option<PathBuf> {
let idx = id.table_index()?;
self.inner.read().paths.get(idx).cloned()
}
pub fn id_of(&self, path: &Path) -> Option<FileId> {
self.inner.read().by_path.get(path).copied()
}
pub fn is_live(&self, id: FileId) -> bool {
let Some(idx) = id.table_index() else {
return false;
};
self.inner.read().live.get(idx).is_some_and(Option::is_some)
}
pub fn id_of_host(&self, stack: &BStack) -> Option<FileId> {
let key = core::ptr::from_ref(stack) as usize;
self.inner.read().by_stack.get(&key).copied()
}
}
static REGISTRY: OnceLock<FileRegistry<'static>> = OnceLock::new();
pub fn init(registry_path: impl AsRef<Path>) -> io::Result<()> {
let reg = FileRegistry::open(registry_path.as_ref())?;
REGISTRY
.set(reg)
.map_err(|_| io_error!(AlreadyExists, "file registry already initialized"))
}
pub fn get() -> Option<&'static FileRegistry<'static>> {
REGISTRY.get()
}
fn require() -> io::Result<&'static FileRegistry<'static>> {
REGISTRY.get().ok_or_else(|| {
io_error!(
NotFound,
"file registry not initialized, init with `bstack_raii::registry::init` first"
)
})
}
pub fn register_path(path: impl AsRef<Path>) -> io::Result<FileId> {
require()?.register_path(path.as_ref())
}
pub fn attach<A>(path: impl AsRef<Path>, allocator: A) -> io::Result<FileId>
where
A: SyncBStackRaiiAllocator + 'static,
{
require()?.attach(path.as_ref(), Arc::new(allocator))
}
pub fn detach(id: FileId) {
if let Some(reg) = REGISTRY.get() {
reg.detach(id);
}
}
pub fn with_host<R>(id: FileId, f: impl FnOnce(&dyn BStackRaiiHost) -> R) -> Option<R> {
REGISTRY.get()?.with_host(id, f)
}
pub fn path_of(id: FileId) -> Option<PathBuf> {
REGISTRY.get()?.path_of(id)
}
pub fn id_of_host(stack: &BStack) -> Option<FileId> {
REGISTRY.get()?.id_of_host(stack)
}
pub fn resolve_self_repr(repr: WidePtr, home: &BStack) -> io::Result<WidePtr> {
if !repr.is_self() || repr.is_null() {
return Ok(repr);
}
match id_of_host(home) {
Some(id) => Ok(WidePtr::with_parts(id, repr.type_id(), repr.offset())),
None => Ok(repr),
}
}
pub fn home_relative_repr(repr: WidePtr, home: &BStack) -> WidePtr {
if repr.is_self() {
return repr;
}
if let Some(id) = id_of_host(home)
&& repr.file() == id
{
return WidePtr::with_parts(FileId::SELF, repr.type_id(), repr.offset());
}
repr
}
pub fn host_arc(id: FileId) -> Option<Arc<dyn BStackRaiiHost + 'static>> {
REGISTRY.get()?.host_arc(id)
}
pub fn id_of(path: impl AsRef<Path>) -> Option<FileId> {
REGISTRY.get()?.id_of(path.as_ref())
}
#[cfg(unix)]
fn path_to_bytes(p: &Path) -> Vec<u8> {
use std::os::unix::ffi::OsStrExt;
p.as_os_str().as_bytes().to_vec()
}
#[cfg(unix)]
fn bytes_to_path(b: &[u8]) -> PathBuf {
use std::os::unix::ffi::OsStrExt;
std::ffi::OsStr::from_bytes(b).to_owned().into()
}
#[cfg(not(unix))]
fn path_to_bytes(p: &Path) -> Vec<u8> {
p.to_string_lossy().into_owned().into_bytes()
}
#[cfg(not(unix))]
fn bytes_to_path(b: &[u8]) -> PathBuf {
PathBuf::from(String::from_utf8_lossy(b).into_owned())
}