deepseek_rust_cli/api/
streaming.rs1use crate::api::types::ChatResponseChunk;
2
3pub struct StreamParser {
4 buffer: Vec<u8>,
5}
6
7impl Default for StreamParser {
8 fn default() -> Self {
9 Self::new()
10 }
11}
12
13impl StreamParser {
14 pub fn new() -> Self {
15 Self { buffer: Vec::new() }
16 }
17
18 pub fn parse_chunk(&mut self, chunk: &[u8]) -> Vec<ChatResponseChunk> {
19 self.buffer.extend_from_slice(chunk);
20 let mut results = Vec::new();
21
22 while let Some(newline_pos) = self.buffer.iter().position(|&b| b == b'\n') {
23 let line_bytes = self.buffer[..newline_pos].to_vec();
24 self.buffer.drain(..=newline_pos);
25
26 if let Ok(line_str) = String::from_utf8(line_bytes) {
27 let line = line_str.trim();
28 if line.is_empty() {
29 continue;
30 }
31
32 if let Some(stripped) = line.strip_prefix("data: ") {
33 let data = stripped.trim();
34 if data == "[DONE]" {
35 continue;
36 }
37 if let Ok(parsed) = serde_json::from_str::<ChatResponseChunk>(data) {
38 results.push(parsed);
39 }
40 }
41 }
42 }
43 results
44 }
45}