use core::ops::{Deref, DerefMut};
use core::fmt;
#[cfg(feature = "std")]
use std::boxed::Box;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::boxed::Box;
#[cfg(feature = "std")]
use std::vec::Vec;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec::Vec;
pub enum Managed<'a, T: 'a + ?Sized> {
Borrowed(&'a mut T),
#[cfg(any(feature = "std", feature = "alloc"))]
Owned(Box<T>)
}
impl<'a, T: 'a + ?Sized> fmt::Debug for Managed<'a, T>
where T: fmt::Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Managed::Borrowed(ref x) => write!(f, "Borrowed({:?})", x),
#[cfg(any(feature = "std", feature = "alloc"))]
&Managed::Owned(ref x) => write!(f, "Owned({:?})", x)
}
}
}
impl<'a, T: 'a + ?Sized> From<&'a mut T> for Managed<'a, T> {
fn from(value: &'a mut T) -> Self {
Managed::Borrowed(value)
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, T: ?Sized + 'a> From<Box<T>> for Managed<'a, T> {
fn from(value: Box<T>) -> Self {
Managed::Owned(value)
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, T: 'a> From<Vec<T>> for Managed<'a, [T]> {
fn from(value: Vec<T>) -> Self {
Managed::Owned(value.into_boxed_slice())
}
}
impl<'a, T: 'a + ?Sized> Deref for Managed<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match self {
&Managed::Borrowed(ref value) => value,
#[cfg(any(feature = "std", feature = "alloc"))]
&Managed::Owned(ref value) => value
}
}
}
impl<'a, T: 'a + ?Sized> DerefMut for Managed<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
&mut Managed::Borrowed(ref mut value) => value,
#[cfg(any(feature = "std", feature = "alloc"))]
&mut Managed::Owned(ref mut value) => value
}
}
}