This commit is contained in:
2023-06-12 17:39:07 +02:00
parent 59f91e2f6b
commit 9854e0c0a8
45 changed files with 4708 additions and 400 deletions

58
lib/src/rgb.rs Normal file
View File

@ -0,0 +1,58 @@
use bytemuck::{cast_slice, Pod, Zeroable};
use core::{
fmt::{self, Debug},
ops::Div,
};
/// An Rgb value that can be safely transmuted to u32 for use with Ws2812.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
pub struct Rgb(u32);
impl Rgb {
#[inline(always)]
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self(u32::from_be_bytes([g, r, b, 0]))
}
/// Get the red, green, and blue components of this Rgb.
#[inline(always)]
pub const fn components(&self) -> [u8; 3] {
let [g, r, b, _] = self.0.to_be_bytes();
[r, g, b]
}
#[inline(always)]
pub fn slice_as_u32s(rgbs: &[Rgb]) -> &[u32] {
cast_slice(rgbs)
}
}
impl Debug for Rgb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let [r, g, b] = self.components();
f.debug_tuple("Rgb").field(&r).field(&g).field(&b).finish()
}
}
impl Div<u8> for Rgb {
type Output = Rgb;
fn div(self, d: u8) -> Self::Output {
let [r, g, b] = self.components();
Rgb::new(r / d, g / d, b / d)
}
}
#[cfg(all(target_arch = "x86_64", test))]
mod tests {
use super::*;
use bytemuck::cast;
#[test]
fn test_rgb_as_u32() {
let rgb = Rgb::new(0x11, 0x22, 0xCC);
let rgb_u32: u32 = cast(rgb);
assert_eq!(rgb_u32, 0x2211CC00);
}
}