use core::fmt;
pub const LINE_LIMIT: usize = 16384;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Headers {
pub fields: Vec<(String, String)>,
pub ignored: Vec<String>,
}
impl Headers {
pub fn get(&self, name: &str) -> Option<&str> {
self.fields
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
pub fn get_int(&self, name: &str) -> Option<i64> {
self.get(name).and_then(parse_leading_int)
}
pub fn get_f64(&self, name: &str) -> Option<f64> {
self.get(name).and_then(parse_leading_f64)
}
pub fn get_bool(&self, name: &str) -> Option<bool> {
self.get(name)
.map(|v| v.trim() == "1" || v.trim() == "true")
}
}
fn parse_leading_int(s: &str) -> Option<i64> {
let t = s.trim_start();
let mut end = 0;
for (i, c) in t.char_indices() {
if c.is_ascii_digit() || (i == 0 && (c == '-' || c == '+')) {
end = i + c.len_utf8();
} else {
break;
}
}
t[..end].parse().ok()
}
fn parse_leading_f64(s: &str) -> Option<f64> {
let t = s.trim_start();
let mut end = 0;
for (i, c) in t.char_indices() {
if c.is_ascii_digit()
|| c == '.'
|| ((c == '-' || c == '+') && i == 0)
|| c == 'e'
|| c == 'E'
{
end = i + c.len_utf8();
} else {
break;
}
}
t[..end].parse().ok()
}
pub fn split_line(line: &str) -> Option<(String, String)> {
let colon = line.find(':')?;
let cut = match line.find(';') {
Some(semi) => &line[..semi],
None => line,
};
let lower = cut.to_ascii_lowercase();
if colon >= lower.len() {
return None;
}
let name = lower[..colon].trim().to_string();
let value = lower[colon + 1..].trim().to_string();
Some((name, value))
}
pub fn parse_block(buf: &[u8]) -> Option<(Headers, usize)> {
let mut headers = Headers::default();
let mut pos = 0usize;
loop {
let rest = &buf[pos..];
let nl = rest.iter().position(|&b| b == b'\n')?;
let raw = &rest[..nl];
pos += nl + 1;
if raw.first() == Some(&b'\r') || raw.is_empty() {
return Some((headers, pos));
}
let line = String::from_utf8_lossy(raw)
.trim_end_matches('\r')
.to_string();
match split_line(&line) {
Some((k, v)) => headers.fields.push((k, v)),
None => headers.ignored.push(line),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusLine {
pub version: i32,
pub code: i32,
pub message: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusAction {
Proceed,
StreamLost,
Redirect,
Fail,
}
impl StatusLine {
pub fn to_wire(&self) -> String {
format!("LSL/{} {} {}\r\n", self.version, self.code, self.message)
}
pub fn parse(line: &str) -> Result<Self, Error> {
let clean = line.trim_end_matches(['\r', '\n']);
let parts: Vec<&str> = clean.split(' ').filter(|p| !p.is_empty()).collect();
if parts.len() < 3 || !parts[0].starts_with("LSL/") {
return Err(Error::MalformedStatusLine(clean.to_string()));
}
let version = parts[0][4..]
.parse()
.map_err(|_| Error::MalformedStatusLine(clean.to_string()))?;
let code = parts[1]
.parse()
.map_err(|_| Error::MalformedStatusLine(clean.to_string()))?;
Ok(StatusLine {
version,
code,
message: parts[2..].join(" "),
})
}
pub fn action(&self) -> StatusAction {
if self.code == 404 {
StatusAction::StreamLost
} else if self.code >= 400 {
StatusAction::Fail
} else if self.code >= 300 {
StatusAction::Redirect
} else {
StatusAction::Proceed
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
MalformedStatusLine(String),
VersionTooOld {
theirs: i32,
},
VersionTooNew {
theirs: i32,
ours: i32,
},
UidMismatch {
expected: String,
actual: String,
},
ByteOrderNotSupported(i32),
Status(StatusLine),
Incomplete,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::MalformedStatusLine(l) => write!(f, "the status line is malformed: {l}"),
Error::VersionTooOld { theirs } => {
write!(
f,
"the server agreed to protocol {theirs}, and this implementation reads 1.10 and above"
)
}
Error::VersionTooNew { theirs, ours } => {
write!(
f,
"the other side runs version {theirs} and this side runs {ours}"
)
}
Error::UidMismatch { expected, actual } => {
write!(
f,
"the answer named the UID {actual} and this connection holds {expected}"
)
}
Error::ByteOrderNotSupported(v) => write!(f, "the byte order {v} is not supported"),
Error::Status(s) => write!(f, "the other side answered {} {}", s.code, s.message),
Error::Incomplete => write!(f, "the buffer holds no complete block"),
}
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_line_with_no_colon_is_ignored() {
assert_eq!(split_line("this line has no colon"), None);
}
#[test]
fn a_semicolon_starts_a_comment() {
assert_eq!(
split_line("Max-Chunk-Length: 32 ; the rest is a comment"),
Some(("max-chunk-length".into(), "32".into()))
);
}
#[test]
fn a_name_is_case_insensitive() {
assert_eq!(
split_line("NaTiVe-ByTe-OrDeR: 1234"),
Some(("native-byte-order".into(), "1234".into()))
);
}
#[test]
fn a_comment_before_the_colon_yields_nothing() {
assert_eq!(split_line("; a comment: with a colon"), None);
}
#[test]
fn a_block_ends_at_a_blank_line() {
let buf = b"A: 1\r\nB: 2\r\n\r\ntrailing";
let (h, used) = parse_block(buf).expect("a complete block");
assert_eq!(
h.fields,
vec![("a".into(), "1".into()), ("b".into(), "2".into())]
);
assert_eq!(&buf[used..], b"trailing");
}
#[test]
fn an_incomplete_block_returns_nothing() {
assert_eq!(parse_block(b"A: 1\r\nB: 2\r\n"), None);
}
#[test]
fn a_status_line_round_trips() {
let s = StatusLine {
version: 110,
code: 200,
message: "OK".into(),
};
assert_eq!(s.to_wire(), "LSL/110 200 OK\r\n");
assert_eq!(StatusLine::parse(&s.to_wire()).unwrap(), s);
}
#[test]
fn a_status_message_can_hold_spaces() {
let s = StatusLine::parse("LSL/110 505 Version not supported").unwrap();
assert_eq!(s.code, 505);
assert_eq!(s.message, "Version not supported");
assert_eq!(s.action(), StatusAction::Fail);
}
#[test]
fn status_codes_map_to_the_documented_action() {
let mk = |c| StatusLine {
version: 110,
code: c,
message: "x".into(),
};
assert_eq!(mk(200).action(), StatusAction::Proceed);
assert_eq!(mk(301).action(), StatusAction::Redirect);
assert_eq!(mk(404).action(), StatusAction::StreamLost);
assert_eq!(mk(500).action(), StatusAction::Fail);
assert_eq!(mk(505).action(), StatusAction::Fail);
}
#[test]
fn a_malformed_status_line_is_rejected() {
assert!(StatusLine::parse("HTTP/1.1 200 OK").is_err());
assert!(StatusLine::parse("LSL/110 200").is_err());
}
#[test]
fn a_number_stops_at_trailing_text() {
let mut h = Headers::default();
h.fields.push(("value-size".into(), "4 bytes".into()));
assert_eq!(h.get_int("value-size"), Some(4));
}
}