use crate::alpha::AlphaLast;
mod has_gray;
pub use has_gray::HasGray;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "bytemuck", derive(bytemuck::Zeroable, bytemuck::Pod))]
#[repr(transparent)]
pub struct Gray<T> {
gray: T,
}
impl<T> Gray<T> {
#[must_use]
pub const fn new(gray: T) -> Self {
Self { gray }
}
#[must_use]
pub const fn gray(&self) -> T
where
T: Copy,
{
self.gray
}
}
impl<T> HasGray for Gray<T>
where
T: Copy,
{
type Component = T;
fn gray(&self) -> Self::Component {
self.gray
}
fn set_gray(&mut self, value: Self::Component) {
self.gray = value;
}
}
pub type Gray8 = Gray<u8>;
pub type Gray16 = Gray<u16>;
pub type GrayAlpha<T> = AlphaLast<T, Gray<T>>;
impl<T> HasGray for GrayAlpha<T>
where
T: Copy,
{
type Component = T;
fn gray(&self) -> Self::Component {
self.color().gray()
}
fn set_gray(&mut self, value: Self::Component) {
*self = Self::with_color(self.alpha(), self.color().with_gray(value));
}
}
pub type GrayAlpha8 = GrayAlpha<u8>;
impl GrayAlpha8 {
#[must_use]
pub const fn new(gray: u8, alpha: u8) -> Self {
Self::with_color(alpha, Gray8::new(gray))
}
}
pub type GrayAlpha16 = GrayAlpha<u16>;
impl GrayAlpha16 {
#[must_use]
pub const fn new(gray: u16, alpha: u16) -> Self {
Self::with_color(alpha, Gray16::new(gray))
}
}
pub type GrayF32 = Gray<f32>;
pub type GrayAlphaF32 = AlphaLast<f32, GrayF32>;
impl GrayAlphaF32 {
#[must_use]
pub const fn new(gray: f32, alpha: f32) -> Self {
Self::with_color(alpha, Gray::new(gray))
}
}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use super::*;
#[test]
fn gray8_trait_accessors() {
let mut gray = Gray8::new(128);
assert_eq!(HasGray::gray(&gray), 128);
HasGray::set_gray(&mut gray, 200);
assert_eq!(HasGray::gray(&gray), 200);
}
#[test]
fn gray_alpha16_new() {
let gray_alpha = GrayAlpha16::new(128, 255);
assert_eq!(gray_alpha.gray(), 128);
assert_eq!(gray_alpha.alpha(), 255);
}
#[test]
fn gray_alphaf32_new() {
let gray_alpha = GrayAlphaF32::new(128.0, 255.0);
assert_eq!(gray_alpha.gray(), 128.0);
assert_eq!(gray_alpha.alpha(), 255.0);
}
}