Skip to main content

a2s_protocol/
rules.rs

1//! Types returned when parsing A2S_RULES responses.
2
3use borrowme::borrowme;
4
5use crate::cursor::{self, Cursor};
6
7#[derive(thiserror::Error, Debug)]
8#[error(transparent)]
9/// An A2S_RULES payload ended before all fields were read or contained invalid UTF-8.
10pub struct Error(#[from] cursor::Error);
11
12pub(crate) const REQUEST_HEADER: &[u8] = b"V";
13pub(crate) const RESPONSE_HEADER: u8 = b'E';
14
15#[borrowme]
16#[derive(Debug)]
17#[owned_attr(derive(Clone))]
18#[owned_attr(doc(hidden))]
19/// One name/value entry returned by an A2S_RULES response.
20///
21/// The strings borrow from the response packet. Use [`Rule::to_owned`] to keep
22/// the entry after releasing that packet.
23pub struct Rule<'a> {
24    /// Rule name.
25    pub name: &'a str,
26    /// Rule value.
27    pub value: &'a str,
28}
29
30#[borrowme]
31#[derive(Debug)]
32#[owned_attr(derive(Clone))]
33#[owned_attr(doc(hidden))]
34/// Rules parsed from an A2S_RULES response.
35///
36/// Rule names and values borrow from the response packet. Use [`Rules::to_owned`]
37/// to create values that no longer borrow from it.
38pub struct Rules<'a> {
39    /// Number of rules reported by the server.
40    pub num: u16,
41    /// Parsed name/value entries.
42    pub rules: Vec<Rule<'a>>,
43}
44
45impl<'a> Rule<'a> {
46    /// Copies this rule entry into an owned value.
47    pub fn to_owned(self) -> OwnedRule {
48        borrowme::to_owned(self)
49    }
50}
51
52impl<'a> Rules<'a> {
53    pub(crate) fn parse(raw: &'a [u8]) -> Result<Self, Error> {
54        let mut cur = Cursor::new(raw);
55        let num = cur.read_short()?;
56        let mut rules = Vec::with_capacity(num as usize);
57
58        for _ in 0..num {
59            rules.push(Rule {
60                name: cur.read_str()?,
61                value: cur.read_str()?,
62            });
63        }
64
65        Ok(Self { num, rules })
66    }
67
68    /// Copies this response and all rule entries into owned values.
69    pub fn to_owned(self) -> OwnedRules {
70        borrowme::to_owned(self)
71    }
72}