1 //! SSE framing. Exact, because requirement R18 compares bytes.2 //!3 //! `data: <json>\n\n` for each event and `data: [DONE]\n\n` once at the end. A4 //! comment line keeps the connection alive before the first event; a comment is5 //! what SSE reserves for bytes that no client must parse.6 7 use std::io::{self, Write};8 9 use inf3r_json::Value;10 11 /// The last frame of a stream.12 pub const DONE: &str = "data: [DONE]\n\n";13 14 /// Writes one event frame.15 pub fn write_event(out: &mut impl Write, event: &Value) -> io::Result<()> {16 let json = inf3r_json::to_string(event);17 write!(out, "data: {json}\n\n")18 }19 20 /// Writes the terminal frame and returns the bytes that were written.21 pub fn write_done(out: &mut impl Write) -> io::Result<()> {22 out.write_all(DONE.as_bytes())23 }24 25 /// Writes a comment line, which a client ignores and a proxy does not.26 pub fn write_comment(out: &mut impl Write, text: &str) -> io::Result<()> {27 // A newline in the text would end the comment and start a field, so the28 // text cannot carry one.29 let text = text.replace(['\r', '\n'], " ");30 write!(out, ": {text}\n\n")31 }