1#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct SseEvent {
12 pub event: Option<String>,
14 pub data: String,
16 pub id: Option<String>,
18 pub retry: Option<u64>,
20}
21
22pub fn parse_sse(body: &[u8]) -> Vec<SseEvent> {
37 let text = String::from_utf8_lossy(body);
38 let mut events = Vec::new();
39 let mut current = SseEvent::default();
40 let mut has_data = false;
41 let mut rest: &str = &text;
42 rest = rest.strip_prefix('\u{feff}').unwrap_or(rest);
44 while !rest.is_empty() {
45 let end = rest.find(['\r', '\n']).unwrap_or(rest.len());
46 let line = &rest[..end];
47 let mut next = &rest[end..];
48 if next.starts_with("\r\n") {
49 next = &next[2..];
50 } else if !next.is_empty() {
51 next = &next[1..];
52 } else {
53 }
56 rest = next;
57
58 if line.is_empty() {
59 if has_data {
60 events.push(std::mem::take(&mut current));
61 } else {
62 current = SseEvent::default();
63 }
64 has_data = false;
65 continue;
66 }
67 if line.starts_with(':') {
68 continue;
69 }
70 let (field, value) = match line.split_once(':') {
71 Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
72 None => (line, ""),
73 };
74 match field {
75 "event" => current.event = Some(value.to_string()),
76 "data" => {
77 if has_data {
78 current.data.push('\n');
79 }
80 current.data.push_str(value);
81 has_data = true;
82 }
83 "id" if !value.contains('\0') => current.id = Some(value.to_string()),
84 "retry" if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) => {
85 current.retry = value.parse().ok();
86 }
87 _ => {}
88 }
89 }
90 events
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96
97 #[test]
98 fn events_parse_with_every_line_ending_and_field() {
99 let body = b"retry: 1500\r\n: a comment\r\nevent: tick\nid: 7\ndata: one\rdata:two\n\ndata: {\"n\":1}\n\n";
100 let events = parse_sse(body);
101 assert_eq!(
102 events,
103 vec![
104 SseEvent {
105 event: Some("tick".into()),
106 data: "one\ntwo".into(),
107 id: Some("7".into()),
108 retry: Some(1500),
109 },
110 SseEvent {
111 event: None,
112 data: "{\"n\":1}".into(),
113 id: None,
114 retry: None,
115 },
116 ]
117 );
118 }
119
120 #[test]
121 fn events_without_data_or_a_terminating_blank_line_are_not_dispatched() {
122 assert!(
123 parse_sse(b"event: ping\n\n").is_empty(),
124 "no data, no event"
125 );
126 assert!(parse_sse(b"data: cut off").is_empty());
127 assert!(parse_sse(b"").is_empty());
128 let events = parse_sse(b"data\n\n");
129 assert_eq!(events[0].data, "", "a bare field name has an empty value");
130 let events = parse_sse(b"retry: soon\nid: a\0b\ndata: x\n\n");
131 assert_eq!((events[0].retry, events[0].id.as_deref()), (None, None));
132 }
133
134 proptest::proptest! {
135 #[test]
138 fn prop_sse_parser_events(
139 events in proptest::collection::vec(
140 (
141 proptest::option::of("[a-z]{1,8}"),
142 proptest::collection::vec("[ -~]{0,16}", 1..4),
143 proptest::option::of("[a-z0-9]{1,8}"),
144 ),
145 0..8,
146 ),
147 crlf in proptest::bool::ANY,
148 ) {
149 let nl = if crlf { "\r\n" } else { "\n" };
150 let mut body = String::new();
151 let mut expected = Vec::new();
152 for (event, lines, id) in &events {
153 if let Some(event) = event {
154 body.push_str(&format!("event: {event}{nl}"));
155 }
156 if let Some(id) = id {
157 body.push_str(&format!("id: {id}{nl}"));
158 }
159 for line in lines {
160 body.push_str(&format!("data: {line}{nl}"));
161 }
162 body.push_str(nl);
163 expected.push(SseEvent {
164 event: event.clone(),
165 data: lines.join("\n"),
166 id: id.clone(),
167 retry: None,
168 });
169 }
170 proptest::prop_assert_eq!(parse_sse(body.as_bytes()), expected);
171 }
172 }
173}