1use core::fmt;
8
9pub const LINE_LIMIT: usize = 16384;
11
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
14pub struct Headers {
15 pub fields: Vec<(String, String)>,
18 pub ignored: Vec<String>,
20}
21
22impl Headers {
23 pub fn get(&self, name: &str) -> Option<&str> {
28 self.fields
29 .iter()
30 .find(|(k, _)| k == name)
31 .map(|(_, v)| v.as_str())
32 }
33
34 pub fn get_int(&self, name: &str) -> Option<i64> {
36 self.get(name).and_then(parse_leading_int)
37 }
38
39 pub fn get_f64(&self, name: &str) -> Option<f64> {
41 self.get(name).and_then(parse_leading_f64)
42 }
43
44 pub fn get_bool(&self, name: &str) -> Option<bool> {
48 self.get(name)
49 .map(|v| v.trim() == "1" || v.trim() == "true")
50 }
51}
52
53fn parse_leading_int(s: &str) -> Option<i64> {
56 let t = s.trim_start();
57 let mut end = 0;
58 for (i, c) in t.char_indices() {
59 if c.is_ascii_digit() || (i == 0 && (c == '-' || c == '+')) {
60 end = i + c.len_utf8();
61 } else {
62 break;
63 }
64 }
65 t[..end].parse().ok()
66}
67
68fn parse_leading_f64(s: &str) -> Option<f64> {
70 let t = s.trim_start();
71 let mut end = 0;
72 for (i, c) in t.char_indices() {
73 if c.is_ascii_digit()
74 || c == '.'
75 || ((c == '-' || c == '+') && i == 0)
76 || c == 'e'
77 || c == 'E'
78 {
79 end = i + c.len_utf8();
80 } else {
81 break;
82 }
83 }
84 t[..end].parse().ok()
85}
86
87pub fn split_line(line: &str) -> Option<(String, String)> {
102 let colon = line.find(':')?;
103 let cut = match line.find(';') {
104 Some(semi) => &line[..semi],
105 None => line,
106 };
107 let lower = cut.to_ascii_lowercase();
108 if colon >= lower.len() {
109 return None;
111 }
112 let name = lower[..colon].trim().to_string();
113 let value = lower[colon + 1..].trim().to_string();
114 Some((name, value))
115}
116
117pub fn parse_block(buf: &[u8]) -> Option<(Headers, usize)> {
123 let mut headers = Headers::default();
124 let mut pos = 0usize;
125
126 loop {
127 let rest = &buf[pos..];
128 let nl = rest.iter().position(|&b| b == b'\n')?;
129 let raw = &rest[..nl];
130 pos += nl + 1;
131
132 if raw.first() == Some(&b'\r') || raw.is_empty() {
135 return Some((headers, pos));
136 }
137
138 let line = String::from_utf8_lossy(raw)
139 .trim_end_matches('\r')
140 .to_string();
141 match split_line(&line) {
142 Some((k, v)) => headers.fields.push((k, v)),
143 None => headers.ignored.push(line),
144 }
145 }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct StatusLine {
151 pub version: i32,
153 pub code: i32,
155 pub message: String,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum StatusAction {
162 Proceed,
164 StreamLost,
166 Redirect,
168 Fail,
170}
171
172impl StatusLine {
173 pub fn to_wire(&self) -> String {
175 format!("LSL/{} {} {}\r\n", self.version, self.code, self.message)
176 }
177
178 pub fn parse(line: &str) -> Result<Self, Error> {
183 let clean = line.trim_end_matches(['\r', '\n']);
184 let parts: Vec<&str> = clean.split(' ').filter(|p| !p.is_empty()).collect();
185 if parts.len() < 3 || !parts[0].starts_with("LSL/") {
186 return Err(Error::MalformedStatusLine(clean.to_string()));
187 }
188 let version = parts[0][4..]
189 .parse()
190 .map_err(|_| Error::MalformedStatusLine(clean.to_string()))?;
191 let code = parts[1]
192 .parse()
193 .map_err(|_| Error::MalformedStatusLine(clean.to_string()))?;
194 Ok(StatusLine {
195 version,
196 code,
197 message: parts[2..].join(" "),
198 })
199 }
200
201 pub fn action(&self) -> StatusAction {
207 if self.code == 404 {
208 StatusAction::StreamLost
209 } else if self.code >= 400 {
210 StatusAction::Fail
211 } else if self.code >= 300 {
212 StatusAction::Redirect
213 } else {
214 StatusAction::Proceed
215 }
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221pub enum Error {
222 MalformedStatusLine(String),
224 VersionTooOld {
230 theirs: i32,
232 },
233 VersionTooNew {
235 theirs: i32,
237 ours: i32,
239 },
240 UidMismatch {
242 expected: String,
244 actual: String,
246 },
247 ByteOrderNotSupported(i32),
249 Status(StatusLine),
251 Incomplete,
253}
254
255impl fmt::Display for Error {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 match self {
258 Error::MalformedStatusLine(l) => write!(f, "the status line is malformed: {l}"),
259 Error::VersionTooOld { theirs } => {
260 write!(
261 f,
262 "the server agreed to protocol {theirs}, and this implementation reads 1.10 and above"
263 )
264 }
265 Error::VersionTooNew { theirs, ours } => {
266 write!(
267 f,
268 "the other side runs version {theirs} and this side runs {ours}"
269 )
270 }
271 Error::UidMismatch { expected, actual } => {
272 write!(
273 f,
274 "the answer named the UID {actual} and this connection holds {expected}"
275 )
276 }
277 Error::ByteOrderNotSupported(v) => write!(f, "the byte order {v} is not supported"),
278 Error::Status(s) => write!(f, "the other side answered {} {}", s.code, s.message),
279 Error::Incomplete => write!(f, "the buffer holds no complete block"),
280 }
281 }
282}
283
284impl std::error::Error for Error {}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn a_line_with_no_colon_is_ignored() {
292 assert_eq!(split_line("this line has no colon"), None);
293 }
294
295 #[test]
296 fn a_semicolon_starts_a_comment() {
297 assert_eq!(
298 split_line("Max-Chunk-Length: 32 ; the rest is a comment"),
299 Some(("max-chunk-length".into(), "32".into()))
300 );
301 }
302
303 #[test]
304 fn a_name_is_case_insensitive() {
305 assert_eq!(
306 split_line("NaTiVe-ByTe-OrDeR: 1234"),
307 Some(("native-byte-order".into(), "1234".into()))
308 );
309 }
310
311 #[test]
312 fn a_comment_before_the_colon_yields_nothing() {
313 assert_eq!(split_line("; a comment: with a colon"), None);
316 }
317
318 #[test]
319 fn a_block_ends_at_a_blank_line() {
320 let buf = b"A: 1\r\nB: 2\r\n\r\ntrailing";
321 let (h, used) = parse_block(buf).expect("a complete block");
322 assert_eq!(
323 h.fields,
324 vec![("a".into(), "1".into()), ("b".into(), "2".into())]
325 );
326 assert_eq!(&buf[used..], b"trailing");
327 }
328
329 #[test]
330 fn an_incomplete_block_returns_nothing() {
331 assert_eq!(parse_block(b"A: 1\r\nB: 2\r\n"), None);
332 }
333
334 #[test]
335 fn a_status_line_round_trips() {
336 let s = StatusLine {
337 version: 110,
338 code: 200,
339 message: "OK".into(),
340 };
341 assert_eq!(s.to_wire(), "LSL/110 200 OK\r\n");
342 assert_eq!(StatusLine::parse(&s.to_wire()).unwrap(), s);
343 }
344
345 #[test]
346 fn a_status_message_can_hold_spaces() {
347 let s = StatusLine::parse("LSL/110 505 Version not supported").unwrap();
348 assert_eq!(s.code, 505);
349 assert_eq!(s.message, "Version not supported");
350 assert_eq!(s.action(), StatusAction::Fail);
351 }
352
353 #[test]
354 fn status_codes_map_to_the_documented_action() {
355 let mk = |c| StatusLine {
356 version: 110,
357 code: c,
358 message: "x".into(),
359 };
360 assert_eq!(mk(200).action(), StatusAction::Proceed);
361 assert_eq!(mk(301).action(), StatusAction::Redirect);
362 assert_eq!(mk(404).action(), StatusAction::StreamLost);
363 assert_eq!(mk(500).action(), StatusAction::Fail);
364 assert_eq!(mk(505).action(), StatusAction::Fail);
365 }
366
367 #[test]
368 fn a_malformed_status_line_is_rejected() {
369 assert!(StatusLine::parse("HTTP/1.1 200 OK").is_err());
370 assert!(StatusLine::parse("LSL/110 200").is_err());
371 }
372
373 #[test]
374 fn a_number_stops_at_trailing_text() {
375 let mut h = Headers::default();
377 h.fields.push(("value-size".into(), "4 bytes".into()));
378 assert_eq!(h.get_int("value-size"), Some(4));
379 }
380}