use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{
cpp_iter, CppBox, CppDeletable, CppIterator, DynamicCast, Ptr, StaticDowncast, StaticUpcast,
};
use std::ops::Deref;
use std::{fmt, ptr, slice};
pub struct Ref<T>(ptr::NonNull<T>);
impl<T> Clone for Ref<T> {
fn clone(&self) -> Self {
Ref(self.0)
}
}
impl<T> Copy for Ref<T> {}
impl<T> fmt::Debug for Ref<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ref({:?})", self.0)
}
}
impl<T> Ref<T> {
pub unsafe fn new(ptr: Ptr<T>) -> Option<Self> {
Self::from_raw(ptr.as_raw_ptr())
}
pub unsafe fn from_raw(ptr: *const T) -> Option<Self> {
ptr::NonNull::new(ptr as *mut T).map(Ref)
}
pub unsafe fn from_raw_non_null(ptr: ptr::NonNull<T>) -> Self {
Ref(ptr)
}
pub unsafe fn as_ptr(self) -> Ptr<T> {
Ptr::from_raw(self.as_raw_ptr())
}
pub unsafe fn as_raw_ref<'a>(self) -> &'a T {
&*self.0.as_ptr()
}
pub unsafe fn as_mut_raw_ref<'a>(self) -> &'a mut T {
&mut *self.0.as_ptr()
}
pub fn as_raw_ptr(self) -> *const T {
self.0.as_ptr()
}
pub fn as_mut_raw_ptr(self) -> *mut T {
self.0.as_ptr()
}
pub unsafe fn static_upcast<U>(self) -> Ref<U>
where
T: StaticUpcast<U>,
{
StaticUpcast::static_upcast(self.as_ptr())
.as_ref()
.expect("StaticUpcast returned null on Ref input")
}
pub unsafe fn static_downcast<U>(self) -> Ref<U>
where
T: StaticDowncast<U>,
{
StaticDowncast::static_downcast(self.as_ptr())
.as_ref()
.expect("StaticDowncast returned null on Ref input")
}
pub unsafe fn dynamic_cast<U>(self) -> Option<Ref<U>>
where
T: DynamicCast<U>,
{
DynamicCast::dynamic_cast(self.as_ptr()).as_ref()
}
}
impl<V, T> Ref<V>
where
V: Data<Output = *const T> + Size,
{
pub unsafe fn as_slice<'a>(self) -> &'a [T] {
let ptr = self.data();
let size = self.size();
slice::from_raw_parts(ptr, size)
}
}
impl<V, T> Ref<V>
where
V: DataMut<Output = *mut T> + Size,
{
pub unsafe fn as_mut_slice<'a>(self) -> &'a mut [T] {
let ptr = self.data_mut();
let size = self.size();
slice::from_raw_parts_mut(ptr, size)
}
}
impl<T, T1, T2> Ref<T>
where
T: Begin<Output = CppBox<T1>> + End<Output = CppBox<T2>>,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
pub unsafe fn iter(self) -> CppIterator<T1, T2> {
cpp_iter(self.begin(), self.end())
}
}
impl<T, T1, T2> Ref<T>
where
T: BeginMut<Output = CppBox<T1>> + EndMut<Output = CppBox<T2>>,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
pub unsafe fn iter_mut(self) -> CppIterator<T1, T2> {
cpp_iter(self.begin_mut(), self.end_mut())
}
}
impl<T> Deref for Ref<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}