a2s-protocol 0.1.1

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

use borrowme::borrowme;

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

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

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

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// One name/value entry returned by an A2S_RULES response.
///
/// The strings borrow from the response packet. Use [`Rule::to_owned`] to keep
/// the entry after releasing that packet.
pub struct Rule<'a> {
    /// Rule name.
    pub name: &'a str,
    /// Rule value.
    pub value: &'a str,
}

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// Rules parsed from an A2S_RULES response.
///
/// Rule names and values borrow from the response packet. Use [`Rules::to_owned`]
/// to create values that no longer borrow from it.
pub struct Rules<'a> {
    /// Number of rules reported by the server.
    pub num: u16,
    /// Parsed name/value entries.
    pub rules: Vec<Rule<'a>>,
}

impl<'a> Rule<'a> {
    /// Copies this rule entry into an owned value.
    pub fn to_owned(self) -> OwnedRule {
        borrowme::to_owned(self)
    }
}

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

        for _ in 0..num {
            rules.push(Rule {
                name: cur.read_str()?,
                value: cur.read_str()?,
            });
        }

        Ok(Self { num, rules })
    }

    /// Copies this response and all rule entries into owned values.
    pub fn to_owned(self) -> OwnedRules {
        borrowme::to_owned(self)
    }
}