use crate::encode::{EventStreamFormatter, SSE_MEDIA_TYPE};
use crate::error::Result;
use crate::event::Event;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SseFormatter;
impl SseFormatter {
pub const fn new() -> Self {
Self
}
pub fn encode_to_string(&self, event: &Event) -> Result<String> {
Ok(frame(&serde_json::to_string(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
}