a2s-protocol 0.1.1

A protocol core for building A2S server query clients
Documentation
//! Types returned when parsing A2S_PLAYER responses.

use borrowme::borrowme;

use crate::cursor::{self, Cursor};

#[derive(thiserror::Error, Debug)]
#[error(transparent)]
/// An A2S_PLAYER payload ended before all required fields were read or contained invalid UTF-8.
pub struct Error(#[from] cursor::Error);

pub(crate) const REQUEST_HEADER: &[u8] = b"U";
pub(crate) const RESPONSE_HEADER: u8 = b'D';

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// One player record from an A2S_PLAYER response.
///
/// The player name borrows from the response packet. Use [`Player::to_owned`]
/// to keep an owned copy after the packet is released.
pub struct Player<'a> {
    /// Player index reported by the server.
    pub index: u8,
    /// Player name.
    pub name: &'a str,
    /// Player score.
    pub score: i32,
    /// Connection duration in seconds.
    pub duration: f32
}

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// Player records parsed from an A2S_PLAYER response.
///
/// Some older engines count players who are still connecting in
/// [`reported_num`](Self::reported_num) without including a record for them.
/// Therefore `reported_num` may be greater than `players.len()`.
pub struct Players<'a> {
    /// Number of players reported by the server, including any connecting players.
    pub reported_num: u8,
    /// Parsed player records returned by the server.
    pub players: Vec<Player<'a>>
}

impl<'a> Player<'a> {
    /// Copies this player record into an owned value.
    pub fn to_owned(self) -> OwnedPlayer {
        borrowme::to_owned(self)
    }

    fn parse(cur: &mut Cursor<'a>) -> Result<Self, Error> {
        Ok(Self {
            index: cur.read_byte()?,
            name: cur.read_str()?,
            score: cur.read_long()?,
            duration: cur.read_float()?,
        })
    }
}

impl<'a> Players<'a> {
    pub(crate) fn parse(raw: &'a [u8]) -> Result<Self, Error> {
        let mut cur = Cursor::new(raw);
        let reported_num = cur.read_byte()?;
        let mut players = Vec::with_capacity(reported_num as usize);

        while !cur.is_end() {
            players.push(Player::parse(&mut cur)?);
        }

        Ok(Self{reported_num, players})
    }

    /// Copies this response and all player records into owned values.
    pub fn to_owned(self) -> OwnedPlayers {
        borrowme::to_owned(self)
    }
}