use crate::{
report::system_panic,
runtime::{
Downcast,
Origin,
Provider,
RuntimeError,
RuntimeResult,
ScriptType,
TypeHint,
Upcast,
},
};
impl<'a, const N: usize, T> Downcast<'a> for [T; N]
where
T: ScriptType,
{
fn downcast(origin: Origin, provider: Provider<'a>) -> RuntimeResult<Self> {
let mut vector = provider.to_owned().take_vec::<T>(origin)?;
let length = vector.len();
if length < N {
return Err(RuntimeError::ShortSlice {
access_origin: origin,
minimum: N,
actual: length,
});
}
if length > N {
vector.truncate(N);
}
match vector.try_into() {
Ok(array) => Ok(array),
Err(_) => {
system_panic!("Downcasting of vector to array failure.")
}
}
}
#[inline(always)]
fn hint() -> TypeHint {
TypeHint::Type(T::type_meta())
}
}
impl<'a, const N: usize, T> Downcast<'a> for &'a [T; N]
where
T: ScriptType,
{
fn downcast(origin: Origin, provider: Provider<'a>) -> RuntimeResult<Self> {
let slice = provider
.to_borrowed(&origin)?
.borrow_slice_ref::<T>(origin)?;
let length = slice.len();
if length < N {
return Err(RuntimeError::ShortSlice {
access_origin: origin,
minimum: N,
actual: length,
});
}
match slice.try_into() {
Ok(array) => Ok(array),
Err(_) => {
system_panic!("Downcasting of slice ref to array failure.")
}
}
}
#[inline(always)]
fn hint() -> TypeHint {
TypeHint::Type(T::type_meta())
}
}
impl<'a, const N: usize, T> Downcast<'a> for &'a mut [T; N]
where
T: ScriptType,
{
fn downcast(origin: Origin, provider: Provider<'a>) -> RuntimeResult<Self> {
let slice = provider
.to_borrowed(&origin)?
.borrow_slice_mut::<T>(origin)?;
let length = slice.len();
if length < N {
return Err(RuntimeError::ShortSlice {
access_origin: origin,
minimum: N,
actual: length,
});
}
match slice.try_into() {
Ok(array) => Ok(array),
Err(_) => {
system_panic!("Downcasting of slice ref to array failure.")
}
}
}
#[inline(always)]
fn hint() -> TypeHint {
TypeHint::Type(T::type_meta())
}
}
impl<'a, const N: usize, T> Upcast<'a> for [T; N]
where
T: ScriptType,
{
type Output = Vec<T>;
#[inline]
fn upcast(_origin: Origin, this: Self) -> RuntimeResult<Self::Output> {
Ok(Vec::from(this))
}
#[inline(always)]
fn hint() -> TypeHint {
TypeHint::Type(T::type_meta())
}
}
impl<'a, const N: usize, T> Upcast<'a> for &'a [T; N]
where
T: ScriptType,
{
type Output = &'a [T];
#[inline]
fn upcast(_origin: Origin, this: Self) -> RuntimeResult<Self::Output> {
Ok(this)
}
#[inline(always)]
fn hint() -> TypeHint {
TypeHint::Type(T::type_meta())
}
}
impl<'a, const N: usize, T> Upcast<'a> for &'a mut [T; N]
where
T: ScriptType,
{
type Output = &'a mut [T];
#[inline]
fn upcast(_origin: Origin, this: Self) -> RuntimeResult<Self::Output> {
Ok(this)
}
#[inline(always)]
fn hint() -> TypeHint {
TypeHint::Type(T::type_meta())
}
}