#[cfg(feature = "array_from_image")]
use image::DynamicImage;
#[cfg(feature = "array_from_image")]
use image::GenericImageView;
#[cfg(feature = "array_from_image")]
use std::path::Path;
use std::ptr;
#[derive(Debug)]
#[repr(transparent)]
pub struct ScreenArrayBase<T, const W: usize, const H: usize> {
arr_ptr: *mut [[T; W]; H],
}
impl<T, const W: usize, const H: usize> ScreenArrayBase<T, W, H> {
const _CHECK: () = {
let _ = W
.checked_mul(H)
.expect("[ScreenArrayBase<T,W,H>] W * H overflows usize");
};
pub fn new(array: [[T; W]; H]) -> Self {
let arr_box = Box::new(array);
let arr_ptr = Box::into_raw(arr_box);
Self { arr_ptr }
}
pub fn new_uninit() -> Self {
let boxed = Box::<[[T; W]; H]>::new_uninit();
let arr_box = unsafe { boxed.assume_init() };
let arr_ptr = Box::into_raw(arr_box);
Self { arr_ptr }
}
pub unsafe fn from_raw(arr_ptr: *mut [[T; W]; H]) -> Self {
assert!(
!arr_ptr.is_null(),
"[ScreenArrayBase<T,W,H>::from_raw] null pointer"
);
Self { arr_ptr }
}
pub fn drop(&mut self) {
unsafe {
let _ = Box::from_raw(self.arr_ptr);
self.arr_ptr = ptr::null_mut();
}
}
pub unsafe fn drop_it(arr_ptr: *mut [[T; W]; H]) {
unsafe {
let _ = Box::from_raw(arr_ptr);
}
}
pub const fn size() -> (usize, usize) {
(H, W)
}
pub fn get_mut(&self) -> &mut [[T; W]; H] {
unsafe { &mut *self.arr_ptr }
}
pub fn get(&self) -> &[[T; W]; H] {
unsafe { &*self.arr_ptr }
}
pub unsafe fn get_from_index_mut(&self, x: usize, y: usize) -> &mut T {
unsafe {
let arr: &mut [[T; W]; H] = &mut *self.arr_ptr;
&mut arr[y][x]
}
}
pub unsafe fn get_from_index(&self, x: usize, y: usize) -> &T {
unsafe {
let arr: &[[T; W]; H] = &*self.arr_ptr;
&arr[y][x]
}
}
pub fn get_ptr(&self) -> *mut [[T; W]; H] {
self.arr_ptr
}
pub unsafe fn get_ptr_num(&self) -> usize {
self.arr_ptr as usize
}
pub unsafe fn get_from_index_ptr(&self, x: usize, y: usize) -> *mut T {
unsafe { &mut (*self.arr_ptr)[y][x] as *mut T }
}
pub unsafe fn get_from_index_ptr_selfless(self_ptr: usize, x: usize, y: usize) -> *mut T {
unsafe {
let arr = self_ptr as *mut [[T; W]; H];
&mut (*arr)[y][x]
}
}
pub fn as_slice(&self) -> &[T] {
unsafe {
let ptr = self.arr_ptr as *const T;
std::slice::from_raw_parts(ptr, W * H)
}
}
pub fn as_mut_slice(&self) -> &mut [T] {
unsafe {
let ptr = self.arr_ptr as *mut T;
std::slice::from_raw_parts_mut(ptr, W * H)
}
}
}
impl<T: num_traits::Zero, const W: usize, const H: usize> ScreenArrayBase<T, W, H> {
pub fn zero() -> Self {
let this = Self::new_uninit();
let slice = this.as_mut_slice();
for elem in slice.iter_mut() {
*elem = T::zero();
}
this
}
}
impl<T: num_traits::Zero, const W: usize, const H: usize> Default for ScreenArrayBase<T, W, H> {
fn default() -> Self {
Self::zero()
}
}
unsafe impl<T: Send, const W: usize, const H: usize> Send for ScreenArrayBase<T, W, H> {}
unsafe impl<T: Sync, const W: usize, const H: usize> Sync for ScreenArrayBase<T, W, H> {}
#[cfg(feature = "array_from_image")]
impl<T, const W: usize, const H: usize> ScreenArrayBase<T, W, H> {
pub fn set_image<P: AsRef<Path>, F: Fn(u32) -> T>(
&mut self,
path: P,
converter: F,
) -> Result<(), Box<dyn std::error::Error>> {
let path = path.as_ref();
let img = image::open(path)?;
let (width, height) = img.dimensions();
if width as usize != W || height as usize != H {
return Err("[ScreenArrayBase<T,W,H>::set_image] image dimensions do not match".into());
}
let raw = img.into_rgba8().into_raw();
for i in 0..H * W {
let r = raw[i * 4] as u32;
let g = raw[i * 4 + 1] as u32;
let b = raw[i * 4 + 2] as u32;
let a = raw[i * 4 + 3] as u32;
let packed = a << 24 | r << 16 | g << 8 | b;
let pixel = converter(packed);
unsafe {
*self.get_from_index_mut(i % W, i / W) = pixel;
}
}
Ok(())
}
pub fn from_image<P: AsRef<Path>, F: Fn(u32) -> T>(
path: P,
converter: F,
) -> Result<ScreenArrayBase<T, W, H>, Box<dyn std::error::Error>> {
let mut arr = ScreenArrayBase::new_uninit();
arr.set_image(path, converter)?;
Ok(arr)
}
}
#[cfg(feature = "array_from_image")]
impl<T: From<u32>, const W: usize, const H: usize> TryFrom<DynamicImage>
for ScreenArrayBase<T, W, H>
{
type Error = Box<dyn std::error::Error>;
fn try_from(value: DynamicImage) -> Result<Self, Self::Error> {
let (width, height) = value.dimensions();
if width as usize != W || height as usize != H {
return Err("[ScreenArrayBase<T,W,H>::try_from] image dimensions do not match".into());
}
let raw = value.into_rgba8().into_raw();
let pixels: Vec<T> = try_from_image_inner(raw);
let ptr = pixels.leak().as_mut_ptr() as *mut [[T; W]; H];
Ok(unsafe { ScreenArrayBase::from_raw(ptr) })
}
}
#[cfg(feature = "array_from_image")]
pub(super) fn try_from_image_inner<T: From<u32>>(raw: Vec<u8>) -> Vec<T> {
raw.chunks_exact(4)
.map(|chunk| {
let r = chunk[0] as u32;
let g = chunk[1] as u32;
let b = chunk[2] as u32;
let a = chunk[3] as u32;
let packed = a << 24 | r << 16 | g << 8 | b;
T::from(packed)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::ops::Add;
#[test]
fn zero_and_size() {
let mut arr = ScreenArrayBase::<u32, 4, 3>::zero();
assert_eq!(arr.as_slice(), &[0u32; 12]);
assert_eq!(ScreenArrayBase::<u32, 4, 3>::size(), (3, 4));
arr.drop();
}
#[test]
fn new_and_read_write() {
let mut arr = ScreenArrayBase::<u32, 4, 3>::new([[1u32; 4]; 3]);
assert_eq!(arr.get()[0][0], 1);
assert_eq!(arr.get()[2][3], 1);
arr.as_mut_slice()[5] = 42;
assert_eq!(arr.as_slice()[5], 42);
unsafe {
assert_eq!(*arr.get_from_index(1, 1), 42);
*arr.get_from_index_mut(0, 0) = 7;
assert_eq!(*arr.get_from_index(0, 0), 7);
}
arr.drop();
}
#[derive(Clone, Debug, PartialEq)]
#[repr(transparent)]
struct CustomPixel(u8);
impl Add<Self> for CustomPixel {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
CustomPixel(self.0 + rhs.0)
}
}
impl num_traits::Zero for CustomPixel {
fn zero() -> Self {
CustomPixel(0)
}
fn is_zero(&self) -> bool {
self.0 == 0
}
}
#[test]
fn generic_custom_type() {
let mut arr = ScreenArrayBase::<CustomPixel, 2, 2>::zero();
assert_eq!(
arr.as_slice(),
&[
CustomPixel(0),
CustomPixel(0),
CustomPixel(0),
CustomPixel(0)
]
);
arr.drop();
let mut arr2 = ScreenArrayBase::<CustomPixel, 2, 2>::new([
[CustomPixel(1), CustomPixel(2)],
[CustomPixel(3), CustomPixel(4)],
]);
assert_eq!(arr2.get()[1][0], CustomPixel(3));
arr2.drop();
}
}