fast image operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use umath::FF32;
pub trait Unfloatify<const N: usize> {
    /// computes 255 * n, for all elements
    fn unfloat(self) -> [u8; N];
}

#[inline(always)]
/// computes 255 * n
pub fn unfloat(n: FF32) -> u8 {
    // SAFETY: n is 0..=1
    unsafe { *(FF32::new(255.0) * n) as u8 }
}

impl<const N: usize> Unfloatify<N> for [FF32; N] {
    fn unfloat(self) -> [u8; N] {
        self.map(unfloat)
    }
}

#[rustfmt::skip]
impl<const N:usize>Unfloatify<N>for[u8; N]{fn unfloat(self)->[u8;N]{self}}

pub trait Floatify<const N: usize> {
    /// computes n / 255, for all elements
    fn float(self) -> [FF32; N];
}

/// computes n / 255
pub fn float(n: u8) -> FF32 {
    // SAFETY: 0..=255 / 0..=255 maynt ever be NAN / INF
    unsafe { FF32::new(n as f32) / FF32::new(255.0) }
}

impl<const N: usize> Floatify<N> for [u8; N] {
    fn float(self) -> [FF32; N] {
        self.map(float)
    }
}

#[rustfmt::skip]
impl<const N:usize>Floatify<N>for[FF32;N]{fn float(self)->[FF32;N]{self}}

pub trait PMap<T, R, const N: usize> {
    /// think of it like a `a.zip(b).map(f).collect::<[]>()`
    fn pmap(self, with: Self, f: impl FnMut(T, T) -> R) -> [R; N];
}

impl<const N: usize, T: Copy, R: Copy> PMap<T, R, N> for [T; N] {
    fn pmap(self, with: Self, mut f: impl FnMut(T, T) -> R) -> [R; N] {
        let mut iter = self.into_iter().zip(with).map(|(a, b)| f(a, b));
        std::array::from_fn(|_| iter.next().unwrap())
    }
}

pub trait Trunc<T, const N: usize> {
    /// it does `a[..a.len() - 1].try_into().unwrap()``.
    fn trunc(&self) -> [T; N - 1];
}

impl<const N: usize, T: Copy> Trunc<T, N> for [T; N] {
    fn trunc(&self) -> [T; N - 1] {
        self[..N - 1].try_into().unwrap()
    }
}

#[test]
fn trunc() {
    let x = [1];
    assert_eq!(x.trunc(), []);
    let x = [1, 2, 3, 4];
    assert_eq!(x.trunc(), [1, 2, 3]);
}