use super::FixedBuf;
use super::plumbing;
use crate::buf::IoBufMut;
use crate::runtime::CONTEXT;
use std::cell::RefCell;
use std::io;
use std::rc::Rc;
#[derive(Clone)]
pub struct FixedBufRegistry<T: IoBufMut> {
inner: Rc<RefCell<plumbing::Registry<T>>>,
}
impl<T: IoBufMut> FixedBufRegistry<T> {
pub fn new(bufs: impl IntoIterator<Item = T>) -> Self {
FixedBufRegistry {
inner: Rc::new(RefCell::new(plumbing::Registry::new(bufs.into_iter()))),
}
}
pub fn register(&self) -> io::Result<()> {
CONTEXT.with(|x| {
x.handle()
.as_ref()
.expect("Not in a runtime context")
.register_buffers(Rc::clone(&self.inner) as _)
})
}
pub fn unregister(&self) -> io::Result<()> {
CONTEXT.with(|x| {
x.handle()
.as_ref()
.expect("Not in a runtime context")
.unregister_buffers(Rc::clone(&self.inner) as _)
})
}
pub fn check_out(&self, index: usize) -> Option<FixedBuf> {
let mut inner = self.inner.borrow_mut();
inner.check_out(index).map(|data| {
let registry = Rc::clone(&self.inner);
unsafe { FixedBuf::new(registry, data) }
})
}
}