Add custom serde implemenation for color
This commit is contained in:
parent
2e51faed54
commit
571dedbd2e
2 changed files with 56 additions and 1 deletions
|
@ -14,3 +14,7 @@ reprc_proc_macro = { path = "src/reprc_proc_macro" }
|
|||
|
||||
# networking
|
||||
serde = { version = "1.0.197", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { version = "1.0.114" }
|
||||
|
||||
|
|
53
src/color.rs
53
src/color.rs
|
@ -3,10 +3,11 @@ use std::ops::MulAssign;
|
|||
use std::str::FromStr;
|
||||
use std::{convert::TryFrom, ops::Mul};
|
||||
|
||||
use serde::de::Visitor;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// `TextColor` describes the color of the text
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||
pub enum Color {
|
||||
White,
|
||||
Black,
|
||||
|
@ -189,6 +190,46 @@ impl Default for Color {
|
|||
}
|
||||
}
|
||||
|
||||
impl Serialize for Color {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&format!("{self}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Color {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
struct ColorVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for ColorVisitor {
|
||||
type Value = Color;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("`color`")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Color, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
Color::try_from(value).map_err(|_| {
|
||||
serde::de::Error::invalid_value(
|
||||
serde::de::Unexpected::Str(value),
|
||||
&ColorVisitor,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_identifier(ColorVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simple_color_conversion() {
|
||||
let color = Color::try_from("white").unwrap();
|
||||
|
@ -206,3 +247,13 @@ fn hex_color_conversion() {
|
|||
|
||||
assert_eq!(string, "#FFFFFF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_serde() {
|
||||
let color = Color::try_from("#a64b4b").unwrap();
|
||||
|
||||
let s = serde_json::to_string(&color).unwrap();
|
||||
let c = serde_json::from_str(&s).unwrap();
|
||||
|
||||
assert_eq!(color, c);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue