aria2-protocol 0.3.10

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
Documentation
//! Primitive SFTP wire field encoders and decoders.

use std::io::{self, Read, Write};
pub(super) fn write_u32(w: &mut impl Write, v: u32) -> io::Result<()> {
    w.write_all(&v.to_be_bytes())
}

pub(super) fn checked_u32_length(length: usize, field: &str) -> io::Result<u32> {
    u32::try_from(length).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("SFTP {field} exceeds the u32 wire limit"),
        )
    })
}

pub(super) fn write_u64(w: &mut impl Write, v: u64) -> io::Result<()> {
    w.write_all(&v.to_be_bytes())
}

/// Write a UTF-8 string as `[length:u32][bytes]` (SFTP string format).
pub(super) fn write_string(w: &mut impl Write, s: &str) -> io::Result<()> {
    write_u32(w, checked_u32_length(s.len(), "string length")?)?;
    w.write_all(s.as_bytes())
}

/// Write raw bytes as `[length:u32][data]` (SFTP string/buffer format).
pub(super) fn write_string_raw(w: &mut impl Write, data: &[u8]) -> io::Result<()> {
    write_u32(w, checked_u32_length(data.len(), "string length")?)?;
    w.write_all(data)
}

pub(super) fn read_u8(r: &mut impl Read) -> io::Result<u8> {
    let mut buf = [0u8; 1];
    r.read_exact(&mut buf)?;
    Ok(buf[0])
}

pub(super) fn read_u32(r: &mut impl Read) -> io::Result<u32> {
    let mut buf = [0u8; 4];
    r.read_exact(&mut buf)?;
    Ok(u32::from_be_bytes(buf))
}

pub(super) fn read_u64(r: &mut impl Read) -> io::Result<u64> {
    let mut buf = [0u8; 8];
    r.read_exact(&mut buf)?;
    Ok(u64::from_be_bytes(buf))
}

/// Read a UTF-8 string in `[length:u32][bytes]` format.
pub(super) fn read_string(r: &mut impl Read) -> io::Result<String> {
    let buf = read_raw(r)?;
    String::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}

/// Read raw bytes in `[length:u32][data]` format.
pub(super) fn read_raw(r: &mut impl Read) -> io::Result<Vec<u8>> {
    let len = read_u32(r)? as usize;
    let mut buf = Vec::new();
    let mut field = r.take(len as u64);
    let read = field.read_to_end(&mut buf)?;
    if read != len {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "incomplete SFTP string",
        ));
    }
    Ok(buf)
}

// =============================================================================