#[cfg(target_os = "linux")]
use std::io;
#[cfg(target_os = "linux")]
pub(crate) fn find_header_end(buf: &[u8]) -> Option<usize> {
if buf.len() < 4 {
return None;
}
buf.windows(4).position(|w| w == b"\r\n\r\n")
}
#[cfg(target_os = "linux")]
pub(crate) fn parse_status_code(header_str: &str) -> io::Result<u16> {
let first_line = header_str
.lines()
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty response"))?;
let mut parts = first_line.split_whitespace();
let _version = parts
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing HTTP version"))?;
let code_str = parts
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing status code"))?;
code_str.parse::<u16>().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid status code: {code_str}"),
)
})
}
#[cfg(target_os = "linux")]
pub(crate) fn is_chunked(header_str: &str) -> bool {
for line in header_str.lines().skip(1) {
if let Some((name, value)) = line.split_once(':')
&& name.trim().eq_ignore_ascii_case("transfer-encoding")
&& value.trim().eq_ignore_ascii_case("chunked")
{
return true;
}
}
false
}
#[cfg(target_os = "linux")]
pub(crate) fn parse_content_length(header_str: &str) -> io::Result<Option<u64>> {
for line in header_str.lines().skip(1) {
if let Some((name, value)) = line.split_once(':')
&& name.trim().eq_ignore_ascii_case("content-length")
{
let value = value.trim();
return value.parse::<u64>().map(Some).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid Content-Length: {value}"),
)
});
}
}
Ok(None)
}
#[cfg(target_os = "linux")]
pub(crate) fn write_all_at_offset(
file: &std::fs::File,
mut buf: &[u8],
mut offset: u64,
) -> io::Result<()> {
use std::os::unix::fs::FileExt;
while !buf.is_empty() {
let n = file.write_at(buf, offset)?;
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"pwrite returned 0 — failed to write all bytes",
));
}
offset += n as u64;
buf = &buf[n..];
}
Ok(())
}
#[cfg(target_os = "linux")]
pub(crate) fn set_blocking(fd: std::os::unix::io::RawFd) {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags >= 0 {
unsafe {
libc::fcntl(fd, libc::F_SETFL, flags & !libc::O_NONBLOCK);
}
}
}