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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use super::{b64, Basic};
use crate::Image;
use core::intrinsics::transmute_unchecked as transmute;
use std::borrow::Cow;
use std::fmt::{Debug, Display, Formatter, Result, Write};

/// Outputs [Kitty Graphics Protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol) encoded data.
pub struct Kitty<T: AsRef<[u8]>, const N: usize>(pub Image<T, N>);

impl<T: AsRef<[u8]>, const N: usize> std::ops::Deref for Kitty<T, N> {
    type Target = Image<T, N>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T: AsRef<[u8]>, const N: usize> Display for Kitty<T, N>
where
    [(); N]: Basic,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        self.write(f)
    }
}

impl<T: AsRef<[u8]>, const N: usize> Debug for Kitty<T, N>
where
    [(); N]: Basic,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        self.write(f)
    }
}

impl<T: AsRef<[u8]>, const N: usize> Kitty<T, N> {
    /// Write out kitty gfx data.
    pub fn write(&self, to: &mut impl Write) -> Result
    where
        [(); N]: Basic,
    {
        macro_rules! cast {
            ($n:literal) => {
                (
                    Cow::Owned(
                        <Image<Box<[u8]>, 3>>::from({
                            // SAFETY: ...
                            unsafe { self.as_ref().trans::<$n>() }
                        })
                        .take_buffer()
                        .to_vec(),
                    ),
                    "24",
                )
            };
        }
        let (bytes, dtype) = {
            match N {
                1 => cast!(1),
                2 => cast!(2),
                3 => (Cow::from(self.bytes()), "24"),
                4 => (Cow::from(self.bytes()), "32"),
                _ => unreachable!(),
            }
        };
        let (w, h) = (self.width(), self.height());

        let enc = b64::encode(&bytes);
        let mut chunks = enc
            .as_bytes()
            .chunks(4096)
            // SAFETY: b64
            .map(|x| unsafe { std::str::from_utf8_unchecked(x) });

        let last = chunks.len();
        const H: &str = "_G";
        const MORE: &str = "m";

        const DISPLAY: char = 'T';
        const ACTION: char = 'a';
        const DATATYPE: char = 'f';
        const TYPE: char = 't';
        const DIRECT: char = 'd';

        const E: &str = r"\";

        let payload = chunks.next().unwrap();
        let more = (last > 1) as u8;
        write!(to, "{H}{DATATYPE}={dtype},{ACTION}={DISPLAY},{TYPE}={DIRECT},s={w},v={h},{MORE}={more};{payload}{E}")?;

        for (payload, i) in chunks.zip(2..) {
            let more = (i != last) as u8;
            write!(to, "{H}{MORE}={more};{payload}{E}")?;
        }
        Ok(())
    }
}

#[test]
fn test() {
    let x = Image::<_, 3>::open("tdata/cat.png");
    use std::hash::Hasher;
    let mut h = std::hash::DefaultHasher::new();
    h.write(Kitty(x).to_string().as_bytes());
    assert_eq!(h.finish(), 0x1cc13114bcf3cc3);
}