use crate::error::MappedPageError;
use crate::page::{MappedPage, PageId};
use crate::pager::Pager;
use crate::protected::{ProtectedPageId, ProtectedPageWriter};
pub trait PageHandle<A: ?Sized> {
type Error;
type Mut<'a>: 'a
where
A: 'a,
Self: 'a;
fn get<'a>(&self, allocator: &'a A) -> Result<&'a MappedPage, Self::Error>;
fn get_mut<'a>(&self, allocator: &'a mut A) -> Result<Self::Mut<'a>, Self::Error>;
}
pub trait PageAllocator<AllocatedType: PageHandle<Self>>: Sized {
type Error;
fn alloc(&mut self) -> Result<AllocatedType, Self::Error>;
fn free(&mut self, id: AllocatedType) -> Result<(), Self::Error>;
}
impl PageHandle<Pager> for PageId {
type Error = MappedPageError;
type Mut<'a> = &'a mut MappedPage;
fn get<'a>(&self, pager: &'a Pager) -> Result<&'a MappedPage, MappedPageError> {
pager.get_page(*self)
}
fn get_mut<'a>(&self, pager: &'a mut Pager) -> Result<&'a mut MappedPage, MappedPageError> {
pager.get_page_mut(*self)
}
}
impl PageAllocator<PageId> for Pager {
type Error = MappedPageError;
fn alloc(&mut self) -> Result<PageId, MappedPageError> {
Pager::alloc(self)
}
fn free(&mut self, id: PageId) -> Result<(), MappedPageError> {
Pager::free(self, id)
}
}
impl PageHandle<Pager> for ProtectedPageId {
type Error = MappedPageError;
type Mut<'a> = ProtectedPageWriter<'a>;
fn get<'a>(&self, pager: &'a Pager) -> Result<&'a MappedPage, MappedPageError> {
pager.get_protected_page(*self)
}
fn get_mut<'a>(
&self,
pager: &'a mut Pager,
) -> Result<ProtectedPageWriter<'a>, MappedPageError> {
pager.get_protected_page_mut(*self)
}
}
impl PageAllocator<ProtectedPageId> for Pager {
type Error = MappedPageError;
fn alloc(&mut self) -> Result<ProtectedPageId, MappedPageError> {
Pager::alloc_protected(self)
}
fn free(&mut self, id: ProtectedPageId) -> Result<(), MappedPageError> {
Pager::free_protected(self, id)
}
}