Skip to main content

a2s_protocol/
player.rs

1//! Types returned when parsing A2S_PLAYER responses.
2
3use borrowme::borrowme;
4
5use crate::cursor::{self, Cursor};
6
7#[derive(thiserror::Error, Debug)]
8#[error(transparent)]
9/// An A2S_PLAYER payload ended before all required fields were read or contained invalid UTF-8.
10pub struct Error(#[from] cursor::Error);
11
12pub(crate) const REQUEST_HEADER: &[u8] = b"U";
13pub(crate) const RESPONSE_HEADER: u8 = b'D';
14
15#[borrowme]
16#[derive(Debug)]
17#[owned_attr(derive(Clone))]
18#[owned_attr(doc(hidden))]
19/// One player record from an A2S_PLAYER response.
20///
21/// The player name borrows from the response packet. Use [`Player::to_owned`]
22/// to keep an owned copy after the packet is released.
23pub struct Player<'a> {
24    /// Player index reported by the server.
25    pub index: u8,
26    /// Player name.
27    pub name: &'a str,
28    /// Player score.
29    pub score: i32,
30    /// Connection duration in seconds.
31    pub duration: f32
32}
33
34#[borrowme]
35#[derive(Debug)]
36#[owned_attr(derive(Clone))]
37#[owned_attr(doc(hidden))]
38/// Player records parsed from an A2S_PLAYER response.
39///
40/// Some older engines count players who are still connecting in
41/// [`reported_num`](Self::reported_num) without including a record for them.
42/// Therefore `reported_num` may be greater than `players.len()`.
43pub struct Players<'a> {
44    /// Number of players reported by the server, including any connecting players.
45    pub reported_num: u8,
46    /// Parsed player records returned by the server.
47    pub players: Vec<Player<'a>>
48}
49
50impl<'a> Player<'a> {
51    /// Copies this player record into an owned value.
52    pub fn to_owned(self) -> OwnedPlayer {
53        borrowme::to_owned(self)
54    }
55
56    fn parse(cur: &mut Cursor<'a>) -> Result<Self, Error> {
57        Ok(Self {
58            index: cur.read_byte()?,
59            name: cur.read_str()?,
60            score: cur.read_long()?,
61            duration: cur.read_float()?,
62        })
63    }
64}
65
66impl<'a> Players<'a> {
67    pub(crate) fn parse(raw: &'a [u8]) -> Result<Self, Error> {
68        let mut cur = Cursor::new(raw);
69        let reported_num = cur.read_byte()?;
70        let mut players = Vec::with_capacity(reported_num as usize);
71
72        while !cur.is_end() {
73            players.push(Player::parse(&mut cur)?);
74        }
75
76        Ok(Self{reported_num, players})
77    }
78
79    /// Copies this response and all player records into owned values.
80    pub fn to_owned(self) -> OwnedPlayers {
81        borrowme::to_owned(self)
82    }
83}