64 lines
1.6 KiB
Rust
64 lines
1.6 KiB
Rust
|
use super::Reflect;
|
||
|
|
||
|
pub trait Array: Reflect {
|
||
|
/// Get a borrow to the element at `idx` in the array.
|
||
|
fn get(&self, idx: usize) -> Option<&dyn Reflect>;
|
||
|
|
||
|
/// Get a mutable borrow to the element at `idx` in the array.
|
||
|
fn get_mut(&mut self, idx: usize) -> Option<&mut dyn Reflect>;
|
||
|
|
||
|
/// Returns the length of the array
|
||
|
fn len(&self) -> usize;
|
||
|
}
|
||
|
|
||
|
impl<T: Clone + Reflect, const N: usize> Array for [T; N] {
|
||
|
fn get(&self, idx: usize) -> Option<&dyn Reflect> {
|
||
|
if idx < self.len() {
|
||
|
Some(&self[idx])
|
||
|
} else {
|
||
|
None
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn get_mut(&mut self, idx: usize) -> Option<&mut dyn Reflect> {
|
||
|
if idx < self.len() {
|
||
|
Some(&mut self[idx])
|
||
|
} else {
|
||
|
None
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn len(&self) -> usize {
|
||
|
N
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[cfg(test)]
|
||
|
mod tests {
|
||
|
use crate::{Reflect, ReflectRef};
|
||
|
|
||
|
#[test]
|
||
|
fn simple() {
|
||
|
let mut arr = [0; 4];
|
||
|
arr[0] = 340;
|
||
|
arr[1] = 275;
|
||
|
arr[2] = 5;
|
||
|
arr[3] = 93;
|
||
|
|
||
|
let arr = Box::new(arr) as Box<dyn Reflect>;
|
||
|
|
||
|
if let ReflectRef::Array(arr) = arr.reflect_ref() {
|
||
|
let zero = arr.get(0).unwrap().as_any().downcast_ref::<i32>().unwrap();
|
||
|
assert_eq!(*zero, 340);
|
||
|
|
||
|
let one = arr.get(1).unwrap().as_any().downcast_ref::<i32>().unwrap();
|
||
|
assert_eq!(*one, 275);
|
||
|
|
||
|
let two = arr.get(2).unwrap().as_any().downcast_ref::<i32>().unwrap();
|
||
|
assert_eq!(*two, 5);
|
||
|
|
||
|
let three = arr.get(3).unwrap().as_any().downcast_ref::<i32>().unwrap();
|
||
|
assert_eq!(*three, 93);
|
||
|
}
|
||
|
}
|
||
|
}
|