Skip to main content

vtcode_bash_runner/
stream.rs

1use std::io;
2use tokio::io::{AsyncBufRead, AsyncBufReadExt};
3
4/// Result of a bounded line read.
5#[derive(Debug)]
6pub enum ReadLineResult {
7    Line(Vec<u8>),
8    Truncated(Vec<u8>),
9    Eof,
10}
11
12/// Read a line with a size limit, preventing unbounded memory growth.
13pub(crate) async fn read_line_with_limit<R: AsyncBufRead + Unpin>(
14    reader: &mut R,
15    buf: &mut Vec<u8>,
16    max_len: usize,
17) -> io::Result<ReadLineResult> {
18    buf.clear();
19
20    loop {
21        let available = reader.fill_buf().await?;
22        if available.is_empty() {
23            // EOF with a partial line left in the buffer: report it as a
24            // (truncated, if it overran) line rather than silently dropping
25            // the data we already read.
26            return Ok(if buf.is_empty() {
27                ReadLineResult::Eof
28            } else if buf.len() <= max_len {
29                ReadLineResult::Line(std::mem::take(buf))
30            } else {
31                ReadLineResult::Truncated(std::mem::take(buf))
32            });
33        }
34
35        if let Some(pos) = memchr::memchr(b'\n', available) {
36            // Found a newline within the available buffer
37            let to_read = pos + 1;
38            let would_be_total = buf.len() + to_read;
39
40            if would_be_total <= max_len {
41                // Line fits within the limit
42                debug_assert!(to_read <= available.len());
43                #[expect(
44                    clippy::indexing_slicing,
45                    reason = "to_read is a memchr hit plus one, so it never exceeds available.len()"
46                )]
47                let chunk = &available[..to_read];
48                buf.extend_from_slice(chunk);
49                reader.consume(to_read);
50                return Ok(ReadLineResult::Line(std::mem::take(buf)));
51            } else {
52                // Line would exceed the limit: fill the remaining space, then
53                // report truncation. Consume the whole line from the reader so
54                // the next read starts at a fresh line.
55                let remaining_space = max_len.saturating_sub(buf.len());
56                if remaining_space > 0 {
57                    debug_assert!(remaining_space <= available.len());
58                    #[expect(
59                        clippy::indexing_slicing,
60                        reason = "would_be_total > max_len implies remaining_space < to_read <= available.len()"
61                    )]
62                    let chunk = &available[..remaining_space];
63                    buf.extend_from_slice(chunk);
64                }
65                reader.consume(to_read);
66                return Ok(ReadLineResult::Truncated(std::mem::take(buf)));
67            }
68        }
69
70        // No newline found in current buffer, add what we can
71        let len = available.len();
72        let would_be_total = buf.len() + len;
73
74        if would_be_total <= max_len {
75            // Buffer content fits within the limit
76            buf.extend_from_slice(available);
77            reader.consume(len);
78        } else {
79            // Would exceed the limit, add only what fits and report truncation
80            // immediately: continuing would either grow the buffer past
81            // `max_len` or block forever on a stream that never sends `\n`.
82            let remaining_space = max_len.saturating_sub(buf.len());
83            if remaining_space > 0 {
84                debug_assert!(remaining_space <= available.len());
85                #[expect(
86                    clippy::indexing_slicing,
87                    reason = "would_be_total > max_len implies remaining_space < available.len()"
88                )]
89                let chunk = &available[..remaining_space];
90                buf.extend_from_slice(chunk);
91            }
92            reader.consume(len);
93            return Ok(ReadLineResult::Truncated(std::mem::take(buf)));
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::{ReadLineResult, read_line_with_limit};
101    use tokio::io::BufReader;
102
103    #[tokio::test]
104    async fn read_line_with_limit_truncates() -> std::io::Result<()> {
105        let data = "hello world\n";
106        let mut reader = BufReader::new(data.as_bytes());
107        let mut buf = Vec::new();
108
109        let result = read_line_with_limit(&mut reader, &mut buf, 5).await?;
110        match result {
111            ReadLineResult::Truncated(bytes) => {
112                assert!(!bytes.is_empty());
113            }
114            other => panic!("expected truncation, got {other:?}"),
115        }
116        Ok(())
117    }
118
119    #[tokio::test]
120    async fn read_line_with_limit_no_newline_stream_returns_truncated() -> std::io::Result<()> {
121        // A stream with no '\n' must terminate with Truncated once the limit is
122        // reached instead of growing the buffer or blocking forever.
123        let data = vec![b'a'; 10_000];
124        let mut reader = BufReader::new(data.as_slice());
125        let mut buf = Vec::new();
126
127        let result = read_line_with_limit(&mut reader, &mut buf, 100).await?;
128        match result {
129            ReadLineResult::Truncated(bytes) => {
130                assert_eq!(bytes.len(), 100, "buffer must not exceed the limit");
131            }
132            other => panic!("expected truncation, got {other:?}"),
133        }
134        Ok(())
135    }
136
137    #[tokio::test]
138    async fn read_line_with_limit_reports_partial_line_at_eof() -> std::io::Result<()> {
139        // Data without a trailing newline must be surfaced as a line rather
140        // than silently dropped.
141        let data = "no newline at end";
142        let mut reader = BufReader::new(data.as_bytes());
143        let mut buf = Vec::new();
144
145        let result = read_line_with_limit(&mut reader, &mut buf, 100).await?;
146        match result {
147            ReadLineResult::Line(bytes) => {
148                assert_eq!(bytes, b"no newline at end");
149            }
150            other => panic!("expected line, got {other:?}"),
151        }
152        Ok(())
153    }
154
155    #[tokio::test]
156    async fn read_line_with_limit_treats_exact_fit_as_complete_line() -> std::io::Result<()> {
157        // `would_be_total == max_len` takes the fits branch; one byte less
158        // must truncate instead. Pins both sides of the limit boundary.
159        for (max_len, expect_truncated) in [(6, false), (5, true)] {
160            let mut reader = BufReader::new(b"hello\n".as_slice());
161            let mut buf = Vec::new();
162            match read_line_with_limit(&mut reader, &mut buf, max_len).await? {
163                ReadLineResult::Line(bytes) => {
164                    assert!(!expect_truncated, "max_len={max_len} must fit");
165                    assert_eq!(bytes, b"hello\n");
166                }
167                ReadLineResult::Truncated(bytes) => {
168                    assert!(expect_truncated, "max_len={max_len} must truncate");
169                    assert_eq!(bytes.len(), max_len);
170                }
171                ReadLineResult::Eof => panic!("max_len={max_len} unexpectedly hit EOF"),
172            }
173        }
174        Ok(())
175    }
176}