Skip to main content

little_kitty/
control.rs

1use std::io::{self, Write};
2
3//
4// Controls
5//
6
7/// Vector of Kitty graphics protocol controls.
8#[derive(Clone, Debug, Default)]
9pub struct Controls(pub Vec<(char, ControlValue)>);
10
11impl Controls {
12    /// Whether we are empty.
13    pub fn is_empty(&self) -> bool {
14        self.0.is_empty()
15    }
16
17    /// Add control.
18    pub fn add<ControlT>(&mut self, code: char, value: ControlT)
19    where
20        ControlT: Into<ControlValue>,
21    {
22        self.0.push((code, value.into()));
23    }
24
25    /// Add control.
26    ///
27    /// Chainable.
28    pub fn with<ControlT>(mut self, code: char, value: ControlT) -> Self
29    where
30        ControlT: Into<ControlValue>,
31    {
32        self.add(code, value);
33        self
34    }
35
36    /// Write.
37    pub fn write<WriteT>(&self, mut writer: WriteT) -> io::Result<()>
38    where
39        WriteT: io::Write,
40    {
41        let mut iterator = self.0.iter().peekable();
42        while let Some((code, value)) = iterator.next() {
43            write!(writer, "{}=", *code)?;
44            value.write(&mut writer)?;
45            if iterator.peek().is_some() {
46                write!(writer, ",")?;
47            }
48        }
49        Ok(())
50    }
51}
52
53//
54// ControlValue
55//
56
57/// Kitty graphics protocol control value.
58#[derive(Clone, Copy, Debug)]
59pub enum ControlValue {
60    /// Character.
61    Char(char),
62
63    /// Integer.
64    Integer(i32),
65}
66
67impl ControlValue {
68    /// Write.
69    pub fn write<WriteT>(&self, mut writer: WriteT) -> io::Result<()>
70    where
71        WriteT: Write,
72    {
73        match self {
74            Self::Char(char_) => write!(writer, "{}", char_),
75            Self::Integer(integer) => write!(writer, "{}", integer.to_string()),
76        }
77    }
78}
79
80impl From<char> for ControlValue {
81    fn from(char_: char) -> Self {
82        Self::Char(char_)
83    }
84}
85
86impl From<i32> for ControlValue {
87    fn from(integer: i32) -> Self {
88        Self::Integer(integer)
89    }
90}
91
92impl From<usize> for ControlValue {
93    fn from(integer: usize) -> Self {
94        (integer as i32).into()
95    }
96}