a2s-protocol 0.1.0

A protocol core for building A2S server query clients
Documentation
//! A simple cursor for reading primitives and `&str` from `&[u8]` without allocations.

/// A cursor for sequentially reading from a byte slice.
///
/// It does not own the data; it only stores `&[u8]` and the current position.
    /// All `read_*` methods advance the position by the size of the data read.

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("unexpected end of stream")]
    UnexpectedEof,
    #[error("invalid UTF-8")]
    InvalidUtf8,
}

#[derive(Debug)]
pub struct Cursor<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    /// Creates a cursor at the beginning of the slice.
    #[inline]
    pub fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// Returns whether the end of the buffer has been reached.
    #[inline]
    pub fn is_end(&self) -> bool { self.pos >= self.buf.len() }

    /// Returns the unread remainder of the buffer.
    #[inline]
    pub fn as_slice(&self) -> &'a [u8] {
        &self.buf[self.pos..]
    }

    /// Reads one `u8`, advancing the cursor by 1 byte.
    #[inline]
    pub fn read_byte(&mut self) -> Result<u8, Error> {
        let byte = *self.buf.get(self.pos).ok_or(Error::UnexpectedEof)?;
        self.pos += 1;
        Ok(byte)
    }

    /// Reads an `i16` in little-endian order, advancing the cursor by 2 bytes.
    #[inline]
    pub fn read_short(&mut self) -> Result<u16, Error> {
        self.read_array::<2>().map(u16::from_le_bytes)
    }

    pub fn read_long(&mut self) -> Result<i32, Error> {
        self.read_array::<4>().map(i32::from_le_bytes)
    }

    pub fn read_float(&mut self) -> Result<f32, Error> {
        self.read_array::<4>().map(f32::from_le_bytes)
    }

    /// Reads a `u64` in little-endian order, advancing the cursor by 8 bytes.
    #[inline]
    pub fn read_longlong(&mut self) -> Result<u64, Error> {
        self.read_array::<8>().map(u64::from_le_bytes)
    }

    /// Reads a `&str` from the current position up to the first `sentinel` byte
    /// (excluding it), advancing the cursor just past the sentinel.
    ///
    /// No allocations are performed; the returned string is a subslice of the original buffer.
    ///
    #[inline]
    fn read_sentinel_str(&mut self, sentinel: u8) -> Result<&'a str, Error> {
        let start = self.pos;
        let rel = self
            .buf
            .get(start..)
            .ok_or(Error::UnexpectedEof)?
            .iter()
            .position(|&b| b == sentinel)
            .ok_or(Error::UnexpectedEof)?;
        let end = start + rel;
        self.pos = end + 1; // skip the sentinel

        let bytes = &self.buf[start..end];
        std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8)
    }

    /// The same as [`read_str`](Self::read_str), but with `sentinel = b'\0'`,
    /// reading a C-style string without having to pass `0` each time.
    #[inline]
    pub fn read_str(&mut self) -> Result<&'a str, Error> {
        self.read_sentinel_str(b'\0')
    }

    /// Helper method: reads N bytes as an array, advancing the cursor.
    #[inline]
    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
        let end = self.pos.checked_add(N).ok_or(Error::UnexpectedEof)?;
        let slice = self.buf.get(self.pos..end).ok_or(Error::UnexpectedEof)?;
        self.pos = end;
        // The slice is guaranteed to have length N by get(pos..end).
        Ok(slice.try_into().expect("slice length is N"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_primitives_and_str() {
        let mut data = Vec::new();
        data.push(0xAB); // u8
        data.extend_from_slice(&(1234u16).to_le_bytes()); // i16
        data.extend_from_slice(&123456789u64.to_le_bytes()); // u64
        data.extend_from_slice(b"hello\0world\0");

        let mut c = Cursor::new(&data);
        assert!(matches!(c.read_byte(), Ok(0xAB)));
        assert!(matches!(c.read_short(), Ok(1234)));
        assert!(matches!(c.read_longlong(), Ok(123456789)));
        assert!(matches!(c.read_str(), Ok("hello")));
        assert!(matches!(c.read_str(), Ok("world")));
        assert!(matches!(c.as_slice(), []));
    }

    #[test]
    fn out_of_bounds_returns_none() {
        let data = [1u8, 2, 3];
        let mut c = Cursor::new(&data);
        assert!(matches!(c.read_str(), Err(Error::UnexpectedEof)));
    }
}