use core::cell::{BorrowError, BorrowMutError, Ref, RefMut};
use core::ops::DerefMut;
use loca::*;
#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct RefCell<T: ?Sized>(::core::cell::RefCell<T>);
impl<T> From<T> for RefCell<T> {
#[inline]
fn from(x: T) -> Self { RefCell(From::from(x)) }
}
impl<T: ?Sized> RefCell<T> {
#[inline]
fn try_borrow(&self) -> Result<Ref<T>, BorrowError> { self.0.try_borrow() }
#[inline]
fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> { self.0.try_borrow_mut() }
}
unsafe impl<'a, A: Alloc + ?Sized> Alloc for &'a RefCell<A> {
unsafe fn alloc(&mut self, l: Layout) -> Result<*mut u8, AllocErr> { b(self, l, |a| a.alloc(l)) }
unsafe fn dealloc(&mut self, ptr: *mut u8, l: Layout) { match self.try_borrow_mut() { Ok(mut a) => a.dealloc(ptr, l), _ => () } }
unsafe fn realloc(&mut self, ptr: *mut u8, old_l: Layout, new_l: Layout) -> Result<*mut u8, AllocErr> { b(self, new_l, |a| a.realloc(ptr, old_l, new_l)) }
unsafe fn alloc_zeroed(&mut self, l: Layout) -> Result<*mut u8, AllocErr> { b(self, l, |a| a.alloc_zeroed(l)) }
unsafe fn alloc_excess(&mut self, l: Layout) -> Result<Excess, AllocErr> { b(self, l, |a| a.alloc_excess(l)) }
unsafe fn realloc_excess(&mut self, ptr: *mut u8, old_l: Layout, new_l: Layout) -> Result<Excess, AllocErr> { b(self, new_l, |a| a.realloc_excess(ptr, old_l, new_l)) }
unsafe fn resize_in_place(&mut self, ptr: *mut u8, old_l: Layout, new_l: Layout) -> Result<(), CannotReallocInPlace> {
match self.try_borrow_mut() { Ok(mut a) => a.resize_in_place(ptr, old_l, new_l), _ => Err(CannotReallocInPlace) }
}
fn usable_size(&self, l: Layout) -> (usize, usize) {
match self.try_borrow() { Ok(a) => a.usable_size(l), _ => (l.size(), l.size()) }
}
}
fn b<A: ?Sized, B, F: FnOnce(&mut A) -> Result<B, AllocErr>>(a: &RefCell<A>, l: Layout, f: F) -> Result<B, AllocErr> {
match a.try_borrow_mut() { Ok(mut a) => f(a.deref_mut()), _ => Err(AllocErr::Exhausted { request: l }) }
}