perf(serialization): 优化颜色模块的序列化性能

使用直接序列化结构代替中间JSON对象,减少内存分配和转换开销
This commit is contained in:
徐涛 2025-07-18 13:47:45 +08:00
parent 137079e5c6
commit 600c8c92ce
2 changed files with 24 additions and 23 deletions

View File

@ -3,8 +3,7 @@ use std::sync::Arc;
use linked_hash_map::LinkedHashMap;
use palette::{Oklch, color_difference::Wcag21RelativeContrast, luma::Luma};
use serde::Serialize;
use serde_json::json;
use serde::{Serialize, ser::SerializeStruct};
use crate::{
convert::{map_oklch_to_luma, map_oklch_to_srgb_hex},
@ -281,15 +280,14 @@ impl Serialize for ColorSet {
let on_root = map_oklch_to_srgb_hex(&self.on_root);
let on_disabled = map_oklch_to_srgb_hex(&self.on_disabled);
let color_set_object = json!({
"root": root,
"hover": hover,
"active": active,
"focus": focus,
"disabled": disabled,
"onRoot": on_root,
"onDisabled": on_disabled,
});
color_set_object.serialize(serializer)
let mut state = serializer.serialize_struct("ColorSet", 6)?;
state.serialize_field("root", &root)?;
state.serialize_field("hover", &hover)?;
state.serialize_field("active", &active)?;
state.serialize_field("focus", &focus)?;
state.serialize_field("disabled", &disabled)?;
state.serialize_field("onRoot", &on_root)?;
state.serialize_field("onDisabled", &on_disabled)?;
state.end()
}
}

View File

@ -1,7 +1,7 @@
use internment::Intern;
use linked_hash_map::LinkedHashMap;
use palette::Oklch;
use serde::Serialize;
use serde_json::Value;
use serde::{Serialize, ser::SerializeStruct};
use crate::convert::map_oklch_to_srgb_hex;
@ -77,20 +77,23 @@ impl Swatch {
}
}
fn get_static_str(s: &str) -> &'static str {
Intern::new(s.to_string()).as_ref()
}
impl Serialize for Swatch {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let swatch_object = SWATCH_LIGHTINGS
.iter()
.map(|l| {
let color = self.get_hex(*l);
let key = format!("{l:02}");
(key, color)
})
.collect::<Value>();
let mut state = serializer.serialize_struct("Swatch", SWATCH_LIGHTINGS.len())?;
swatch_object.serialize(serializer)
for l in SWATCH_LIGHTINGS {
let color = self.get_hex(l);
let key: &'static str = get_static_str(&format!("{l:02}"));
state.serialize_field(key, &color)?;
}
state.end()
}
}