#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Json,
Events,
}
impl Kind {
pub fn of(content_type: &str) -> Option<Self> {
let media = content_type
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
match media.as_str() {
"application/json" => Some(Self::Json),
"text/event-stream" => Some(Self::Events),
_ => None,
}
}
}
pub fn events(stream: &[u8]) -> Vec<String> {
let text = String::from_utf8_lossy(stream);
let mut out = Vec::new();
let mut data: Option<String> = None;
let normalised = text.replace("\r\n", "\n").replace('\r', "\n");
let Some(whole) = normalised.rfind('\n').map(|end| &normalised[..=end]) else {
return out;
};
for line in whole.split_inclusive('\n') {
let line = line.trim_end_matches('\n');
if line.is_empty() {
if let Some(event) = data.take()
&& !event.is_empty()
{
out.push(event);
}
continue;
}
if line.starts_with(':') {
continue;
}
let (field, value) = line.split_once(':').unwrap_or((line, ""));
let value = value.strip_prefix(' ').unwrap_or(value);
if field == "data" {
let event = data.get_or_insert_with(String::new);
if !event.is_empty() {
event.push('\n');
}
event.push_str(value);
}
}
out
}