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
use serde::{Deserialize, Serialize};

fn to_string(data: &[u8]) -> String {
    snailquote::escape(std::str::from_utf8(data).unwrap_or("")).to_string()
}

/// Serializes an indexed chunk of stdout
/// Send by a single running PTY process.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct OutputChunk {
    /// The message index, generated by the PTY process.
    pub index: usize,
    /// Raw bytes of stdout
    pub data: Vec<u8>,
}

impl OutputChunk {
    /// The data buffer length
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns true if this chunk's data contains the given index
    pub fn contains(&self, index: usize) -> bool {
        index >= self.start() && index < self.end()
    }

    /// Returns true if this chunk's data ends before the given index
    pub fn is_before(&self, index: usize) -> bool {
        self.end() <= index
    }

    /// Truncates the current output chunk, removing all data that is before the given index
    pub fn truncate_before(&mut self, index: usize) {
        if index <= self.start() {
            return;
        }

        if index >= self.end() {
            self.data.clear();
            return;
        }

        let data_index = index - self.start();
        self.data.drain(0..data_index);
        self.index = index;
    }

    /// The byte index at which this buffer starts (inclusive)
    pub fn start(&self) -> usize {
        self.index
    }

    /// The byte index at which this buffer ends (exclusive)
    pub fn end(&self) -> usize {
        self.index + self.data.len()
    }
}

impl ToString for OutputChunk {
    fn to_string(&self) -> String {
        to_string(self.data.as_slice())
    }
}

/// Serialize an unindexed chunk of stdin.
/// May be sent by multiple CLI connections.
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct InputChunk {
    /// Raw bytes of stdin
    pub data: Vec<u8>,
}

impl InputChunk {
    /// THe data buffer length
    pub fn len(&self) -> usize {
        self.data.len()
    }
}

impl ToString for InputChunk {
    fn to_string(&self) -> String {
        to_string(self.data.as_slice())
    }
}