use std::fmt;
use std::time::Duration;
#[derive(Debug)]
pub struct Event {
pub id: Option<String>,
pub event_type: Option<String>,
pub data: String,
}
#[derive(Debug, PartialEq)]
pub enum ParseResult {
Next,
Dispatch,
SetRetry(Duration),
}
pub fn parse_event_line(line: &str, event: &mut Event) -> ParseResult {
let line = line.trim_end_matches(|c| c == '\r' || c == '\n');
if line == "" {
ParseResult::Dispatch
} else {
let (field, value) = if let Some(pos) = line.find(':') {
let (f, v) = line.split_at(pos);
let v = &v[1..];
let v = if v.starts_with(' ') { &v[1..] } else { v };
(f, v)
} else {
(line, "")
};
match field {
"event" => {
event.event_type = Some(value.to_string());
}
"data" => {
event.data.push_str(value);
event.data.push('\n');
}
"id" => {
event.id = Some(value.to_string());
}
"retry" => {
if let Ok(retry) = value.parse::<u64>() {
return ParseResult::SetRetry(Duration::from_millis(retry));
}
}
_ => (), }
ParseResult::Next
}
}
impl Event {
pub fn new() -> Event {
Event {
id: None,
event_type: None,
data: "".to_string(),
}
}
pub fn is_empty(&self) -> bool {
self.id.is_none() && self.event_type.is_none() && self.data.is_empty()
}
pub fn clear(&mut self) {
self.id = None;
self.event_type = None;
self.data.clear();
}
}
impl fmt::Display for Event {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref id) = self.id {
write!(f, "id: {}\n", id)?;
}
if let Some(ref event_type) = self.event_type {
write!(f, "event: {}\n", event_type)?;
}
for line in self.data.lines() {
write!(f, "data: {}\n", line)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_event_display() {
assert_eq!(
"data: hello world\n",
Event {
id: None,
event_type: None,
data: "hello world".to_string()
}
.to_string()
);
assert_eq!(
"id: foo\ndata: hello world\n",
Event {
id: Some("foo".to_string()),
event_type: None,
data: "hello world".to_string()
}
.to_string()
);
assert_eq!(
"event: bar\ndata: hello world\n",
Event {
id: None,
event_type: Some("bar".to_string()),
data: "hello world".to_string()
}
.to_string()
);
}
#[test]
fn multiline_event_display() {
assert_eq!(
"data: hello\ndata: world\n",
Event {
id: None,
event_type: None,
data: "hello\nworld".to_string()
}
.to_string()
);
assert_eq!(
"data: hello\ndata: \ndata: world\n",
Event {
id: None,
event_type: None,
data: "hello\n\nworld".to_string()
}
.to_string()
);
}
}