use crate::encode::{EventStreamFormatter, SSE_MEDIA_TYPE};
use crate::error::Result;
use crate::event::Event;
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SseFrame<E = Event> {
Event(E),
Comment(String),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SseFormatter;
impl SseFormatter {
pub const fn new() -> Self {
Self
}
pub fn encode_serializable(&self, event: &impl serde::Serialize) -> Result<String> {
Ok(frame(&self.event_json(event)?))
}
pub fn encode_frame<E: serde::Serialize>(&self, value: &SseFrame<E>) -> Result<String> {
match value {
SseFrame::Event(event) => self.encode_serializable(event),
SseFrame::Comment(text) => Ok(comment(text)),
}
}
pub(crate) fn event_json(&self, event: &impl serde::Serialize) -> Result<String> {
Ok(serde_json::to_string(event)?)
}
pub fn encode_to_string(&self, event: &Event) -> Result<String> {
self.encode_serializable(event)
}
}
impl EventStreamFormatter for SseFormatter {
fn content_type(&self) -> &'static str {
SSE_MEDIA_TYPE
}
fn encode(&self, event: &Event) -> Result<Vec<u8>> {
Ok(self.encode_to_string(event)?.into_bytes())
}
}
pub fn frame(payload: &str) -> String {
let mut out = String::with_capacity(payload.len() + 8);
let mut rest = payload;
loop {
match rest.find(['\r', '\n']) {
Some(index) => {
out.push_str("data: ");
out.push_str(&rest[..index]);
out.push('\n');
let width = if rest[index..].starts_with("\r\n") {
2
} else {
1
};
rest = &rest[index + width..];
}
None => {
out.push_str("data: ");
out.push_str(rest);
out.push('\n');
break;
}
}
}
out.push('\n');
out
}
pub fn comment(payload: &str) -> String {
let mut output = String::with_capacity(payload.len() + 4);
for line in comment_lines(payload) {
output.push_str(": ");
output.push_str(line);
output.push('\n');
}
output.push('\n');
output
}
pub(crate) fn comment_lines(payload: &str) -> impl Iterator<Item = &str> {
let mut rest = Some(payload);
std::iter::from_fn(move || {
let value = rest.take()?;
match value.find(['\r', '\n']) {
Some(index) => {
let width = if value[index..].starts_with("\r\n") {
2
} else {
1
};
rest = Some(&value[index + width..]);
Some(&value[..index])
}
None => Some(value),
}
})
}