perf(format): elide mirrored instance fields and deduplicate vectors in .figcraft (#1819)

This commit is contained in:
Bryton Cooper
2026-11-28 01:03:16 -07:00
parent d586d37cf8
commit b6a67ae19c
7 changed files with 1875 additions and 7 deletions
+8
View File
@@ -394,6 +394,14 @@ impl Document {
NodeId(self.next_id.next)
}
/// Replace the document's raw node map and `next_id` counter (used by compact format loaders
/// before [`Self::validate`] / [`Self::repair`]).
pub fn set_raw_nodes(&mut self, nodes: impl IntoIterator<Item = (NodeId, Arc<Node>)>, next_id: NodeId) {
self.nodes = nodes.into_iter().map(|(id, node)| (id, NodeArc(node))).collect();
self.next_id.next = next_id.0;
self.dirty = Dirty::default();
}
/// The collaboration client ids are allocated for (0: none, a single-user document).
pub fn client_id(&self) -> u32 {
self.next_id.client
+584
View File
@@ -0,0 +1,584 @@
//! Streaming compact `.figcraft` document deserializer and mirror/vector resolver.
//!
//! Reads legacy v1 `document.json` and compact mirror/vector-table `document.json` in a single
//! streaming pass, resolving mirror chains iteratively with cycle detection and a materialized
//! memory budget against amplification bombs.
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::sync::Arc;
use craft_figcraft_format::{Header, MAX_DOCUMENT};
use figcraft_doc::color::{BlendMode, Color, ColorProfile};
use figcraft_doc::geom::Affine;
use figcraft_doc::{
AnnotationCategory, Ballots, BoardTimer, Comment, DesignReview, DevSnapshot, Document, FileKind, ImagePreset, Libraries, Node, NodeId, NodeKind,
Style, Variables, VectorNetwork, Vote, VoteRecord,
};
use serde::de::{DeserializeSeed, Error as DeError, IgnoredAny, MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use super::fields::{MirrorPatch, apply_full_patch, apply_mirror_patch, deserialize_patch_field, est_node_bytes, est_vector_bytes};
use crate::FormatError;
/// Maximum number of nodes accepted in one `document.json`.
const MAX_NODES: usize = 5_000_000;
/// Minimum materialized memory budget (bytes) allowed for compact expansion.
const MIN_MATERIALIZED_BUDGET: usize = 16 * 1024 * 1024;
/// Maximum allowed materialized expansion ratio relative to input JSON byte length.
const MAX_EXPANSION_RATIO: usize = 256;
/// Materialized memory ceiling for resolving mirrors and `vectorRef` entries.
pub(crate) fn materialized_budget(input_bytes: usize) -> usize {
input_bytes.saturating_mul(MAX_EXPANSION_RATIO).clamp(MIN_MATERIALIZED_BUDGET, MAX_DOCUMENT as usize)
}
/// Parse a `document.json` string (legacy v1 or compact mirrors/vectors), checking the native
/// header and version first.
pub(crate) fn parse_compact_document(text: &str) -> Result<(Document, Header), FormatError> {
if !text.contains("\"mirror\"") && !text.contains("\"vectorRef\"") {
return craft_figcraft_format::read_document_json::<Document>(text).map_err(|e| match e {
craft_figcraft_format::ReadDocumentError::Json(error) => FormatError::Corrupt(error.to_string()),
craft_figcraft_format::ReadDocumentError::NewerVersion(error) => FormatError::Newer(error.0),
});
}
parse_compact_document_with_budget(text, materialized_budget(text.len()))
}
/// [`parse_compact_document`] with an explicit materialized memory budget.
pub(crate) fn parse_compact_document_with_budget(text: &str, budget: usize) -> Result<(Document, Header), FormatError> {
let header = craft_figcraft_format::read_header(text).map_err(|e| FormatError::Corrupt(e.to_string()))?;
craft_figcraft_format::check_version(&header).map_err(|e| FormatError::Newer(e.0))?;
let mut de = serde_json::Deserializer::from_str(text);
let wire = CompactDocSeed { budget }.deserialize(&mut de).map_err(|e| FormatError::Corrupt(e.to_string()))?;
de.end().map_err(|e| FormatError::Corrupt(e.to_string()))?;
let doc = materialize(wire, budget)?;
Ok((doc, header))
}
struct CompactDocWire {
name: String,
kind: FileKind,
pages: Vec<NodeId>,
nodes: BTreeMap<NodeId, CompactNodeEntry>,
vectors: Vec<VectorNetwork>,
next_id: NodeId,
styles: Vec<Style>,
variables: Variables,
current_page: Option<NodeId>,
document_colors: Vec<Color>,
comments: Vec<Comment>,
libraries: Arc<Libraries>,
color_profile: ColorProfile,
image_presets: Vec<ImagePreset>,
design_review: DesignReview,
annotation_categories: Option<Vec<AnnotationCategory>>,
dev_snapshots: BTreeMap<NodeId, Arc<DevSnapshot>>,
timer: Option<BoardTimer>,
vote: Option<Vote>,
votes: Ballots,
vote_history: Vec<VoteRecord>,
}
enum CompactNodeEntry {
Full { node: Box<Node>, vector_ref: Option<u32> },
Mirror(Box<CompactMirror>),
}
struct CompactMirror {
id: NodeId,
source: NodeId,
parent: Option<NodeId>,
children: Vec<NodeId>,
vector_ref: Option<u32>,
explicit_kind: Option<NodeKind>,
patch: MirrorPatch,
}
struct CompactDocSeed {
budget: usize,
}
impl<'de> DeserializeSeed<'de> for CompactDocSeed {
type Value = CompactDocWire;
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
deserializer.deserialize_map(CompactDocVisitor { budget: self.budget })
}
}
struct CompactDocVisitor {
budget: usize,
}
impl<'de> Visitor<'de> for CompactDocVisitor {
type Value = CompactDocWire;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a FigCraft document object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut state = DocParseState::default();
while let Some(key) = map.next_key::<Cow<'de, str>>()? {
read_doc_field(&key, &mut map, &mut state, self.budget)?;
}
state.finish()
}
}
#[derive(Default)]
struct DocParseState {
name: Option<String>,
kind: Option<FileKind>,
pages: Option<Vec<NodeId>>,
nodes: Option<BTreeMap<NodeId, CompactNodeEntry>>,
vectors: Option<Vec<VectorNetwork>>,
next_id: Option<NodeId>,
styles: Option<Vec<Style>>,
variables: Option<Variables>,
current_page: Option<Option<NodeId>>,
document_colors: Option<Vec<Color>>,
comments: Option<Vec<Comment>>,
libraries: Option<Arc<Libraries>>,
color_profile: Option<ColorProfile>,
image_presets: Option<Vec<ImagePreset>>,
design_review: Option<DesignReview>,
annotation_categories: Option<Option<Vec<AnnotationCategory>>>,
dev_snapshots: Option<BTreeMap<NodeId, Arc<DevSnapshot>>>,
timer: Option<Option<BoardTimer>>,
vote: Option<Option<Vote>>,
votes: Option<Ballots>,
vote_history: Option<Vec<VoteRecord>>,
}
impl DocParseState {
fn finish<E: DeError>(self) -> Result<CompactDocWire, E> {
Ok(CompactDocWire {
name: self.name.ok_or_else(|| E::missing_field("name"))?,
kind: self.kind.unwrap_or_default(),
pages: self.pages.ok_or_else(|| E::missing_field("pages"))?,
nodes: self.nodes.ok_or_else(|| E::missing_field("nodes"))?,
vectors: self.vectors.unwrap_or_default(),
next_id: self.next_id.ok_or_else(|| E::missing_field("next_id"))?,
styles: self.styles.unwrap_or_default(),
variables: self.variables.unwrap_or_default(),
current_page: self.current_page.unwrap_or(None),
document_colors: self.document_colors.unwrap_or_default(),
comments: self.comments.unwrap_or_default(),
libraries: self.libraries.unwrap_or_default(),
color_profile: self.color_profile.unwrap_or_default(),
image_presets: self.image_presets.unwrap_or_default(),
design_review: self.design_review.unwrap_or_default(),
annotation_categories: self.annotation_categories.unwrap_or(None),
dev_snapshots: self.dev_snapshots.unwrap_or_default(),
timer: self.timer.unwrap_or(None),
vote: self.vote.unwrap_or(None),
votes: self.votes.unwrap_or_default(),
vote_history: self.vote_history.unwrap_or_default(),
})
}
}
fn read_doc_field<'de, A: MapAccess<'de>>(key: &str, map: &mut A, s: &mut DocParseState, budget: usize) -> Result<(), A::Error> {
match key {
"name" => s.name = Some(map.next_value()?),
"kind" => s.kind = Some(map.next_value()?),
"pages" => s.pages = Some(map.next_value()?),
"nodes" => s.nodes = Some(map.next_value_seed(NodesMapSeed { budget })?),
"vectors" => s.vectors = Some(map.next_value()?),
"next_id" => s.next_id = Some(map.next_value()?),
"styles" => s.styles = Some(map.next_value()?),
"variables" => s.variables = Some(map.next_value()?),
"current_page" => s.current_page = Some(map.next_value()?),
"document_colors" => s.document_colors = Some(map.next_value()?),
"comments" => s.comments = Some(map.next_value()?),
"libraries" => s.libraries = Some(map.next_value()?),
"color_profile" => s.color_profile = Some(map.next_value()?),
"image_presets" => s.image_presets = Some(map.next_value()?),
"design_review" => s.design_review = Some(map.next_value()?),
"annotation_categories" => s.annotation_categories = Some(map.next_value()?),
"dev_snapshots" => s.dev_snapshots = Some(map.next_value()?),
"timer" => s.timer = Some(map.next_value()?),
"vote" => s.vote = Some(map.next_value()?),
"votes" => s.votes = Some(map.next_value()?),
"vote_history" => s.vote_history = Some(map.next_value()?),
_ => {
let _ = map.next_value::<IgnoredAny>()?;
}
}
Ok(())
}
struct NodesMapSeed {
budget: usize,
}
impl<'de> DeserializeSeed<'de> for NodesMapSeed {
type Value = BTreeMap<NodeId, CompactNodeEntry>;
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
deserializer.deserialize_map(NodesMapVisitor { budget: self.budget })
}
}
struct NodesMapVisitor {
budget: usize,
}
impl<'de> Visitor<'de> for NodesMapVisitor {
type Value = BTreeMap<NodeId, CompactNodeEntry>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a map of node ids to nodes")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut nodes = BTreeMap::new();
let mut charged = 0usize;
while let Some(id) = map.next_key::<NodeId>()? {
if nodes.len() >= MAX_NODES {
return Err(A::Error::custom(format!("document exceeds maximum of {MAX_NODES} nodes")));
}
let entry = map.next_value::<CompactNodeEntry>()?;
let charge = match &entry {
CompactNodeEntry::Full { node, .. } => est_node_bytes(node),
CompactNodeEntry::Mirror(_) => std::mem::size_of::<Node>(),
};
charged = charged.saturating_add(charge);
if charged > self.budget {
return Err(A::Error::custom("document exceeds materialized memory budget"));
}
nodes.insert(id, entry);
}
Ok(nodes)
}
}
impl<'de> Deserialize<'de> for CompactNodeEntry {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_map(CompactNodeVisitor)
}
}
struct CompactNodeVisitor;
impl<'de> Visitor<'de> for CompactNodeVisitor {
type Value = CompactNodeEntry;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a layer object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut acc = NodeAccumulator::default();
while let Some(key) = map.next_key::<Cow<'de, str>>()? {
read_node_key(&key, &mut map, &mut acc)?;
}
acc.finish()
}
}
#[derive(Default)]
struct NodeAccumulator {
is_mirror: bool,
id: Option<NodeId>,
source: Option<Option<NodeId>>,
parent: Option<Option<NodeId>>,
children: Option<Vec<NodeId>>,
vector_ref: Option<u32>,
explicit_kind: Option<NodeKind>,
kind_type: Option<String>,
kind_network: Option<VectorNetwork>,
kind_extra: Option<serde_json::Map<String, Value>>,
patch: MirrorPatch,
}
fn is_kind_field(key: &str) -> bool {
matches!(
key,
"background"
| "flows"
| "prototype"
| "opening"
| "contents_hidden"
| "start"
| "sweep"
| "inner"
| "count"
| "inner_ratio"
| "characters"
| "style"
| "runs"
| "auto_resize"
| "align_h"
| "align_v"
| "paragraph_spacing"
| "paragraph_indent"
| "list"
| "paragraphs"
| "list_spacing"
| "hanging_punctuation"
| "hanging_list"
| "leading_trim"
| "max_lines"
| "wrap_style"
| "features"
| "path"
| "saved_breaks"
| "op"
| "description"
| "props"
| "prop_order"
| "component"
)
}
fn read_node_key<'de, A: MapAccess<'de>>(key: &str, map: &mut A, acc: &mut NodeAccumulator) -> Result<(), A::Error> {
match key {
"mirror" => acc.is_mirror = map.next_value()?,
"id" => acc.id = Some(map.next_value()?),
"source" => acc.source = Some(map.next_value()?),
"parent" => acc.parent = Some(map.next_value()?),
"children" => acc.children = Some(map.next_value()?),
"vectorRef" => acc.vector_ref = Some(map.next_value()?),
"kind" => acc.explicit_kind = Some(map.next_value()?),
"type" => acc.kind_type = Some(map.next_value()?),
"network" => acc.kind_network = Some(map.next_value()?),
other => {
if deserialize_patch_field(other, map, &mut acc.patch)? {
return Ok(());
}
if is_kind_field(other) {
let val = map.next_value::<Value>()?;
acc.kind_extra.get_or_insert_with(serde_json::Map::new).insert(other.to_owned(), val);
} else {
let _ = map.next_value::<IgnoredAny>()?;
}
}
}
Ok(())
}
impl NodeAccumulator {
fn finish<E: DeError>(mut self) -> Result<CompactNodeEntry, E> {
let id = self.id.ok_or_else(|| E::missing_field("id"))?;
if self.is_mirror {
if self.explicit_kind.is_some() && self.vector_ref.is_some() {
return Err(E::custom("mirror node cannot set both `kind` and `vectorRef`"));
}
if self.kind_type.is_some() || self.kind_network.is_some() {
return Err(E::custom("mirror node must use `kind` or `vectorRef`, not `type`"));
}
let source = self.source.flatten().ok_or_else(|| E::missing_field("source"))?;
return Ok(CompactNodeEntry::Mirror(Box::new(CompactMirror {
id,
source,
parent: self.parent.flatten(),
children: self.children.unwrap_or_default(),
vector_ref: self.vector_ref,
explicit_kind: self.explicit_kind,
patch: self.patch,
})));
}
let name = self.patch.name.take().ok_or_else(|| E::missing_field("name"))?;
let width = self.patch.width.take().ok_or_else(|| E::missing_field("width"))?;
let height = self.patch.height.take().ok_or_else(|| E::missing_field("height"))?;
let (kind, vector_ref) = build_full_kind(self.kind_type, self.kind_network, self.vector_ref, self.kind_extra)?;
let mut node = Node::new(id, kind, name, 0.0, 0.0);
// Reset kind-specific Node::new presets back to Node's serde defaults before applying fields.
node.width = width;
node.height = height;
node.parent = self.parent.flatten();
node.children = self.children.unwrap_or_default();
node.source = self.source.flatten();
node.fills.clear();
node.strokes.clear();
node.stroke = Default::default();
node.corners = Default::default();
node.blend = BlendMode::PassThrough;
node.clip = false;
node.transform = Affine::IDENTITY;
node.visible = true;
node.opacity = 1.0;
node.scale_factor = 1.0;
apply_full_patch(&mut node, self.patch);
Ok(CompactNodeEntry::Full { node: Box::new(node), vector_ref })
}
}
fn build_full_kind<E: DeError>(
kind_type: Option<String>,
kind_network: Option<VectorNetwork>,
vector_ref: Option<u32>,
kind_extra: Option<serde_json::Map<String, Value>>,
) -> Result<(NodeKind, Option<u32>), E> {
let ty = kind_type.ok_or_else(|| E::missing_field("type"))?;
if vector_ref.is_some() && ty != "vector" {
return Err(E::custom("`vectorRef` is only valid on vector layers"));
}
match ty.as_str() {
"frame" => Ok((NodeKind::Frame, None)),
"group" => Ok((NodeKind::Group, None)),
"rectangle" => Ok((NodeKind::Rectangle, None)),
"line" => Ok((NodeKind::Line, None)),
"slice" => Ok((NodeKind::Slice, None)),
"vector" => match (kind_network, vector_ref) {
(Some(_), Some(_)) => Err(E::custom("vector layer cannot set both `network` and `vectorRef`")),
(Some(network), None) => Ok((NodeKind::Vector { network }, None)),
(None, Some(idx)) => Ok((NodeKind::Vector { network: VectorNetwork::default() }, Some(idx))),
(None, None) => Err(E::missing_field("network")),
},
_ => {
let mut map = kind_extra.unwrap_or_default();
map.insert("type".to_owned(), Value::String(ty));
let kind = serde_json::from_value::<NodeKind>(Value::Object(map)).map_err(E::custom)?;
Ok((kind, None))
}
}
}
fn materialize(wire: CompactDocWire, budget: usize) -> Result<Document, FormatError> {
let vectors = wire.vectors;
let mut charged: usize = vectors.iter().map(est_vector_bytes).fold(0usize, usize::saturating_add);
if charged > budget {
return Err(FormatError::Corrupt("document vectors exceed materialized memory budget".into()));
}
let mut raw = wire.nodes;
let ids: Vec<NodeId> = raw.keys().copied().collect();
let mut resolved: HashMap<NodeId, Arc<Node>> = HashMap::with_capacity(ids.len());
let mut resolving: Vec<NodeId> = Vec::new();
let mut in_stack: HashMap<NodeId, bool> = HashMap::new();
for root_id in ids {
if resolved.contains_key(&root_id) {
continue;
}
resolve_chain(root_id, &mut raw, &vectors, &mut resolved, &mut resolving, &mut in_stack, &mut charged, budget)?;
}
let mut doc = Document::without_pages(wire.name);
doc.kind = wire.kind;
doc.pages = wire.pages;
doc.styles = wire.styles;
doc.variables = wire.variables;
doc.current_page = wire.current_page;
doc.document_colors = wire.document_colors;
doc.comments = wire.comments;
doc.libraries = wire.libraries;
doc.color_profile = wire.color_profile;
doc.image_presets = wire.image_presets;
doc.design_review = wire.design_review;
doc.annotation_categories = wire.annotation_categories;
doc.dev_snapshots = wire.dev_snapshots;
doc.timer = wire.timer;
doc.vote = wire.vote;
doc.votes = wire.votes;
doc.vote_history = wire.vote_history;
doc.set_raw_nodes(resolved, wire.next_id);
Ok(doc)
}
#[allow(clippy::too_many_arguments)]
fn resolve_chain(
start: NodeId,
raw: &mut BTreeMap<NodeId, CompactNodeEntry>,
vectors: &[VectorNetwork],
resolved: &mut HashMap<NodeId, Arc<Node>>,
stack: &mut Vec<NodeId>,
in_stack: &mut HashMap<NodeId, bool>,
charged: &mut usize,
budget: usize,
) -> Result<(), FormatError> {
stack.clear();
let mut cur = start;
loop {
if resolved.contains_key(&cur) {
break;
}
if in_stack.get(&cur).copied().unwrap_or(false) {
return Err(FormatError::Corrupt(format!("mirror cycle involving node {}", cur.0)));
}
let next = match raw.get(&cur) {
Some(CompactNodeEntry::Full { .. }) => {
stack.push(cur);
in_stack.insert(cur, true);
break;
}
Some(CompactNodeEntry::Mirror(m)) => {
if m.source == cur {
return Err(FormatError::Corrupt(format!("mirror node {} references itself", cur.0)));
}
stack.push(cur);
in_stack.insert(cur, true);
m.source
}
None => {
return Err(FormatError::Corrupt(format!("mirror references missing source node {}", cur.0)));
}
};
cur = next;
}
while let Some(id) = stack.pop() {
in_stack.remove(&id);
let Some(entry) = raw.remove(&id) else { continue };
let node = match entry {
CompactNodeEntry::Full { mut node, vector_ref } => {
if let Some(idx) = vector_ref {
let net = lookup_vector(vectors, idx)?;
let base_charge = est_node_bytes(&node);
let net_charge = est_vector_bytes(net);
charge_budget(charged, base_charge.saturating_add(net_charge), budget)?;
node.kind = NodeKind::Vector { network: net.clone() };
} else {
charge_budget(charged, est_node_bytes(&node), budget)?;
}
*node
}
CompactNodeEntry::Mirror(m) => {
let src =
resolved.get(&m.source).ok_or_else(|| FormatError::Corrupt(format!("mirror references missing source node {}", m.source.0)))?;
let vref_net = match m.vector_ref {
Some(idx) => Some(lookup_vector(vectors, idx)?),
None => None,
};
// Charge before cloning the source node or vector network to prevent OOM spikes.
let pre_charge = est_node_bytes(src).saturating_add(vref_net.map_or(0, est_vector_bytes));
charge_budget(charged, pre_charge, budget)?;
let mut node = (**src).clone();
node.id = m.id;
node.source = Some(m.source);
node.parent = m.parent;
node.children = m.children;
if let Some(kind) = m.explicit_kind {
node.kind = kind;
} else if let Some(net) = vref_net {
node.kind = NodeKind::Vector { network: net.clone() };
}
apply_mirror_patch(&mut node, m.patch);
let extra = est_node_bytes(&node).saturating_sub(pre_charge);
charge_budget(charged, extra, budget)?;
node
}
};
resolved.insert(id, Arc::new(node));
}
Ok(())
}
fn lookup_vector(vectors: &[VectorNetwork], idx: u32) -> Result<&VectorNetwork, FormatError> {
usize::try_from(idx).ok().and_then(|i| vectors.get(i)).ok_or_else(|| FormatError::Corrupt(format!("invalid vectorRef {idx}")))
}
fn charge_budget(charged: &mut usize, amount: usize, budget: usize) -> Result<(), FormatError> {
*charged = charged.saturating_add(amount);
if *charged > budget {
return Err(FormatError::Corrupt("document exceeds materialized memory budget".into()));
}
Ok(())
}
+351
View File
@@ -0,0 +1,351 @@
//! Compact `.figcraft` document serializer.
//!
//! Elides unchanged fields on cycle-free mirrored layers (`Node::source`) and deduplicates
//! repeated non-empty `VectorNetwork`s into a top-level `"vectors"` table.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use figcraft_doc::color::BlendMode;
use figcraft_doc::geom::Affine;
use figcraft_doc::{Document, MaskType, Node, NodeId, NodeKind, VectorNetwork};
use serde::ser::{SerializeMap, SerializeStruct};
use serde::{Serialize, Serializer};
use super::decode::materialized_budget;
use super::fields::{canonical_vector_key, est_node_bytes, est_vector_bytes, exact_kind_eq, serialize_mirror_diff_fields};
/// Conservative lower bound on encoded bytes for a compact mirror record.
const MIN_MIRROR_JSON_BYTES: usize = 36;
/// Conservative lower bound on encoded bytes for a full node record.
const MIN_FULL_JSON_BYTES: usize = 128;
/// Serializable view of a [`Document`] that writes mirrored layers as deltas against their
/// `source` and hoists repeated `VectorNetwork`s into `"vectors"`.
pub(crate) struct CompactDocument<'a> {
doc: &'a Document,
mirrors: BTreeSet<NodeId>,
vectors: Vec<&'a VectorNetwork>,
vector_refs: BTreeMap<NodeId, u32>,
}
impl<'a> CompactDocument<'a> {
pub(crate) fn new(doc: &'a Document) -> Self {
let mut mirrors = find_acyclic_mirrors(doc);
let (mut vectors, mut vector_refs) = build_vector_table(doc, &mirrors);
enforce_reload_budget(doc, &mut mirrors, &mut vectors, &mut vector_refs);
Self { doc, mirrors, vectors, vector_refs }
}
}
/// Identifies every node whose `source` pointer chain reaches a live non-cyclic root.
///
/// Uses iterative 3-color traversal so arbitrarily deep chains never overflow the stack.
fn find_acyclic_mirrors(doc: &Document) -> BTreeSet<NodeId> {
// 0 = visiting, 1 = acyclic, 2 = cyclic/invalid
let mut state: HashMap<NodeId, u8> = HashMap::with_capacity(doc.node_count());
let mut mirrors = BTreeSet::new();
let mut chain: Vec<NodeId> = Vec::new();
for node in doc.nodes() {
let Some(src) = node.source else { continue };
if src == node.id || doc.node(src).is_none() {
state.insert(node.id, 2);
continue;
}
chain.clear();
let mut cur = node.id;
let outcome = loop {
if let Some(&st) = state.get(&cur) {
break if st == 1 { 1 } else { 2 };
}
state.insert(cur, 0);
chain.push(cur);
let Some(n) = doc.node(cur) else {
break 2;
};
let Some(next) = n.source else {
break 1;
};
if next == cur || doc.node(next).is_none() {
break 2;
}
cur = next;
};
for id in &chain {
state.insert(*id, outcome);
}
if outcome == 1 {
mirrors.insert(node.id);
}
}
mirrors
}
/// Collects finite non-empty `VectorNetwork`s that would actually be serialized at least twice,
/// assigning deterministic indices in `NodeId` order.
fn build_vector_table<'a>(doc: &'a Document, mirrors: &BTreeSet<NodeId>) -> (Vec<&'a VectorNetwork>, BTreeMap<NodeId, u32>) {
let mut keys: Vec<(NodeId, Vec<u8>, &'a VectorNetwork)> = Vec::new();
let mut counts: HashMap<Vec<u8>, usize> = HashMap::new();
for node in doc.nodes() {
let NodeKind::Vector { network } = &node.kind else { continue };
if mirrors.contains(&node.id)
&& let Some(src) = node.source.and_then(|id| doc.node(id))
&& exact_kind_eq(&node.kind, &src.kind)
{
// Kind is inherited from source; no vector data is emitted for this mirror.
continue;
}
let Some(key) = canonical_vector_key(network) else { continue };
*counts.entry(key.clone()).or_insert(0) += 1;
keys.push((node.id, key, network));
}
let mut vectors: Vec<&'a VectorNetwork> = Vec::new();
let mut index_by_key: HashMap<Vec<u8>, u32> = HashMap::new();
let mut vector_refs: BTreeMap<NodeId, u32> = BTreeMap::new();
for (id, key, net) in keys {
if counts.get(&key).copied().unwrap_or(0) < 2 {
continue;
}
let idx = if let Some(&existing) = index_by_key.get(&key) {
existing
} else {
let Ok(next) = u32::try_from(vectors.len()) else { continue };
vectors.push(net);
index_by_key.insert(key, next);
next
};
vector_refs.insert(id, idx);
}
(vectors, vector_refs)
}
/// Ensures an honest document never compacts below the decoder's amplification budget.
///
/// If a pathological fan-out would exceed `materialized_budget(est_json_bytes)`, drops compact
/// encoding so the saved document always reloads cleanly.
fn enforce_reload_budget(doc: &Document, mirrors: &mut BTreeSet<NodeId>, vectors: &mut Vec<&VectorNetwork>, vector_refs: &mut BTreeMap<NodeId, u32>) {
if mirrors.is_empty() && vectors.is_empty() {
return;
}
let nodes_charge: usize = doc.nodes().map(est_node_bytes).fold(0usize, usize::saturating_add);
let vecs_charge: usize = vectors.iter().map(|v| est_vector_bytes(v)).fold(0usize, usize::saturating_add);
let total_materialized = nodes_charge.saturating_add(vecs_charge);
let est_compact = doc
.node_count()
.saturating_sub(mirrors.len())
.saturating_mul(MIN_FULL_JSON_BYTES)
.saturating_add(mirrors.len().saturating_mul(MIN_MIRROR_JSON_BYTES));
if total_materialized > materialized_budget(est_compact) {
mirrors.clear();
vectors.clear();
vector_refs.clear();
}
}
impl Serialize for CompactDocument<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let d = self.doc;
let mut st = serializer.serialize_struct("Document", 20)?;
st.serialize_field("name", &d.name)?;
if !d.kind.is_design() {
st.serialize_field("kind", &d.kind)?;
}
st.serialize_field("pages", &d.pages)?;
if !self.vectors.is_empty() {
st.serialize_field("vectors", &self.vectors)?;
}
st.serialize_field("nodes", &CompactNodesMap { doc: d, mirrors: &self.mirrors, vector_refs: &self.vector_refs })?;
st.serialize_field("next_id", &d.next_id())?;
st.serialize_field("styles", &d.styles)?;
st.serialize_field("variables", &d.variables)?;
st.serialize_field("current_page", &d.current_page)?;
st.serialize_field("document_colors", &d.document_colors)?;
st.serialize_field("comments", &d.comments)?;
if !figcraft_doc::Libraries::is_unused(&d.libraries) {
st.serialize_field("libraries", &d.libraries)?;
}
if !d.color_profile.is_srgb() {
st.serialize_field("color_profile", &d.color_profile)?;
}
if !d.image_presets.is_empty() {
st.serialize_field("image_presets", &d.image_presets)?;
}
if !d.design_review.is_default() {
st.serialize_field("design_review", &d.design_review)?;
}
if d.annotation_categories.is_some() {
st.serialize_field("annotation_categories", &d.annotation_categories)?;
}
if !d.dev_snapshots.is_empty() {
st.serialize_field("dev_snapshots", &d.dev_snapshots)?;
}
if d.timer.is_some() {
st.serialize_field("timer", &d.timer)?;
}
if d.vote.is_some() {
st.serialize_field("vote", &d.vote)?;
}
if !d.votes.is_empty() {
st.serialize_field("votes", &d.votes)?;
}
if !d.vote_history.is_empty() {
st.serialize_field("vote_history", &d.vote_history)?;
}
st.end()
}
}
struct CompactNodesMap<'a> {
doc: &'a Document,
mirrors: &'a BTreeSet<NodeId>,
vector_refs: &'a BTreeMap<NodeId, u32>,
}
impl Serialize for CompactNodesMap<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(Some(self.doc.node_count()))?;
for node in self.doc.nodes() {
if self.mirrors.contains(&node.id)
&& let Some(src_id) = node.source
&& let Some(src) = self.doc.node(src_id)
{
let vref = self.vector_refs.get(&node.id).copied();
map.serialize_entry(&node.id, &CompactMirrorNode { node, src, vector_ref: vref })?;
} else if let Some(&vref) = self.vector_refs.get(&node.id) {
map.serialize_entry(&node.id, &FullVectorRefNode { node, vector_ref: vref })?;
} else {
map.serialize_entry(&node.id, node)?;
}
}
map.end()
}
}
struct CompactMirrorNode<'a> {
node: &'a Node,
src: &'a Node,
vector_ref: Option<u32>,
}
impl Serialize for CompactMirrorNode<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?;
map.serialize_entry("mirror", &true)?;
map.serialize_entry("id", &self.node.id)?;
if let Some(src_id) = self.node.source {
map.serialize_entry("source", &src_id)?;
}
if let Some(parent) = self.node.parent {
map.serialize_entry("parent", &parent)?;
}
if !self.node.children.is_empty() {
map.serialize_entry("children", &self.node.children)?;
}
if !exact_kind_eq(&self.node.kind, &self.src.kind) {
if let Some(idx) = self.vector_ref {
map.serialize_entry("vectorRef", &idx)?;
} else {
map.serialize_entry("kind", &self.node.kind)?;
}
}
serialize_mirror_diff_fields(&mut map, self.src, self.node)?;
map.end()
}
}
/// Full non-mirror `NodeKind::Vector` serialized with `"type": "vector"` and `"vectorRef": idx`
/// instead of an inline `"network"`.
struct FullVectorRefNode<'a> {
node: &'a Node,
vector_ref: u32,
}
impl Serialize for FullVectorRefNode<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let n = self.node;
let mut map = serializer.serialize_map(None)?;
map.serialize_entry("id", &n.id)?;
map.serialize_entry("name", &n.name)?;
map.serialize_entry("type", "vector")?;
map.serialize_entry("vectorRef", &self.vector_ref)?;
if let Some(parent) = n.parent {
map.serialize_entry("parent", &parent)?;
}
if !n.children.is_empty() {
map.serialize_entry("children", &n.children)?;
}
if !n.visible {
map.serialize_entry("visible", &n.visible)?;
}
if n.locked {
map.serialize_entry("locked", &n.locked)?;
}
if n.opacity != 1.0 {
map.serialize_entry("opacity", &n.opacity)?;
}
if n.blend != BlendMode::PassThrough {
map.serialize_entry("blend", &n.blend)?;
}
if n.transform != Affine::IDENTITY {
map.serialize_entry("transform", &n.transform)?;
}
map.serialize_entry("width", &n.width)?;
map.serialize_entry("height", &n.height)?;
serialize_optional_full_fields(&mut map, n)?;
map.end()
}
}
fn emit_if<S: SerializeMap, T: Serialize + ?Sized>(map: &mut S, key: &str, cond: bool, val: &T) -> Result<(), S::Error> {
if cond {
map.serialize_entry(key, val)?;
}
Ok(())
}
fn serialize_optional_full_fields<S: SerializeMap>(map: &mut S, n: &Node) -> Result<(), S::Error> {
serialize_paint_and_layout_fields(map, n)?;
serialize_component_and_meta_fields(map, n)
}
fn serialize_paint_and_layout_fields<S: SerializeMap>(map: &mut S, n: &Node) -> Result<(), S::Error> {
emit_if(map, "fills", !n.fills.is_empty(), &n.fills)?;
emit_if(map, "strokes", !n.strokes.is_empty(), &n.strokes)?;
emit_if(map, "stroke", n.stroke != Default::default(), &n.stroke)?;
emit_if(map, "effects", !n.effects.is_empty(), &n.effects)?;
emit_if(map, "corners", n.corners != Default::default(), &n.corners)?;
emit_if(map, "constraints", n.constraints != Default::default(), &n.constraints)?;
emit_if(map, "layout", n.layout.is_some(), &n.layout)?;
emit_if(map, "child_layout", n.child_layout != Default::default(), &n.child_layout)?;
emit_if(map, "clip", n.clip, &n.clip)?;
emit_if(map, "is_mask", n.is_mask, &n.is_mask)?;
emit_if(map, "mask_type", !MaskType::is_alpha(&n.mask_type), &n.mask_type)?;
emit_if(map, "grids", !n.grids.is_empty(), &n.grids)?;
emit_if(map, "guides", !n.guides.is_empty(), &n.guides)?;
emit_if(map, "exports", !n.exports.is_empty(), &n.exports)?;
emit_if(map, "interactions", !n.interactions.is_empty(), &n.interactions)?;
emit_if(map, "overflow", n.overflow != Default::default(), &n.overflow)?;
emit_if(map, "scroll_position", n.scroll_position != Default::default(), &n.scroll_position)?;
emit_if(map, "styles", n.styles != Default::default(), &n.styles)
}
fn serialize_component_and_meta_fields<S: SerializeMap>(map: &mut S, n: &Node) -> Result<(), S::Error> {
emit_if(map, "bound", !n.bound.is_empty(), &n.bound)?;
emit_if(map, "var_modes", !n.var_modes.is_empty(), &n.var_modes)?;
emit_if(map, "scale_factor", n.scale_factor != 1.0, &n.scale_factor)?;
emit_if(map, "bool_op", n.bool_op.is_some(), &n.bool_op)?;
emit_if(map, "constrain_proportions", n.constrain_proportions, &n.constrain_proportions)?;
emit_if(map, "source", n.source.is_some(), &n.source)?;
emit_if(map, "exposed", n.exposed, &n.exposed)?;
emit_if(map, "dev_status", !n.dev_status.is_none(), &n.dev_status)?;
emit_if(map, "dev_changed", n.dev_changed, &n.dev_changed)?;
emit_if(map, "dev_note", !n.dev_note.is_empty(), &n.dev_note)?;
emit_if(map, "overrides", !n.overrides.is_empty(), &n.overrides)?;
emit_if(map, "prop_refs", !n.prop_refs.is_empty(), &n.prop_refs)?;
emit_if(map, "plugin_data", !n.plugin_data.is_empty(), &n.plugin_data)?;
emit_if(map, "annotations", !n.annotations.is_empty(), &n.annotations)?;
emit_if(map, "code_links", !n.code_links.is_empty(), &n.code_links)?;
emit_if(map, "dev_resources", !n.dev_resources.is_empty(), &n.dev_resources)?;
emit_if(map, "measurements", !n.measurements.is_empty(), &n.measurements)?;
emit_if(map, "board", n.board.is_some(), &n.board)
}
+500
View File
@@ -0,0 +1,500 @@
//! Structural equality, canonical vector keys, and single-source field mapping for compact
//! `.figcraft` mirror deltas.
//!
//! `Paint` ignores `color_alpha` in `PartialEq`, and IEEE-754 equates `-0.0` with `0.0`.
//! Float and paint fields therefore compare bit-for-bit or via serialized JSON so mirror
//! encoding never drops data that full `document.json` preserves.
use std::collections::{BTreeMap, BTreeSet};
use figcraft_doc::color::{BlendMode, Paint, PaintKind};
use figcraft_doc::geom::Affine;
use figcraft_doc::proto::{Interaction, Overflow, ScrollPosition};
use figcraft_doc::{
Annotation, AutoLayout, BoardItem, BoolOp, ChildLayout, CodeLink, CollectionId, Constraints, Corners, DevResource, DevStatus, Effect,
ExportSetting, Guide, LayoutGrid, LetterSpacing, LineHeight, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, StrokeProps,
StyleRefs, TextData, TextStyle, VariableId, VectorNetwork, Vertex,
};
use serde::Serialize;
use serde::de::MapAccess;
use serde::ser::SerializeMap;
/// Defines `MirrorPatch` plus mirror diff-serialization, streaming field deserialization, and
/// patch application from one field table so adding or editing a field keeps all paths in lockstep.
macro_rules! compact_mirror_fields {
(
boxed: [ $( $bkey:literal => $bfield:ident : $bty:ty => $beq:ident ),* $(,)? ],
value: [ $( $vkey:literal => $vfield:ident : $vty:ty => $veq:ident ),* $(,)? ]
) => {
#[derive(Default)]
pub(super) struct MirrorPatch {
pub(super) guides: Option<Vec<Guide>>,
$( pub(super) $bfield: Option<Box<$bty>>, )*
$( pub(super) $vfield: Option<$vty>, )*
}
pub(super) fn serialize_mirror_diff_fields<S: SerializeMap>(
map: &mut S,
src: &Node,
node: &Node,
) -> Result<(), S::Error> {
if !eq_vec_exact(&node.guides, &src.guides) {
map.serialize_entry("guides", &node.guides)?;
}
$(
if !$beq(&node.$bfield, &src.$bfield) {
map.serialize_entry($bkey, &node.$bfield)?;
}
)*
$(
if !$veq(&node.$vfield, &src.$vfield) {
map.serialize_entry($vkey, &node.$vfield)?;
}
)*
Ok(())
}
pub(super) fn deserialize_patch_field<'de, A: MapAccess<'de>>(
key: &str,
map: &mut A,
patch: &mut MirrorPatch,
) -> Result<bool, A::Error> {
if key == "guides" {
let list = map.next_value::<Vec<Guide>>()?;
patch.guides.get_or_insert_with(Vec::new).extend(list);
return Ok(true);
}
match key {
$(
$bkey => {
patch.$bfield = Some(Box::new(map.next_value::<$bty>()?));
Ok(true)
}
)*
$(
$vkey => {
patch.$vfield = Some(map.next_value::<$vty>()?);
Ok(true)
}
)*
_ => Ok(false),
}
}
pub(super) fn apply_mirror_patch(node: &mut Node, patch: MirrorPatch) {
if let Some(guides) = patch.guides {
node.guides = guides;
}
$(
if let Some(v) = patch.$bfield {
node.$bfield = *v;
}
)*
$(
if let Some(v) = patch.$vfield {
node.$vfield = v;
}
)*
}
pub(super) fn apply_full_patch(node: &mut Node, patch: MirrorPatch) {
apply_mirror_patch(node, patch);
}
};
}
compact_mirror_fields! {
boxed: [
"stroke" => stroke: StrokeProps => eq_stroke,
"child_layout" => child_layout: ChildLayout => eq_child_layout,
"styles" => styles: StyleRefs => eq_plain,
],
value: [
"name" => name: String => eq_plain,
"visible" => visible: bool => eq_plain,
"locked" => locked: bool => eq_plain,
"opacity" => opacity: f32 => eq_f32,
"blend" => blend: BlendMode => eq_plain,
"transform" => transform: Affine => eq_affine,
"width" => width: f64 => eq_f64,
"height" => height: f64 => eq_f64,
"fills" => fills: Vec<Paint> => eq_paint_vec,
"strokes" => strokes: Vec<Paint> => eq_paint_vec,
"effects" => effects: Vec<Effect> => eq_vec_exact,
"corners" => corners: Corners => eq_corners,
"constraints" => constraints: Constraints => eq_plain,
"layout" => layout: Option<AutoLayout> => eq_opt_exact,
"clip" => clip: bool => eq_plain,
"is_mask" => is_mask: bool => eq_plain,
"mask_type" => mask_type: MaskType => eq_plain,
"grids" => grids: Vec<LayoutGrid> => eq_vec_exact,
"exports" => exports: Vec<ExportSetting> => eq_vec_exact,
"interactions" => interactions: Vec<Interaction> => eq_vec_exact,
"overflow" => overflow: Overflow => eq_plain,
"scroll_position" => scroll_position: ScrollPosition => eq_scroll_position,
"bound" => bound: BTreeMap<String, VariableId> => eq_plain,
"var_modes" => var_modes: BTreeMap<CollectionId, ModeId> => eq_plain,
"scale_factor" => scale_factor: f64 => eq_f64,
"bool_op" => bool_op: Option<BoolOp> => eq_plain,
"constrain_proportions" => constrain_proportions: bool => eq_plain,
"exposed" => exposed: bool => eq_plain,
"dev_status" => dev_status: DevStatus => eq_plain,
"dev_changed" => dev_changed: bool => eq_plain,
"dev_note" => dev_note: String => eq_plain,
"overrides" => overrides: BTreeSet<String> => eq_plain,
"prop_refs" => prop_refs: BTreeMap<String, String> => eq_plain,
"plugin_data" => plugin_data: BTreeMap<String, String> => eq_plain,
"annotations" => annotations: Vec<Annotation> => eq_vec_exact,
"code_links" => code_links: Vec<CodeLink> => eq_plain,
"dev_resources" => dev_resources: Vec<DevResource> => eq_plain,
"measurements" => measurements: Vec<Measurement> => eq_vec_exact,
"board" => board: Option<BoardItem> => eq_opt_exact,
]
}
/// Fails to compile if a new field is added to `figcraft_doc::Node` without updating
/// `compact_mirror_fields!`.
#[allow(dead_code)]
fn every_node_field_visited(n: &Node) {
let Node {
id: _,
name: _,
kind: _,
parent: _,
children: _,
visible: _,
locked: _,
opacity: _,
blend: _,
transform: _,
width: _,
height: _,
fills: _,
strokes: _,
stroke: _,
effects: _,
corners: _,
constraints: _,
layout: _,
child_layout: _,
clip: _,
is_mask: _,
mask_type: _,
grids: _,
guides: _,
exports: _,
interactions: _,
overflow: _,
scroll_position: _,
styles: _,
bound: _,
var_modes: _,
scale_factor: _,
bool_op: _,
constrain_proportions: _,
source: _,
exposed: _,
dev_status: _,
dev_changed: _,
dev_note: _,
overrides: _,
prop_refs: _,
plugin_data: _,
annotations: _,
code_links: _,
dev_resources: _,
measurements: _,
board: _,
} = n;
}
/// Canonical JSON key for deduplicating finite `VectorNetwork`s without losing `-0.0` or
/// `Paint::color_alpha`.
pub(super) fn canonical_vector_key(net: &VectorNetwork) -> Option<Vec<u8>> {
if net.vertices.is_empty() || !is_finite_network(net) {
return None;
}
serde_json::to_vec(net).ok()
}
/// Whether every float in `net` is finite (non-finite networks stay inline so `FiniteValue`
/// sanitizes them directly).
pub(super) fn is_finite_network(net: &VectorNetwork) -> bool {
let verts_ok = net.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite() && v.radius.is_finite());
let segs_ok = net.segments.iter().all(|s| s.ta.0.is_finite() && s.ta.1.is_finite() && s.tb.0.is_finite() && s.tb.1.is_finite());
let regs_ok = net.regions.iter().all(is_finite_region);
verts_ok && segs_ok && regs_ok
}
fn is_finite_region(r: &Region) -> bool {
let space_ok =
r.paint_space.is_none_or(|ps| ps.width.is_finite() && ps.height.is_finite() && ps.transform.as_coeffs().iter().all(|c| c.is_finite()));
let fills_ok = r.fills.as_ref().is_none_or(|fs| fs.iter().all(is_finite_paint));
space_ok && fills_ok
}
fn is_finite_paint(p: &Paint) -> bool {
if !p.opacity.is_finite() || !p.color_alpha.is_finite() {
return false;
}
match &p.kind {
PaintKind::Solid { color } => color.r.is_finite() && color.g.is_finite() && color.b.is_finite() && color.a.is_finite(),
_ => serde_json::to_vec(&p.kind).is_ok(),
}
}
/// Conservative heap byte estimate for one `VectorNetwork`.
pub(super) fn est_vector_bytes(net: &VectorNetwork) -> usize {
let loops: usize = net.regions.iter().map(|r| r.loops.iter().map(|l| l.len().saturating_mul(8)).sum::<usize>()).sum();
net.vertices
.len()
.saturating_mul(std::mem::size_of::<Vertex>())
.saturating_add(net.segments.len().saturating_mul(std::mem::size_of::<Segment>()))
.saturating_add(net.regions.len().saturating_mul(std::mem::size_of::<Region>()))
.saturating_add(loops)
}
/// Conservative heap byte estimate for one materialized `Node`.
pub(super) fn est_node_bytes(node: &Node) -> usize {
let kind_extra = match &node.kind {
NodeKind::Vector { network } => est_vector_bytes(network),
NodeKind::Text(t) => t
.characters
.len()
.saturating_add(t.runs.len().saturating_mul(std::mem::size_of::<figcraft_doc::StyleRun>()))
.saturating_add(t.paragraphs.len().saturating_mul(16)),
NodeKind::Component { description, props, prop_order } => {
description.len().saturating_add(props.len().saturating_mul(64)).saturating_add(prop_order.len().saturating_mul(24))
}
NodeKind::Instance { props, .. } => props.len().saturating_mul(64),
_ => 0,
};
let bound_bytes: usize = node.bound.iter().map(|(k, v)| k.len().saturating_add(v.len()).saturating_add(64)).sum();
let var_modes_bytes: usize = node.var_modes.iter().map(|(k, v)| k.len().saturating_add(v.len()).saturating_add(64)).sum();
let plugin_bytes: usize = node.plugin_data.iter().map(|(k, v)| k.len().saturating_add(v.len()).saturating_add(48)).sum();
let prop_refs_bytes: usize = node.prop_refs.iter().map(|(k, v)| k.len().saturating_add(v.len()).saturating_add(48)).sum();
std::mem::size_of::<Node>()
.saturating_add(node.name.len())
.saturating_add(node.children.len().saturating_mul(8))
.saturating_add(node.fills.len().saturating_mul(std::mem::size_of::<Paint>()))
.saturating_add(node.strokes.len().saturating_mul(std::mem::size_of::<Paint>()))
.saturating_add(node.effects.len().saturating_mul(std::mem::size_of::<Effect>()))
.saturating_add(node.overrides.len().saturating_mul(32))
.saturating_add(bound_bytes)
.saturating_add(var_modes_bytes)
.saturating_add(plugin_bytes)
.saturating_add(prop_refs_bytes)
.saturating_add(kind_extra)
}
#[inline]
fn eq_plain<T: PartialEq>(a: &T, b: &T) -> bool {
a == b
}
#[inline]
fn eq_f64(a: &f64, b: &f64) -> bool {
a.to_bits() == b.to_bits()
}
#[inline]
fn eq_f32(a: &f32, b: &f32) -> bool {
a.to_bits() == b.to_bits()
}
#[inline]
fn eq_affine(a: &Affine, b: &Affine) -> bool {
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| x.to_bits() == y.to_bits())
}
fn eq_opt_f64(a: Option<f64>, b: Option<f64>) -> bool {
match (a, b) {
(None, None) => true,
(Some(x), Some(y)) => eq_f64(&x, &y),
_ => false,
}
}
fn eq_corners(a: &Corners, b: &Corners) -> bool {
a.radii.iter().zip(&b.radii).all(|(x, y)| eq_f64(x, y)) && eq_f64(&a.smoothing, &b.smoothing)
}
fn eq_child_layout(a: &ChildLayout, b: &ChildLayout) -> bool {
a.sizing_h == b.sizing_h
&& a.sizing_v == b.sizing_v
&& a.absolute == b.absolute
&& eq_opt_f64(a.min_w, b.min_w)
&& eq_opt_f64(a.max_w, b.max_w)
&& eq_opt_f64(a.min_h, b.min_h)
&& eq_opt_f64(a.max_h, b.max_h)
&& a.grid_column == b.grid_column
&& a.grid_row == b.grid_row
&& a.grid_column_span == b.grid_column_span
&& a.grid_row_span == b.grid_row_span
}
fn eq_scroll_position(a: &ScrollPosition, b: &ScrollPosition) -> bool {
a == b
}
fn eq_stroke(a: &StrokeProps, b: &StrokeProps) -> bool {
if !eq_f64(&a.weight, &b.weight)
|| a.align != b.align
|| a.cap_start != b.cap_start
|| a.cap_end != b.cap_end
|| a.join != b.join
|| !eq_f64(&a.miter_limit, &b.miter_limit)
|| a.dash_cap != b.dash_cap
|| a.dashes.len() != b.dashes.len()
|| !a.dashes.iter().zip(&b.dashes).all(|(x, y)| eq_f64(x, y))
{
return false;
}
let sides_ok = match (a.sides, b.sides) {
(None, None) => true,
(Some(x), Some(y)) => x.iter().zip(&y).all(|(l, r)| eq_f64(l, r)),
_ => false,
};
sides_ok && eq_opt_exact(&a.width_profile, &b.width_profile) && eq_opt_exact(&a.brush, &b.brush)
}
fn eq_json<T: Serialize + ?Sized>(a: &T, b: &T) -> bool {
matches!((serde_json::to_vec(a), serde_json::to_vec(b)), (Ok(x), Ok(y)) if x == y)
}
fn eq_exact<T: Serialize + PartialEq>(a: &T, b: &T) -> bool {
a == b && eq_json(a, b)
}
fn eq_vec_exact<T: Serialize + PartialEq>(a: &[T], b: &[T]) -> bool {
(a.is_empty() && b.is_empty()) || (a == b && eq_json(a, b))
}
fn eq_opt_exact<T: Serialize + PartialEq>(a: &Option<T>, b: &Option<T>) -> bool {
match (a, b) {
(None, None) => true,
(Some(x), Some(y)) => x == y && eq_json(x, y),
_ => false,
}
}
fn eq_paint(a: &Paint, b: &Paint) -> bool {
if a.visible != b.visible || a.blend != b.blend || !eq_f32(&a.opacity, &b.opacity) || !eq_f32(&a.color_alpha, &b.color_alpha) {
return false;
}
match (&a.kind, &b.kind) {
(PaintKind::Solid { color: ca }, PaintKind::Solid { color: cb }) => {
eq_f32(&ca.r, &cb.r) && eq_f32(&ca.g, &cb.g) && eq_f32(&ca.b, &cb.b) && eq_f32(&ca.a, &cb.a)
}
_ => a.kind == b.kind && eq_json(&a.kind, &b.kind),
}
}
fn eq_paint_vec(a: &[Paint], b: &[Paint]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| eq_paint(x, y))
}
fn eq_vertex(a: &Vertex, b: &Vertex) -> bool {
eq_f64(&a.x, &b.x) && eq_f64(&a.y, &b.y) && eq_f64(&a.radius, &b.radius) && a.mirror == b.mirror && a.cap == b.cap && a.join == b.join
}
fn eq_segment(a: &Segment, b: &Segment) -> bool {
a.a == b.a && a.b == b.b && eq_f64(&a.ta.0, &b.ta.0) && eq_f64(&a.ta.1, &b.ta.1) && eq_f64(&a.tb.0, &b.tb.0) && eq_f64(&a.tb.1, &b.tb.1)
}
fn eq_region(a: &Region, b: &Region) -> bool {
let fills_ok = match (&a.fills, &b.fills) {
(None, None) => true,
(Some(fa), Some(fb)) => eq_paint_vec(fa, fb),
_ => false,
};
let space_ok = match (a.paint_space, b.paint_space) {
(None, None) => true,
(Some(pa), Some(pb)) => eq_f64(&pa.width, &pb.width) && eq_f64(&pa.height, &pb.height) && eq_affine(&pa.transform, &pb.transform),
_ => false,
};
a.winding == b.winding && a.loops == b.loops && fills_ok && space_ok
}
pub(super) fn exact_vector_network_eq(a: &VectorNetwork, b: &VectorNetwork) -> bool {
a.vertices.len() == b.vertices.len()
&& a.segments.len() == b.segments.len()
&& a.regions.len() == b.regions.len()
&& a.vertices.iter().zip(&b.vertices).all(|(x, y)| eq_vertex(x, y))
&& a.segments.iter().zip(&b.segments).all(|(x, y)| eq_segment(x, y))
&& a.regions.iter().zip(&b.regions).all(|(x, y)| eq_region(x, y))
}
fn eq_line_height(a: LineHeight, b: LineHeight) -> bool {
match (a, b) {
(LineHeight::Auto, LineHeight::Auto) => true,
(LineHeight::Pixels(x), LineHeight::Pixels(y)) | (LineHeight::Percent(x), LineHeight::Percent(y)) => eq_f64(&x, &y),
_ => false,
}
}
fn eq_letter_spacing(a: LetterSpacing, b: LetterSpacing) -> bool {
match (a, b) {
(LetterSpacing::Pixels(x), LetterSpacing::Pixels(y)) | (LetterSpacing::Percent(x), LetterSpacing::Percent(y)) => eq_f64(&x, &y),
_ => false,
}
}
fn eq_text_style(a: &TextStyle, b: &TextStyle) -> bool {
if a.font_family != b.font_family
|| a.font_style != b.font_style
|| !eq_f64(&a.font_size, &b.font_size)
|| !eq_line_height(a.line_height, b.line_height)
|| !eq_letter_spacing(a.letter_spacing, b.letter_spacing)
|| a.decoration != b.decoration
|| a.case != b.case
|| a.position != b.position
|| a.link != b.link
|| a.style_id != b.style_id
|| a.variations.len() != b.variations.len()
|| !a.variations.iter().zip(&b.variations).all(|((ka, va), (kb, vb))| ka == kb && eq_f64(va, vb))
{
return false;
}
let fills_ok = match (&a.fills, &b.fills) {
(None, None) => true,
(Some(fa), Some(fb)) => eq_paint_vec(fa, fb),
_ => false,
};
fills_ok && eq_opt_exact(&a.decoration_look, &b.decoration_look)
}
fn eq_text_data(a: &TextData, b: &TextData) -> bool {
a.characters == b.characters
&& eq_text_style(&a.style, &b.style)
&& a.auto_resize == b.auto_resize
&& a.align_h == b.align_h
&& a.align_v == b.align_v
&& eq_f64(&a.paragraph_spacing, &b.paragraph_spacing)
&& eq_f64(&a.paragraph_indent, &b.paragraph_indent)
&& a.list == b.list
&& a.paragraphs == b.paragraphs
&& eq_f64(&a.list_spacing, &b.list_spacing)
&& a.hanging_punctuation == b.hanging_punctuation
&& a.hanging_list == b.hanging_list
&& a.leading_trim == b.leading_trim
&& a.max_lines == b.max_lines
&& a.wrap_style == b.wrap_style
&& a.features == b.features
&& eq_vec_exact(&a.runs, &b.runs)
&& eq_opt_exact(&a.path, &b.path)
&& eq_opt_exact(&a.saved_breaks, &b.saved_breaks)
}
pub(super) fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool {
match (a, b) {
(NodeKind::Frame, NodeKind::Frame)
| (NodeKind::Group, NodeKind::Group)
| (NodeKind::Rectangle, NodeKind::Rectangle)
| (NodeKind::Line, NodeKind::Line)
| (NodeKind::Slice, NodeKind::Slice) => true,
(NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => exact_vector_network_eq(na, nb),
(NodeKind::Text(ta), NodeKind::Text(tb)) => eq_text_data(ta, tb),
_ => eq_exact(a, b),
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Compact `.figcraft` document encoding for mirrored instance layers and repeated vectors.
//!
//! Unchanged and partially overridden mirrored layers (`Node::source`) are written as delta
//! records (`"mirror": true` plus only the fields that differ from `source`), and repeated
//! non-empty `VectorNetwork`s are hoisted into a top-level `"vectors"` table referenced by
//! `"vectorRef"`. Documents without mirrors or repeated vectors serialize identically to legacy
//! `document.json`, and legacy v1 files always load unchanged.
mod decode;
mod encode;
mod fields;
pub(crate) use decode::parse_compact_document;
pub(crate) use encode::CompactDocument;
#[cfg(test)]
pub(crate) use decode::{materialized_budget, parse_compact_document_with_budget};
+404
View File
@@ -0,0 +1,404 @@
//! Tests for compact `.figcraft` mirror-delta and vector-table encoding.
use figcraft_doc::color::{Color, Paint};
use figcraft_doc::geom::{Affine, Point};
use figcraft_doc::{Document, Guide, NodeKind, TextData, VectorNetwork};
use super::*;
fn star_vector(points: usize, radius: f64) -> VectorNetwork {
let pts: Vec<Point> = (0..points)
.map(|i| {
let angle = (i as f64) * std::f64::consts::TAU / (points as f64);
let r = if i % 2 == 0 { radius } else { radius * 0.5 };
Point::new(angle.cos() * r, angle.sin() * r)
})
.collect();
VectorNetwork::from_points(&pts, true)
}
fn assert_docs_exact(a: &Document, b: &Document) {
assert_eq!(a.node_count(), b.node_count());
assert_eq!(a.pages, b.pages);
assert_eq!(a.name, b.name);
for na in a.nodes() {
let nb = b.node(na.id).expect("missing node");
assert_eq!(na, nb, "node {} `{}`", na.id.0, na.name);
assert_eq!(na.width.to_bits(), nb.width.to_bits(), "width bits on {}", na.id.0);
assert_eq!(na.height.to_bits(), nb.height.to_bits(), "height bits on {}", na.id.0);
assert_eq!(na.opacity.to_bits(), nb.opacity.to_bits(), "opacity bits on {}", na.id.0);
for (pa, pb) in na.fills.iter().zip(&nb.fills) {
assert_eq!(pa.color_alpha.to_bits(), pb.color_alpha.to_bits(), "color_alpha on {}", na.id.0);
}
}
}
fn build_component_instances_doc(instances: usize, layers_per_component: usize, icon_vertices: usize) -> Document {
let mut doc = Document::new("DesignSystem");
let page = doc.first_page().unwrap();
let comp = doc
.create(
page,
NodeKind::Component { description: "Card".into(), props: Default::default(), prop_order: Vec::new() },
"Card",
0.0,
0.0,
400.0,
300.0,
)
.unwrap();
let icon_net = star_vector(icon_vertices, 12.0);
let mut src_children = Vec::with_capacity(layers_per_component);
for i in 0..layers_per_component {
let kind = match i % 4 {
0 => NodeKind::Text(TextData::new(format!("Label {i}"))),
1 => NodeKind::Vector { network: icon_net.clone() },
_ => NodeKind::Rectangle,
};
let cid = doc.create(comp, kind, &format!("L{i}"), (i % 8) as f64 * 48.0, (i / 8) as f64 * 56.0, 40.0, 40.0).unwrap();
src_children.push(cid);
}
for k in 0..instances {
let inst = doc
.create(
page,
NodeKind::Instance { component: comp, props: Default::default() },
"Card",
((k % 32) as f64) * 420.0,
((k / 32) as f64) * 320.0,
400.0,
300.0,
)
.unwrap();
doc.get_mut(inst).unwrap().source = Some(comp);
for (idx, &src_id) in src_children.iter().enumerate() {
let src_node = doc.node(src_id).unwrap().clone();
let mut copy = src_node;
copy.id = doc.alloc_id();
copy.parent = None;
copy.children.clear();
copy.source = Some(src_id);
// Override one label per instance to exercise partial mirror deltas too.
if idx == 0 && k % 3 == 0 {
if let NodeKind::Text(ref mut t) = copy.kind {
t.characters = format!("Custom {k}");
}
copy.overrides.insert("characters".into());
}
doc.insert(copy, inst, None).unwrap();
}
}
doc
}
#[test]
fn mirrored_layers_are_elided_and_roundtrip_deterministically() {
let doc = build_component_instances_doc(128, 20, 32);
let mut compact_json = Vec::new();
write_json(&doc, &mut compact_json).unwrap();
let full_json = serde_json::to_vec(&doc).unwrap();
assert!(
compact_json.len() * 4 < full_json.len(),
"expected >4x reduction in document.json: compact={} vs full={}",
compact_json.len(),
full_json.len()
);
let text = std::str::from_utf8(&compact_json).unwrap();
let (back, issues) = from_json(text).unwrap();
assert!(issues.is_empty(), "{issues:?}");
assert_docs_exact(&doc, &back);
// Resaving produces byte-identical document.json.
let mut second_json = Vec::new();
write_json(&back, &mut second_json).unwrap();
assert_eq!(compact_json, second_json);
// Round-tripping through serde_json::Value (alphabetical key order) also works.
let val = to_json(&doc).unwrap();
let (from_val, val_issues) = from_json(&val.to_string()).unwrap();
assert!(val_issues.is_empty(), "{val_issues:?}");
assert_docs_exact(&doc, &from_val);
// Full `.figcraft` archive + preview still works cleanly.
let archive = save_bytes(&doc, None).unwrap();
let (loaded, load_issues) = load_bytes(&archive).unwrap();
assert!(load_issues.is_empty(), "{load_issues:?}");
assert_docs_exact(&doc, &loaded);
let preview = thumbnail::archive_preview(std::io::Cursor::new(&archive), 64);
assert!(preview.page.is_some());
}
#[test]
fn mirror_deltas_preserve_default_overrides_negative_zero_color_alpha_and_nested_chains() {
let mut doc = Document::new("EdgeCases");
let page = doc.first_page().unwrap();
let comp = doc
.create(
page,
NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() },
"C",
0.0,
0.0,
100.0,
100.0,
)
.unwrap();
let src = doc.create(comp, NodeKind::Frame, "Box", 0.0, 0.0, 50.0, 50.0).unwrap();
{
let s = doc.get_mut(src).unwrap();
s.clip = true;
s.visible = false;
s.opacity = 0.5;
s.guides.push(Guide { vertical: true, offset: 12.0 });
let mut p = Paint::solid(Color::WHITE);
p.color_alpha = 0.25;
s.fills = vec![p];
}
// Mirror 1 resets non-default source fields back to defaults, flips -0.0 and color_alpha.
let mut m1 = doc.node(src).unwrap().clone();
m1.id = doc.alloc_id();
m1.parent = None;
m1.children.clear();
m1.source = Some(src);
m1.clip = false;
m1.visible = true;
m1.opacity = 1.0;
m1.guides.clear();
m1.width = -0.0;
m1.fills[0].color_alpha = 0.75;
let m1_id = doc.insert(m1, page, None).unwrap();
// Mirror 2 chains onto Mirror 1 and changes transform only.
let mut m2 = doc.node(m1_id).unwrap().clone();
m2.id = doc.alloc_id();
m2.parent = None;
m2.children.clear();
m2.source = Some(m1_id);
m2.transform = Affine::translate((20.0, 30.0));
doc.insert(m2, page, None).unwrap();
let v = to_json(&doc).unwrap();
assert_eq!(v["nodes"][m1_id.0.to_string()]["mirror"], json!(true));
let (back, issues) = from_json(&v.to_string()).unwrap();
assert!(issues.is_empty(), "{issues:?}");
assert_docs_exact(&doc, &back);
}
#[test]
fn repeated_non_mirror_vector_networks_are_deduplicated_in_vectors_table() {
let mut doc = Document::new("Icons");
let page = doc.first_page().unwrap();
let icon = star_vector(48, 24.0);
for i in 0..8 {
doc.create(page, NodeKind::Vector { network: icon.clone() }, &format!("Icon {i}"), i as f64 * 30.0, 0.0, 24.0, 24.0).unwrap();
}
let val = to_json(&doc).unwrap();
assert_eq!(val["vectors"].as_array().map(Vec::len), Some(1));
let (back, issues) = from_json(&val.to_string()).unwrap();
assert!(issues.is_empty(), "{issues:?}");
assert_docs_exact(&doc, &back);
let mut a = Vec::new();
let mut b = Vec::new();
write_json(&doc, &mut a).unwrap();
write_json(&back, &mut b).unwrap();
assert_eq!(a, b);
}
#[test]
fn cyclic_source_pointers_fall_back_on_encode_and_are_rejected_on_decode() {
let mut doc = Document::new("Cycle");
let page = doc.first_page().unwrap();
let a = doc.create(page, NodeKind::Rectangle, "A", 0.0, 0.0, 10.0, 10.0).unwrap();
let b = doc.create(page, NodeKind::Rectangle, "B", 10.0, 0.0, 10.0, 10.0).unwrap();
doc.get_mut(a).unwrap().source = Some(b);
doc.get_mut(b).unwrap().source = Some(a);
// Encoder falls back to full nodes rather than hanging or producing invalid mirrors.
let v = to_json(&doc).unwrap();
assert!(v["nodes"][a.0.to_string()].get("mirror").is_none());
assert!(v["nodes"][b.0.to_string()].get("mirror").is_none());
let (back, _) = from_json(&v.to_string()).unwrap();
assert_docs_exact(&doc, &back);
// Hand-crafted cyclic mirror JSON is rejected cleanly.
let cyclic = r#"{"format":"figcraft","version":1,"imageIndex":[],"name":"C","pages":[1],"next_id":4,"nodes":{
"1":{"id":1,"name":"Page","type":"page","width":0.0,"height":0.0,"children":[2,3]},
"2":{"mirror":true,"id":2,"source":3,"parent":1},
"3":{"mirror":true,"id":3,"source":2,"parent":1}
}}"#;
assert!(matches!(from_json(cyclic), Err(FormatError::Corrupt(_))));
// Self-mirror and missing source are rejected cleanly.
let self_mirror = r#"{"format":"figcraft","version":1,"imageIndex":[],"name":"C","pages":[1],"next_id":3,"nodes":{
"1":{"id":1,"name":"Page","type":"page","width":0.0,"height":0.0,"children":[2]},
"2":{"mirror":true,"id":2,"source":2,"parent":1}
}}"#;
assert!(matches!(from_json(self_mirror), Err(FormatError::Corrupt(_))));
let missing_source = r#"{"format":"figcraft","version":1,"imageIndex":[],"name":"C","pages":[1],"next_id":3,"nodes":{
"1":{"id":1,"name":"Page","type":"page","width":0.0,"height":0.0,"children":[2]},
"2":{"mirror":true,"id":2,"source":999,"parent":1}
}}"#;
assert!(matches!(from_json(missing_source), Err(FormatError::Corrupt(_))));
}
#[test]
fn invalid_vector_refs_and_amplification_bombs_are_rejected() {
let bad_ref = r#"{"format":"figcraft","version":1,"imageIndex":[],"name":"V","pages":[1],"next_id":3,"vectors":[],"nodes":{
"1":{"id":1,"name":"Page","type":"page","width":0.0,"height":0.0,"children":[2]},
"2":{"id":2,"name":"Bad","type":"vector","vectorRef":0,"parent":1,"width":10.0,"height":10.0}
}}"#;
assert!(matches!(from_json(bad_ref), Err(FormatError::Corrupt(_))));
let both_net_and_ref = r#"{"format":"figcraft","version":1,"imageIndex":[],"name":"V","pages":[1],"next_id":3,"vectors":[{"vertices":[],"segments":[],"regions":[]}],"nodes":{
"1":{"id":1,"name":"Page","type":"page","width":0.0,"height":0.0,"children":[2]},
"2":{"id":2,"name":"Bad","type":"vector","vectorRef":0,"network":{"vertices":[],"segments":[],"regions":[]},"parent":1,"width":10.0,"height":10.0}
}}"#;
assert!(matches!(from_json(both_net_and_ref), Err(FormatError::Corrupt(_))));
// Amplification bomb: 1 heavy vector source mirrored 1,000 times against a small budget.
let doc = build_component_instances_doc(50, 4, 256);
let mut json_bytes = Vec::new();
write_json(&doc, &mut json_bytes).unwrap();
let text = std::str::from_utf8(&json_bytes).unwrap();
assert!(compact::materialized_budget(text.len()) > 0);
assert!(matches!(compact::parse_compact_document_with_budget(text, 64 * 1024), Err(FormatError::Corrupt(_))));
}
#[test]
fn truncation_and_bit_flip_mutations_never_panic() {
let doc = build_component_instances_doc(4, 6, 16);
let mut raw = Vec::new();
write_json(&doc, &mut raw).unwrap();
// Truncation sweep across stride points.
let step = (raw.len() / 64).max(1);
for len in (0..raw.len()).step_by(step) {
if let Ok(s) = std::str::from_utf8(&raw[..len]) {
let _ = from_json(s);
}
}
// Single-byte bit-flip sweep across stride points.
for idx in (0..raw.len()).step_by(step) {
let mut mutated = raw.clone();
mutated[idx] ^= 0x55;
if let Ok(s) = std::str::from_utf8(&mutated) {
let _ = from_json(s);
}
}
}
#[test]
#[ignore = "benchmark: run with cargo test --release -p figcraft-format bench_compact_format -- --ignored --nocapture"]
fn bench_compact_format() {
use std::time::Instant;
let cases: [(&str, Document); 3] = [
("42k heavy instances (64-vtx icons)", build_component_instances_doc(1024, 40, 64)),
("42k light instances (no vectors)", {
let mut doc = Document::new("Light");
let page = doc.first_page().unwrap();
let comp = doc
.create(
page,
NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() },
"Card",
0.0,
0.0,
400.0,
300.0,
)
.unwrap();
let mut kids = Vec::new();
for i in 0..40 {
let kind = if i % 4 == 0 { NodeKind::Text(TextData::new(format!("Label {i}"))) } else { NodeKind::Rectangle };
kids.push(doc.create(comp, kind, &format!("L{i}"), (i % 8) as f64 * 48.0, (i / 8) as f64 * 56.0, 40.0, 40.0).unwrap());
}
for k in 0..1024 {
let inst = doc
.create(
page,
NodeKind::Instance { component: comp, props: Default::default() },
"Card",
(k % 32) as f64 * 420.0,
(k / 32) as f64 * 320.0,
400.0,
300.0,
)
.unwrap();
doc.get_mut(inst).unwrap().source = Some(comp);
for &src_id in &kids {
let mut c = doc.node(src_id).unwrap().clone();
c.id = doc.alloc_id();
c.parent = None;
c.children.clear();
c.source = Some(src_id);
doc.insert(c, inst, None).unwrap();
}
}
doc
}),
("42k flat (no instances)", {
let mut doc = Document::new("Flat");
let page = doc.first_page().unwrap();
for i in 0..42_000 {
let kind = if i % 4 == 0 { NodeKind::Text(TextData::new(format!("Label {i}"))) } else { NodeKind::Rectangle };
doc.create(page, kind, &format!("L{i}"), (i % 100) as f64 * 50.0, (i / 100) as f64 * 50.0, 40.0, 40.0).unwrap();
}
doc
}),
];
for (label, doc) in &cases {
let t0 = Instant::now();
let mut legacy_json = Vec::new();
craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), &mut legacy_json).unwrap();
let legacy_write = t0.elapsed();
let t1 = Instant::now();
let legacy_text = std::str::from_utf8(&legacy_json).unwrap();
let (_legacy_back, _) = craft_figcraft_format::read_document_json::<Document>(legacy_text).unwrap();
let legacy_read = t1.elapsed();
let t2 = Instant::now();
let mut compact_json = Vec::new();
write_json(doc, &mut compact_json).unwrap();
let compact_write = t2.elapsed();
let t3 = Instant::now();
let compact_text = std::str::from_utf8(&compact_json).unwrap();
let (compact_back, issues) = from_json(compact_text).unwrap();
let compact_read = t3.elapsed();
assert!(issues.is_empty());
assert_eq!(compact_back.node_count(), doc.node_count());
let t4 = Instant::now();
let zip_bytes = save_bytes(doc, None).unwrap();
let zip_save = t4.elapsed();
let t5 = Instant::now();
let (_zip_back, zip_issues) = load_bytes(&zip_bytes).unwrap();
let zip_load = t5.elapsed();
assert!(zip_issues.is_empty());
eprintln!(
"[{label}] nodes={}\n document.json: {:.2} MB -> {:.2} MB ({:.2}x)\n write_json: {:.1} ms -> {:.1} ms ({:.2}x)\n from_json: {:.1} ms -> {:.1} ms ({:.2}x)\n .figcraft zip: {:.2} MB (save {:.1} ms, load {:.1} ms)",
doc.node_count(),
legacy_json.len() as f64 / 1_048_576.0,
compact_json.len() as f64 / 1_048_576.0,
legacy_json.len() as f64 / compact_json.len() as f64,
legacy_write.as_secs_f64() * 1000.0,
compact_write.as_secs_f64() * 1000.0,
legacy_write.as_secs_f64() / compact_write.as_secs_f64(),
legacy_read.as_secs_f64() * 1000.0,
compact_read.as_secs_f64() * 1000.0,
legacy_read.as_secs_f64() / compact_read.as_secs_f64(),
zip_bytes.len() as f64 / 1_048_576.0,
zip_save.as_secs_f64() * 1000.0,
zip_load.as_secs_f64() * 1000.0,
);
}
}
+11 -7
View File
@@ -1,7 +1,9 @@
//! The native `.figcraft` format.
//!
//! A zip archive holding `document.json` (the [`Document`] as JSON, with a `format`/`version`
//! header; layer fields at their default values are left out and read back as those defaults),
//! header; layer fields at their default values are left out and read back as those defaults,
//! mirrored instance layers are written as deltas against their `source`, and repeated vector
//! networks are hoisted into a top-level `vectors` table),
//! `images/<sha256>` for every image the document (or a saved version) uses, an optional
//! `thumbnail.png` and an optional version history: `versions/index.json` (`{"versions": [{id,
//! name, description, time, images}]}`, oldest first) plus one `versions/<id>.json` snapshot per
@@ -44,6 +46,7 @@ pub use library::{is_valid_library_id, read_library, read_library_within};
#[cfg(not(target_arch = "wasm32"))]
pub use streaming_save::{collect_live_images, save_file_with_history};
mod compact;
mod density;
use std::collections::{BTreeMap, BTreeSet};
@@ -479,8 +482,9 @@ impl<S: serde::ser::SerializeStructVariant> serde::ser::SerializeStructVariant f
/// NaN and infinite numbers are written as `0`.
pub fn to_json(doc: &Document) -> Result<Value, FormatError> {
{
let compact = compact::CompactDocument::new(doc);
let mut bytes = Vec::new();
craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), &mut bytes).map_err(io_err)?;
craft_figcraft_format::write_document_json(&FiniteValue(&compact), &native_image_index(doc), &mut bytes).map_err(io_err)?;
serde_json::from_slice(&bytes).map_err(io_err)
}
}
@@ -488,7 +492,8 @@ pub fn to_json(doc: &Document) -> Result<Value, FormatError> {
/// Write the document (without images) as `document.json` content to `w`.
/// NaN and infinite numbers are written as `0`.
pub fn write_json(doc: &Document, w: impl Write) -> Result<(), FormatError> {
craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), w).map_err(io_err)
let compact = compact::CompactDocument::new(doc);
craft_figcraft_format::write_document_json(&FiniteValue(&compact), &native_image_index(doc), w).map_err(io_err)
}
/// Parse `document.json` content.
@@ -500,10 +505,7 @@ pub fn from_json(text: &str) -> Result<(Document, Vec<String>), FormatError> {
/// (a newer file is refused before its document is read), then the document is deserialized
/// straight from the text.
fn parse_json(text: &str) -> Result<(Document, Vec<String>, ImageIndex), FormatError> {
let (mut doc, header) = craft_figcraft_format::read_document_json::<Document>(text).map_err(|e| match e {
craft_figcraft_format::ReadDocumentError::Json(error) => FormatError::Corrupt(error.to_string()),
craft_figcraft_format::ReadDocumentError::NewerVersion(error) => FormatError::Newer(error.0),
})?;
let (mut doc, header) = compact::parse_compact_document(text)?;
let images = header.images.map(|hashes| hashes.into_iter().collect());
let issues = doc.validate();
if !issues.is_empty() {
@@ -1256,6 +1258,8 @@ pub fn load_file(path: &std::path::Path) -> Result<(Document, Vec<String>), Form
#[cfg(test)]
mod branch_tests;
#[cfg(test)]
mod compact_tests;
#[cfg(test)]
mod dtcg_tests;
#[cfg(test)]
mod guides_tests;