vbsp_common/
lightcolor.rs

1use crate::EntityParseError;
2use serde::de::{Error, Unexpected};
3use serde::{Deserialize, Deserializer};
4use std::str::FromStr;
5
6#[derive(Debug, Clone)]
7pub struct LightColor {
8    pub r: u8,
9    pub g: u8,
10    pub b: u8,
11    pub intensity: u16,
12}
13
14impl FromStr for LightColor {
15    type Err = EntityParseError;
16
17    fn from_str(str: &str) -> Result<Self, Self::Err> {
18        let mut values = str.split_whitespace();
19        let r = values
20            .next()
21            .ok_or(EntityParseError::ElementCount)?
22            .parse()
23            .map_err(EntityParseError::Int)?;
24        let g = values
25            .next()
26            .ok_or(EntityParseError::ElementCount)?
27            .parse()
28            .map_err(EntityParseError::Int)?;
29        let b = values
30            .next()
31            .ok_or(EntityParseError::ElementCount)?
32            .parse()
33            .map_err(EntityParseError::Int)?;
34        let intensity = values
35            .next()
36            .ok_or(EntityParseError::ElementCount)?
37            .parse()
38            .map_err(EntityParseError::Int)?;
39        if values.next().is_some() {
40            return Err(EntityParseError::ElementCount);
41        }
42        Ok(LightColor { r, g, b, intensity })
43    }
44}
45
46impl<'de> Deserialize<'de> for LightColor {
47    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
48    where
49        D: Deserializer<'de>,
50    {
51        let str = <&str>::deserialize(deserializer)?;
52        str.parse()
53            .map_err(|_| D::Error::invalid_value(Unexpected::Str(str), &"a list of 4 integers"))
54    }
55}