color.rs

 1use std::{
 2    fmt,
 3    ops::{Deref, DerefMut},
 4};
 5
 6use crate::json::ToJson;
 7use pathfinder_color::ColorU;
 8use serde::{Deserialize, Deserializer};
 9use serde_json::json;
10
11#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
12#[repr(transparent)]
13pub struct Color(ColorU);
14
15impl Color {
16    pub fn transparent_black() -> Self {
17        Self(ColorU::transparent_black())
18    }
19
20    pub fn black() -> Self {
21        Self(ColorU::black())
22    }
23
24    pub fn white() -> Self {
25        Self(ColorU::white())
26    }
27
28    pub fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
29        Self(ColorU::new(r, g, b, a))
30    }
31
32    pub fn from_u32(rgba: u32) -> Self {
33        Self(ColorU::from_u32(rgba))
34    }
35}
36
37impl<'de> Deserialize<'de> for Color {
38    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
39    where
40        D: Deserializer<'de>,
41    {
42        let mut rgba = u32::deserialize(deserializer)?;
43
44        if rgba <= 0xFFFFFF {
45            rgba = (rgba << 8) + 0xFF;
46        }
47
48        Ok(Self::from_u32(rgba))
49    }
50}
51
52impl ToJson for Color {
53    fn to_json(&self) -> serde_json::Value {
54        json!(format!(
55            "0x{:x}{:x}{:x}{:x}",
56            self.0.r, self.0.g, self.0.b, self.0.a
57        ))
58    }
59}
60
61impl Deref for Color {
62    type Target = ColorU;
63    fn deref(&self) -> &Self::Target {
64        &self.0
65    }
66}
67
68impl DerefMut for Color {
69    fn deref_mut(&mut self) -> &mut Self::Target {
70        &mut self.0
71    }
72}
73
74impl fmt::Debug for Color {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        self.0.fmt(f)
77    }
78}