use std::io;
use crate::BStackRaiiAllocator;
use bstack::BStackRange;
use crate::io_core::TryCloneIn;
use crate::types::compiled::BStackOwned;
use crate::types::traits::{AutoDrop, BStackBlock, BStackDrop, BStackRef};
pub enum BStackCow<T: BStackBlock> {
Borrowed(BStackRef<T>),
Owned(BStackOwned<T>),
}
impl<T: BStackBlock> BStackCow<T> {
pub fn borrowed(reference: BStackRef<T>) -> Self {
BStackCow::Borrowed(reference)
}
pub fn owned(owned: BStackOwned<T>) -> Self {
BStackCow::Owned(owned)
}
pub fn is_borrowed(&self) -> bool {
matches!(self, BStackCow::Borrowed(_))
}
pub fn is_owned(&self) -> bool {
matches!(self, BStackCow::Owned(_))
}
pub fn as_ref(&self) -> BStackRef<T> {
match self {
BStackCow::Owned(o) => unsafe { BStackRef::from_range(o.handle().range()) },
BStackCow::Borrowed(r) => *r,
}
}
pub fn range(&self) -> BStackRange {
self.as_ref().into_range()
}
pub fn handle(&self) -> T {
unsafe { <T as BStackBlock>::from_range(self.range()) }
}
pub fn into_owned<A: BStackRaiiAllocator>(self, allocator: &A) -> io::Result<BStackOwned<T>>
where
T: TryCloneIn,
{
match self {
BStackCow::Owned(o) => Ok(o),
BStackCow::Borrowed(r) => {
unsafe { <T as BStackBlock>::from_range(r.into_range()) }.try_clone_in(allocator)
}
}
}
pub fn to_mut<A: BStackRaiiAllocator>(
&mut self,
allocator: &A,
) -> io::Result<&mut BStackOwned<T>>
where
T: TryCloneIn,
{
if let BStackCow::Borrowed(r) = self {
let owned = unsafe { <T as BStackBlock>::from_range((*r).into_range()) }
.try_clone_in(allocator)?;
*self = BStackCow::Owned(owned);
}
match self {
BStackCow::Owned(o) => Ok(o),
BStackCow::Borrowed(_) => unreachable!("to_mut just ensured Owned"),
}
}
pub fn auto<A: BStackRaiiAllocator>(self, allocator: &A) -> AutoDrop<'_, Self, A> {
unsafe { AutoDrop::from_raw(self, allocator) }
}
}
impl<T: BStackBlock> BStackDrop for BStackCow<T> {
fn bstack_drop<A: BStackRaiiAllocator>(self, allocator: &A) -> io::Result<()> {
match self {
BStackCow::Owned(o) => o.bstack_drop(allocator),
BStackCow::Borrowed(_) => Ok(()),
}
}
}
impl<T: BStackBlock> From<BStackOwned<T>> for BStackCow<T> {
fn from(owned: BStackOwned<T>) -> Self {
BStackCow::Owned(owned)
}
}
impl<T: BStackBlock> From<BStackRef<T>> for BStackCow<T> {
fn from(reference: BStackRef<T>) -> Self {
BStackCow::Borrowed(reference)
}
}