pub(crate) fn message_end(reply: &[u8]) -> Option<usize> {
if !reply.starts_with(b"HTTP/1.") {
return None;
}
let body = find(reply, b"\r\n\r\n")? + 4;
let head = &reply[..body - 4];
let status: u16 = std::str::from_utf8(head.get(9..12)?).ok()?.parse().ok()?;
if status < 200 {
return None;
}
if status == 204 || status == 304 {
return Some(body);
}
let mut length: Option<usize> = None;
let mut chunked = false;
for line in head.split(|&byte| byte == b'\n').skip(1) {
let line = line.strip_suffix(b"\r").unwrap_or(line);
let Some(colon) = line.iter().position(|&byte| byte == b':') else {
continue;
};
let (name, value) = (&line[..colon], line[colon + 1..].trim_ascii());
if name.eq_ignore_ascii_case(b"transfer-encoding") {
chunked = value
.rsplit(|&byte| byte == b',')
.next()
.is_some_and(|last| last.trim_ascii().eq_ignore_ascii_case(b"chunked"));
} else if name.eq_ignore_ascii_case(b"content-length") {
let declared: usize = std::str::from_utf8(value).ok()?.parse().ok()?;
if length.is_some_and(|earlier| earlier != declared) {
return None;
}
length = Some(declared);
}
}
if chunked {
return chunked_end(&reply[body..]).map(|end| body + end);
}
let end = body.checked_add(length?)?;
(reply.len() >= end).then_some(end)
}
fn chunked_end(body: &[u8]) -> Option<usize> {
let mut at = 0;
loop {
let line_end = at + find(&body[at..], b"\r\n")?;
let size_field = &body[at..line_end];
let digits = size_field.split(|&byte| byte == b';').next()?.trim_ascii();
let size = usize::from_str_radix(std::str::from_utf8(digits).ok()?, 16).ok()?;
at = line_end + 2;
if size == 0 {
if body[at..].starts_with(b"\r\n") {
return Some(at + 2);
}
return find(&body[at..], b"\r\n\r\n").map(|end| at + end + 4);
}
at = at.checked_add(size)?.checked_add(2)?;
if at > body.len() {
return None;
}
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}