1use std::collections::VecDeque;
8
9use serde_json::{Value, json};
10
11#[cfg(test)]
12mod tests;
13
14#[derive(Debug, Clone)]
16pub struct TailBuffer {
17 limit: usize,
18 data: VecDeque<u8>,
19 truncated: bool,
20}
21
22impl TailBuffer {
23 #[must_use]
25 pub fn new(limit: usize) -> Self {
26 Self {
27 limit,
28 data: VecDeque::new(),
29 truncated: false,
30 }
31 }
32
33 pub fn push(&mut self, bytes: &[u8]) {
35 self.data.extend(bytes);
36 if self.data.len() > self.limit {
37 let excess = self.data.len() - self.limit;
38 self.data.drain(..excess);
39 self.truncated = true;
40 }
41 }
42
43 #[must_use]
45 pub const fn truncated(&self) -> bool {
46 self.truncated
47 }
48
49 #[must_use]
52 pub fn text(&self) -> String {
53 let bytes: Vec<u8> = self.data.iter().copied().collect();
54 let start = if self.truncated {
55 bytes
56 .iter()
57 .take(3)
58 .take_while(|b| (**b & 0b1100_0000) == 0b1000_0000)
59 .count()
60 } else {
61 0
62 };
63 String::from_utf8_lossy(&bytes[start..]).replace('\0', "\u{fffd}")
64 }
65}
66
67#[must_use]
69pub const fn signal_exit_code(signal: i32) -> i32 {
70 128 + signal
71}
72
73#[must_use]
75pub fn process_result(stdout: &TailBuffer, stderr: &TailBuffer, exit_code: i32) -> Value {
76 json!({
77 "stdout": stdout.text(),
78 "stderr": stderr.text(),
79 "exit_code": exit_code,
80 "stdout_truncated": stdout.truncated(),
81 "stderr_truncated": stderr.truncated(),
82 })
83}