1use tokio::sync::mpsc;
5
6use crate::ClientError;
7
8#[cfg(test)]
9mod tests;
10
11#[derive(Debug)]
13pub struct Chunks {
14 receiver: mpsc::Receiver<Result<Vec<u8>, ClientError>>,
15}
16
17impl Chunks {
18 #[must_use]
20 pub fn channel() -> (mpsc::Sender<Result<Vec<u8>, ClientError>>, Self) {
21 let (sender, receiver) = mpsc::channel(16);
22 (sender, Self { receiver })
23 }
24
25 pub async fn next(&mut self) -> Option<Result<Vec<u8>, ClientError>> {
27 self.receiver.recv().await
28 }
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ServerEvent {
34 pub name: String,
36 pub data: String,
38}
39
40#[derive(Debug)]
43pub struct EventReader {
44 chunks: Chunks,
45 pending: Vec<u8>,
47}
48
49impl EventReader {
50 #[must_use]
52 pub const fn new(chunks: Chunks) -> Self {
53 Self {
54 chunks,
55 pending: Vec::new(),
56 }
57 }
58
59 pub async fn next(&mut self) -> Option<Result<ServerEvent, ClientError>> {
61 loop {
62 if let Some(event) = self.parse_one() {
63 return Some(Ok(event));
64 }
65 match self.chunks.next().await? {
66 Ok(chunk) => self.pending.extend_from_slice(&chunk),
67 Err(error) => return Some(Err(error)),
68 }
69 }
70 }
71
72 fn parse_one(&mut self) -> Option<ServerEvent> {
75 loop {
76 let end = blank_line(&self.pending)?;
77 let block: Vec<u8> = self.pending.drain(..end.1).take(end.0).collect();
78 let text = String::from_utf8_lossy(&block);
79 let mut name = None;
80 let mut data: Option<String> = None;
81 for line in text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) {
82 let (field, value) = line.split_once(':').unwrap_or((line, ""));
83 let value = value.strip_prefix(' ').unwrap_or(value);
84 match field {
85 "event" => name = Some(value.to_owned()),
86 "data" => match &mut data {
87 Some(data) => {
88 data.push('\n');
89 data.push_str(value);
90 }
91 None => data = Some(value.to_owned()),
92 },
93 _ => {}
94 }
95 }
96 if name.is_some() || data.is_some() {
97 return Some(ServerEvent {
98 name: name.unwrap_or_else(|| "message".to_owned()),
99 data: data.unwrap_or_default(),
100 });
101 }
102 }
103 }
104}
105
106fn blank_line(bytes: &[u8]) -> Option<(usize, usize)> {
109 (0..bytes.len()).find_map(|i| {
110 if bytes[i..].starts_with(b"\n\n") {
111 Some((i, i + 2))
112 } else if bytes[i..].starts_with(b"\r\n\r\n") {
113 Some((i, i + 4))
114 } else {
115 None
116 }
117 })
118}