1#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
2
3mod body;
6mod stream;
7
8use std::time::Duration;
9
10pub use body::*;
11pub use stream::*;
12
13#[derive(Default, Debug, PartialEq, Eq, Hash, Clone)]
14pub struct Sse {
15 pub event: Option<String>,
16 pub data: Option<String>,
17 pub id: Option<String>,
18 pub retry: Option<u64>,
19}
20
21impl Sse {
22 pub fn is_event(&self) -> bool {
23 self.event.is_some()
24 }
25 pub fn is_message(&self) -> bool {
26 self.event.is_none()
27 }
28 pub fn event(mut self, event: impl Into<String>) -> Self {
29 self.event = Some(event.into());
30 self
31 }
32 pub fn data(mut self, data: impl Into<String>) -> Self {
33 self.data = Some(data.into());
34 self
35 }
36 pub fn id(mut self, id: impl Into<String>) -> Self {
37 self.id = Some(id.into());
38 self
39 }
40 pub fn retry(mut self, retry: u64) -> Self {
41 self.retry = Some(retry);
42 self
43 }
44 pub fn retry_duration(mut self, retry: Duration) -> Self {
45 self.retry = Some(retry.as_millis() as u64);
46 self
47 }
48}
49
50impl From<Sse> for bytes::Bytes {
51 fn from(val: Sse) -> Self {
52 let mut bytes = Vec::new();
53 if let Some(event) = val.event {
54 bytes.extend_from_slice(b"event: ");
55 bytes.extend_from_slice(event.as_bytes());
56 bytes.push(b'\n');
57 }
58 if let Some(data) = val.data {
59 bytes.extend_from_slice(b"data: ");
60 bytes.extend_from_slice(data.as_bytes());
61 bytes.push(b'\n');
62 }
63 if let Some(id) = val.id {
64 bytes.extend_from_slice(b"id: ");
65 bytes.extend_from_slice(id.as_bytes());
66 bytes.push(b'\n');
67 }
68 if let Some(retry) = val.retry {
69 bytes.extend_from_slice(b"retry: ");
70 bytes.extend(retry.to_string().as_bytes());
71 bytes.push(b'\n');
72 }
73 bytes.push(b'\n');
74 bytes.into()
75 }
76}