feat: implement Display for Color

This commit is contained in:
aviac 2023-09-25 08:56:23 +02:00
parent 032428b98e
commit ff9c410c44
No known key found for this signature in database
GPG key ID: 644781002BDEA982
3 changed files with 13 additions and 9 deletions

2
Cargo.lock generated
View file

@ -224,7 +224,7 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "forgejo-api-types"
version = "0.1.5"
version = "0.1.6"
dependencies = [
"chrono",
"clap",

View file

@ -1,6 +1,6 @@
[package]
name = "forgejo-api-types"
version = "0.1.5"
version = "0.1.6"
edition = "2021"
license = "AGPL-3.0-or-later"
keywords = ["forgejo", "types", "codeberg", "api"]

View file

@ -1,3 +1,4 @@
use std::fmt::Display;
use std::ops::{Deref, DerefMut};
use palette::rgb::Rgb;
@ -16,6 +17,12 @@ impl Deref for Color {
}
}
impl Display for Color {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "#{:02X}{:02X}{:02X}", self.red, self.green, self.blue)
}
}
impl DerefMut for Color {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
@ -27,10 +34,7 @@ impl Serialize for Color {
where
S: Serializer,
{
// Convert the RGB color to a six-digit hexadecimal string
let hex_string =
format!("#{:02X}{:02X}{:02X}", self.red, self.green, self.blue).to_lowercase();
serializer.serialize_str(&hex_string)
serializer.serialize_str(self.to_string().as_str())
}
}
@ -79,7 +83,7 @@ mod color_tests {
fn color_serialize() {
// Example of serializing and deserializing
let rgb_color = Color(Rgb::new(0x64, 0x32, 0xc8));
let rgb_color_str = "\"#6432c8\"";
let rgb_color_str = "\"#6432C8\"";
let serialized = serde_json::to_string(&rgb_color).unwrap();
assert_eq!(serialized, rgb_color_str);
@ -89,7 +93,7 @@ mod color_tests {
fn color_deserialize() {
// Example of serializing and deserializing
let rgb_color = Color(Rgb::new(0x64, 0x32, 0xc8));
let rgb_color_str = "\"#6432c8\"";
let rgb_color_str = "\"#6432C8\"";
let deserialized: Color = serde_json::from_str(rgb_color_str).unwrap();
assert_eq!(deserialized, rgb_color);
@ -98,7 +102,7 @@ mod color_tests {
#[test]
fn multiple_pound_symbols_not_allowed() {
// Example of serializing and deserializing
let rgb_color_str = "\"##6432c8\"";
let rgb_color_str = "\"##6432C8\"";
let deserialized: Result<Color, _> = serde_json::from_str(rgb_color_str);
assert!(deserialized.is_err());