use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::mem::size_of;
use std::slice;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PixelType {
U8x4,
}
impl PixelType {
pub(crate) fn size(&self) -> usize {
4
}
pub(crate) fn is_aligned(&self, buffer: &[u8]) -> bool {
match self {
Self::U8x4 => unsafe { buffer.align_to::<U8x4>() }.0.is_empty(),
}
}
}
pub trait GetCount {
fn count() -> usize;
}
pub struct Count<const N: usize>;
impl<const N: usize> GetCount for Count<N> {
#[inline(always)]
fn count() -> usize {
N
}
}
pub struct Values<const N: usize>;
pub trait PixelComponent
where
Self: Sized + Copy + Debug + PartialEq + 'static,
{
type CountOfComponentValues;
}
impl PixelComponent for u8 {
type CountOfComponentValues = Values<256>;
}
impl PixelComponent for u16 {
type CountOfComponentValues = Values<65536>;
}
impl PixelComponent for i32 {
type CountOfComponentValues = Values<0>;
}
impl PixelComponent for f32 {
type CountOfComponentValues = Values<0>;
}
pub trait PixelExt
where
Self: Copy + Clone + Sized + Debug + PartialEq,
{
type Component: PixelComponent;
type CountOfComponents: GetCount;
fn count_of_components() -> usize {
Self::CountOfComponents::count()
}
fn size() -> usize {
size_of::<Self>()
}
#[cfg(target_arch = "wasm32")]
fn components(buf: &[Self]) -> &[Self::Component] {
let size = buf.len() * Self::count_of_components();
let components_ptr = buf.as_ptr() as *const Self::Component;
unsafe { slice::from_raw_parts(components_ptr, size) }
}
fn components_mut(buf: &mut [Self]) -> &mut [Self::Component] {
let size = buf.len() * Self::count_of_components();
let components_ptr = buf.as_mut_ptr() as *mut Self::Component;
unsafe { slice::from_raw_parts_mut(components_ptr, size) }
}
}
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub struct Pixel<T, C, const COUNT_OF_COMPONENTS: usize>(
pub T,
PhantomData<[C; COUNT_OF_COMPONENTS]>,
)
where
T: Sized + Copy + Clone + PartialEq + 'static,
C: PixelComponent;
impl<T, C, const COUNT_OF_COMPONENTS: usize> PixelExt for Pixel<T, C, COUNT_OF_COMPONENTS>
where
Self: Debug,
T: Sized + Copy + Clone + PartialEq + 'static,
C: PixelComponent,
{
type Component = C;
type CountOfComponents = Count<COUNT_OF_COMPONENTS>;
}
macro_rules! pixel_struct {
($name:ident, $type:tt, $comp_type:tt, $comp_count:literal, $pixel_type:expr, $doc:expr) => {
#[doc = $doc]
pub type $name = Pixel<$type, $comp_type, $comp_count>;
impl Debug for $name {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let components_ptr = self as *const _ as *const $comp_type;
let components: &[$comp_type] =
unsafe { slice::from_raw_parts(components_ptr, $comp_count) };
write!(f, "{}{:?}", stringify!($name), components)
}
}
};
}
pixel_struct!(
U8x4,
[u8; 4],
u8,
4,
PixelType::U8x4,
"Four bytes per pixel (RGBA8, RGBx8, CMYK8 and other)"
);