tab_api/
chunk.rs

1use serde::{Deserialize, Serialize};
2
3fn to_string(data: &[u8]) -> String {
4    snailquote::escape(std::str::from_utf8(data).unwrap_or("")).to_string()
5}
6
7/// Serializes an indexed chunk of stdout
8/// Send by a single running PTY process.
9#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
10pub struct OutputChunk {
11    /// The message index, generated by the PTY process.
12    pub index: usize,
13    /// Raw bytes of stdout
14    pub data: Vec<u8>,
15}
16
17impl OutputChunk {
18    /// The data buffer length
19    pub fn len(&self) -> usize {
20        self.data.len()
21    }
22
23    /// Returns true if this chunk's data contains the given index
24    pub fn contains(&self, index: usize) -> bool {
25        index >= self.start() && index < self.end()
26    }
27
28    /// Returns true if this chunk's data ends before the given index
29    pub fn is_before(&self, index: usize) -> bool {
30        self.end() <= index
31    }
32
33    /// Truncates the current output chunk, removing all data that is before the given index
34    pub fn truncate_before(&mut self, index: usize) {
35        if index <= self.start() {
36            return;
37        }
38
39        if index >= self.end() {
40            self.data.clear();
41            return;
42        }
43
44        let data_index = index - self.start();
45        self.data.drain(0..data_index);
46        self.index = index;
47    }
48
49    /// The byte index at which this buffer starts (inclusive)
50    pub fn start(&self) -> usize {
51        self.index
52    }
53
54    /// The byte index at which this buffer ends (exclusive)
55    pub fn end(&self) -> usize {
56        self.index + self.data.len()
57    }
58}
59
60impl ToString for OutputChunk {
61    fn to_string(&self) -> String {
62        to_string(self.data.as_slice())
63    }
64}
65
66/// Serialize an unindexed chunk of stdin.
67/// May be sent by multiple CLI connections.
68#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
69pub struct InputChunk {
70    /// Raw bytes of stdin
71    pub data: Vec<u8>,
72}
73
74impl InputChunk {
75    /// THe data buffer length
76    pub fn len(&self) -> usize {
77        self.data.len()
78    }
79}
80
81impl ToString for InputChunk {
82    fn to_string(&self) -> String {
83        to_string(self.data.as_slice())
84    }
85}