Merge pull request #477 from MorionTutoriales/experiment/cached-layer-image-dependencies

Avoid recompositing unrelated texture sets and layers after image imports
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-15 00:18:27 -05:00
commit a0e2cf1efc
15 files changed
+507 -221

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# Code style
Style conventions for MaterialCraft's Rust code.
Style conventions for TextureCraft's Rust code.
Read alongside [AGENTS.md](AGENTS.md) for repository requirements.
## Naming and Rust conventions
+55 -20
View File
@@ -10,10 +10,11 @@ use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
use crate::image_identity::ImageIdentity;
use crate::store::{BakedMaps, ImageStore, PixelStore};
/// Default byte budget of a [`BelowCache`], per nesting level it holds (see
@@ -78,48 +79,82 @@ pub struct StackKey {
layers: Vec<Layer>,
pixels: Vec<(LayerId, Option<Channel>, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
images: Vec<(String, usize)>,
images: Vec<(String, ImageIdentity)>,
}
impl StackKey {
/// The key of `roots` (layers of texture set `ts`, bottom → top) and their effects.
pub fn new(project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, ts: usize, roots: &[LayerId]) -> Option<StackKey> {
StackKey::of_tree(project, pixels, baked, images, ts, roots.to_vec(), &project.render_tree(roots))
/// The key of `roots` (layers of a texture set, bottom → top) and their effects.
pub fn new(
project: &Project,
pixels: &PixelStore,
baked: &BakedMaps,
images: &ImageStore,
texture_set_index: usize,
roots: &[LayerId],
) -> Option<StackKey> {
StackKey::of_tree(project, pixels, baked, images, texture_set_index, roots.to_vec(), &project.render_tree(roots))
}
/// The key of the layers in `tree` (and their effects), drawn as `roots` arrange them.
/// The key of the layers in `render_tree` (and their effects), drawn as `roots` arrange them.
fn of_tree(
project: &Project,
pixels: &PixelStore,
baked: &BakedMaps,
images: &ImageStore,
ts: usize,
texture_set_index: usize,
roots: Vec<LayerId>,
tree: &BTreeSet<LayerId>,
render_tree: &BTreeSet<LayerId>,
) -> Option<StackKey> {
let mut set = project.texture_set(ts).ok()?.clone();
let mut set = project.texture_set(texture_set_index).ok()?.clone();
set.name.clear();
set.description.clear();
set.stack.clear();
set.bake = Default::default();
let effects: BTreeSet<LayerId> = tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
let pixels = tree
let effect_ids: BTreeSet<LayerId> = render_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
let pixel_handles = render_tree
.iter()
.chain(&effects)
.chain(&effect_ids)
.flat_map(|id| {
let layer = Channel::ALL.into_iter().filter_map(move |c| pixels.layer(*id, c).map(|img| (*id, Some(c), Shared(img.clone()))));
layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone()))))
let layer_channels =
Channel::ALL.into_iter().filter_map(move |channel| pixels.layer(*id, channel).map(|image| (*id, Some(channel), Shared(image.clone()))));
layer_channels.chain(pixels.masks.get(id).map(|image| (*id, None, Shared(image.clone()))))
})
.collect();
let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect();
images.sort();
let mut referenced_images = BTreeSet::new();
if !images.is_empty() {
let mut record_image_reference = |source: &Source| {
if let Source::Image { name, .. } = source
&& let Some((name, _)) = images.get_key_value(name)
{
referenced_images.insert(name);
}
};
for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) {
if let LayerKind::Fill(fill) = &layer.kind {
fill.sources.values().for_each(&mut record_image_reference);
}
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
match &effect.kind {
EffectKind::Fill { source, .. } => record_image_reference(source),
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
_ => {}
}
}
}
}
let image_identities =
referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect();
Some(StackKey {
set,
roots,
layers: tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
pixels,
baked: (baked.resolution, baked.maps.iter().map(|(m, d)| (*m, Arc::as_ptr(d) as usize)).collect()),
images,
layers: render_tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
pixels: pixel_handles,
baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()),
images: image_identities,
})
}
}
+19
View File
@@ -0,0 +1,19 @@
use std::sync::{Arc, Weak};
use crate::store::ImageRes;
/// Keeps an image's allocation identity stable without retaining pixels after resource removal.
#[derive(Debug)]
pub(crate) struct ImageIdentity(Weak<ImageRes>);
impl ImageIdentity {
pub(crate) fn new(image: &Arc<ImageRes>) -> Self {
Self(Arc::downgrade(image))
}
}
impl PartialEq for ImageIdentity {
fn eq(&self, other: &Self) -> bool {
self.0.ptr_eq(&other.0)
}
}
+1
View File
@@ -13,6 +13,7 @@ mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
pub mod eval;
mod image_identity;
pub mod pattern;
pub mod store;
pub mod thumb;
@@ -573,3 +573,61 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
assert!(!check_cached(&f, 0, hot).is_empty());
}
}
#[test]
fn cached_stack_tracks_referenced_images_only() {
use std::sync::Arc;
use texturecraft_compose::{ImageRes, ImageStore};
let mut fixture = fixture();
let hot_layer = heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") };
fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() });
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let mut images = ImageStore::default();
let baked = Default::default();
let tiles = all_tiles(RES, RES);
let mut cache = BelowCache::default();
cache.set_hot(Some(hot_layer));
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
let mut previous_image = None;
for stage in ["cold", "resolve", "unused1", "unused2", "unused3", "replace", "remove"] {
match stage {
"resolve" => {
let image = image_with_value(1.0);
previous_image = Some(Arc::downgrade(&image));
images.insert("used".into(), image);
}
"replace" => {
let replacement = image_with_value(0.4);
let replacement_weak = Arc::downgrade(&replacement);
images.insert("used".into(), replacement);
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels");
previous_image = Some(replacement_weak);
}
"remove" => {
images.remove("used");
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels");
}
"cold" => {}
_ => {
images.insert(stage.into(), image_with_value(0.5));
}
}
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
let input = inputs(&fixture, 0, &images, &baked);
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
let retained = cache.len() - 1;
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}");
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
composite_tiles(&input, &mut expected, &tiles);
assert!(output == expected, "{stage}");
}
}
+27 -20
View File
@@ -383,38 +383,45 @@ impl Session {
/// With `merge`, this folds into the previous undo step when that was an edit of the same kind
/// (a parameter set while the cook ran).
pub fn apply_link_cook(&mut self, id: LayerId, bytes: &[u8], merge: bool) -> Result<()> {
let m = read_mcmat(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let maps = decoded_maps(&m)?;
let names = self.edit_merging(EDIT, merge, |s| {
let LayerKind::Fill(mut fill) = s.doc.project.layer(id)?.kind.clone() else {
let material = read_mcmat(bytes).map_err(|error| EngineError::Other(error.to_string()))?;
let maps = decoded_maps(&material)?;
let names = self.edit_merging(EDIT, merge, |session| {
let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else {
return Err(EngineError::Other(format!("layer {} is not a fill", id.0)));
};
let link = fill.link.as_mut().ok_or_else(|| EngineError::Other(format!("layer {} is not a MaterialCraft material", id.0)))?;
for p in &mut link.params {
if let Some(cooked) = m.manifest.parameters.iter().find(|c| c.id == p.id) {
p.value = cooked.value.clone();
for parameter in &mut link.params {
if let Some(cooked) = material.manifest.parameters.iter().find(|candidate| candidate.id == parameter.id) {
parameter.value = cooked.value.clone();
}
}
link.size = m.manifest.size[0];
link.size = material.manifest.size[0];
let stem = texturecraft_formats::sanitize_resource_name(&link.name);
let old: Vec<String> =
fill.sources.values().filter_map(|src| if let Source::Image { name, .. } = src { Some(name.clone()) } else { None }).collect();
let names = put_maps(s, &stem, &maps, &mut fill);
s.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill);
// Old maps go unless another layer (a duplicate) still shows them.
let mut used = Vec::new();
for set in 0..s.doc.project.texture_sets.len() {
for root in s.doc.project.texture_sets.get(set).map(|t| t.stack.clone()).unwrap_or_default() {
crate::material_lib::images_used(&s.doc.project, root, &mut used, 0);
let old_names: Vec<String> =
fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect();
let names = put_maps(session, &stem, &maps, &mut fill);
session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill);
// Duplicated layers may still use the earlier maps
let mut used_names = Vec::new();
for set in 0..session.doc.project.texture_sets.len() {
for root in session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.clone()).unwrap_or_default() {
crate::material_lib::images_used(&session.doc.project, root, &mut used_names, 0);
}
}
for name in old.iter().filter(|n| !used.contains(n)) {
s.doc.resources.remove(name);
for name in old_names.iter().filter(|name| !used_names.contains(name)) {
session.doc.resources.remove(name);
}
Ok(names)
})?;
self.sync_images();
// Reuse the validated maps before synchronization considers decoding missing images
self.cache_decoded(names, maps);
self.sync_images();
Ok(())
}
+20 -21
View File
@@ -38,7 +38,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
impl Session {
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS))
self.edit("Import resource", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS))
}
/// Add an image within a decoded texel budget, inside the caller's edit
@@ -47,39 +47,38 @@ impl Session {
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
}
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image");
let base = texturecraft_formats::sanitize_resource_name(leaf);
let mut name = base.clone();
let mut n = 2;
let mut duplicate_index = 2;
while self.doc.resources.contains_key(&name) {
name = format!("{n}_{base}");
n += 1;
name = format!("{duplicate_index}_{base}");
duplicate_index += 1;
}
self.doc.resources.insert(name.clone(), Arc::new(bytes));
self.images.insert(name.clone(), decoded(image));
Ok(name)
}
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
pub fn sync_images(&mut self) {
let keep: Vec<String> = self.doc.resources.keys().cloned().collect();
self.images.retain(|k, _| keep.contains(k));
// Linked materials' packages are resources too, not images.
let missing: Vec<(String, Arc<Vec<u8>>)> = self
.doc
.resources
.iter()
.filter(|(k, _)| !self.images.contains_key(*k) && !k.ends_with(&format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT)))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
for (k, bytes) in missing {
match texturecraft_formats::decode_image(&bytes) {
Ok(d) => {
self.images.insert(k, decoded(d));
self.images.retain(|name, _| self.doc.resources.contains_key(name));
// Linked material packages are resources but cannot be decoded as images
let package_suffix = format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT);
for (name, bytes) in &self.doc.resources {
if self.images.contains_key(name) || name.ends_with(&package_suffix) {
continue;
}
match texturecraft_formats::decode_image(bytes) {
Ok(image) => {
self.images.insert(name.clone(), decoded(image));
}
Err(e) => self.log.push(format!("resource {k}: {e}")),
Err(error) => self.log.push(format!("resource {name}: {error}")),
}
}
}
+45 -13
View File
@@ -571,23 +571,55 @@ impl Session {
self.invalidate_changed(other);
}
/// Mark dirty every texture set whose composite differs between `other` and the current
/// Mark dirty every texture set whose composite differs between the previous and current
/// document (after an edit, undo or redo).
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
self.follow_uv_layouts(&other.project);
pub(crate) fn invalidate_changed(&mut self, previous_document: &Document) {
self.follow_uv_layouts(&previous_document.project);
self.sync_caches();
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
let all = resources(other) != resources(&self.doc);
let (empty, images) = (BakedMaps::default(), Default::default());
let key = |d: &Document, ts: usize| {
let stack = d.project.texture_sets.get(ts).map(|s| s.stack.as_slice()).unwrap_or_default();
StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack)
// Removed or replaced resources may change any set's rendered content
let removed_or_replaced_resource =
previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current)));
let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect();
let uses_added_resource = |texture_set_index: usize| {
use texturecraft_core::{EffectKind, Fill, Source};
let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name));
let uses_fill =
|fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package));
let project = &self.doc.project;
!added_resource_names.is_empty()
&& project.texture_sets.get(texture_set_index).is_some_and(|set| {
project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| {
matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill))
|| layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind {
EffectKind::Fill { source, .. } => uses_source(source),
EffectKind::Material(fill) => uses_fill(fill),
_ => false,
})
})
})
};
for ts in 0..self.caches.len() {
if (all || key(other, ts) != key(&self.doc, ts))
&& let Some(c) = self.caches.get_mut(ts)
let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default());
let stack_key = |document: &Document, texture_set_index: usize| {
let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default();
StackKey::new(
&document.project,
&document.pixels,
document.baked.get(&texture_set_index).unwrap_or(&empty_baked_maps),
&empty_images,
texture_set_index,
stack,
)
};
for texture_set_index in 0..self.caches.len() {
if (removed_or_replaced_resource
|| stack_key(previous_document, texture_set_index) != stack_key(&self.doc, texture_set_index)
|| uses_added_resource(texture_set_index))
&& let Some(cache) = self.caches.get_mut(texture_set_index)
{
c.invalidate_all();
cache.invalidate_all();
}
}
}
+47 -1
View File
@@ -2,7 +2,7 @@
//! frame-budgeted compositor, through engine commands.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId, LayerKind};
use texturecraft_engine::core::{Channel, Fill, LayerId, LayerKind, Source};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
@@ -206,6 +206,52 @@ fn edits_invalidate_only_the_sets_they_change() {
assert!((rough(&mut s, 0) - 0.4).abs() < 1e-3);
}
#[test]
fn importing_images_invalidates_only_sets_with_newly_resolved_references() {
use std::sync::Arc;
let mut session = session();
let referenced_layer = session.doc.project.texture_sets[1].stack[0];
session
.edit("Reference missing image", |session| {
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::image("later.png"));
session.doc.project.layer_mut(referenced_layer).unwrap().kind = LayerKind::Fill(fill);
Ok(())
})
.unwrap();
session.update();
let mut image_bytes = Vec::new();
let image = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
image.write_to(&mut std::io::Cursor::new(&mut image_bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes("later.png", image_bytes.clone()).unwrap();
assert!(session.caches[0].dirty.is_empty(), "unrelated set stays clean");
assert!(!session.caches[1].dirty.is_empty(), "newly resolved image invalidates its set");
session.update();
let (x, y) = covered(&session, 1);
assert!(session.caches[1].composite.value(Channel::BaseColor, x, y)[0] > 0.9);
let imported_image = Arc::downgrade(&session.images["later.png"]);
session.undo().unwrap();
assert!(!session.caches[0].dirty.is_empty(), "resource removal retains broad invalidation");
assert!(!session.caches[1].dirty.is_empty());
assert!(imported_image.upgrade().is_none(), "undo releases the decoded image even while encoded bytes remain in history");
session.update();
session.redo().unwrap();
assert!(session.caches[0].dirty.is_empty());
assert!(!session.caches[1].dirty.is_empty());
assert!(!imported_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "redo decodes a new image allocation");
session.update();
session.import_resource_bytes("unused.png", image_bytes).unwrap();
assert!(session.caches.iter().all(|cache| cache.dirty.is_empty()), "unused image leaves every set clean");
let resolved_image = Arc::downgrade(&session.images["later.png"]);
session.sync_images();
assert!(resolved_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "sync reuses already decoded images");
}
#[test]
fn budgeted_updates_spread_work_and_end_identical() {
let mut s = session();
+39 -31
View File
@@ -108,47 +108,55 @@ fn imports_as_a_linked_fill_with_its_maps() {
/// An image marked DirectX keeps the mark when a re-cook replaces it.
#[test]
fn recooks_keep_the_normal_format_of_a_map() {
let mut s = session();
let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap();
s.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap();
let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("a fill") };
let mut session = session();
let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
execute(&mut session, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap();
session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap();
let LayerKind::Fill(fill) = &session.doc.project.layer(id).unwrap().kind else { panic!("a fill") };
assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { normal_format: NormalFormat::DirectX, .. })));
}
#[test]
fn parameters_are_checked_stored_and_recooked_in_one_undo_step() {
let mut s = session();
let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
let set = |s: &mut Session, p: Value| execute(s, "material.link.set", &p);
assert!(set(&mut s, json!({"id": "nope", "value": 1, "cook": false})).is_err());
assert!(set(&mut s, json!({"id": "wear", "value": "soft", "cook": false})).is_err());
assert!(set(&mut s, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err());
set(&mut s, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap();
assert_eq!(link(&s, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]}));
set(&mut s, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap();
assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.9}));
let mut session = session();
let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
let set = |session: &mut Session, params: Value| execute(session, "material.link.set", &params);
assert!(set(&mut session, json!({"id": "nope", "value": 1, "cook": false})).is_err());
assert!(set(&mut session, json!({"id": "wear", "value": "soft", "cook": false})).is_err());
assert!(set(&mut session, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err());
set(&mut session, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap();
assert_eq!(link(&session, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]}));
set(&mut session, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap();
assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.9}));
// Cooks follow the texture set resolution
let job = session.link_job(id, &serde_json::Map::new()).unwrap();
// The job carries every value and the texture set's resolution.
let job = s.link_job(id, &serde_json::Map::new()).unwrap();
assert_eq!(job.size, 128);
assert_eq!(job.values["wear"], json!({"t": "float", "v": 0.9}));
// What the job cooked (here: built by hand) replaces the maps, merged into the edit.
let old = map_name(&s, id, Channel::Roughness);
s.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap();
assert!((roughness(&mut s) - 0.75).abs() < 2e-3);
assert!(!s.doc.resources.contains_key(&old), "old maps are dropped");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!((roughness(&mut s) - 0.25).abs() < 2e-3, "undo restores the earlier maps");
assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.5}));
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert!((roughness(&mut s) - 0.75).abs() < 2e-3);
// Merge the cooked maps into the parameter edit
let old = map_name(&session, id, Channel::Roughness);
session.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap();
// Presets skip inputs the painter can't set; unknown presets are errors.
assert!(execute(&mut s, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err());
execute(&mut s, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap();
assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 1.0}));
assert!((roughness(&mut session) - 0.75).abs() < 2e-3);
assert!(!session.doc.resources.contains_key(&old), "old maps are dropped");
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert!((roughness(&mut session) - 0.25).abs() < 2e-3, "undo restores the earlier maps");
assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.5}));
execute(&mut session, "edit.redo", &Value::Null).unwrap();
assert!((roughness(&mut session) - 0.75).abs() < 2e-3);
// Presets skip unsupported inputs and reject unknown names
assert!(execute(&mut session, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err());
execute(&mut session, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap();
assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0}));
}
#[test]
+29 -15
View File
@@ -21,27 +21,31 @@ pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
/// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the
/// header, before any pixel is decoded or allocated.
pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result<DecodedImage> {
let mut reader =
image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?;
// TGA has no magic signature; its decoder validates the header when no format was recognized
let format = reader.format().unwrap_or(image::ImageFormat::Tga);
reader.set_format(format);
let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
let (width, height) = reader.into_dimensions().map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?;
if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE {
return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})")));
}
if u64::from(width) * u64::from(height) > max_texels {
return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels")));
}
let image =
crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?;
let image = crate::guard("image", || {
image::load_from_memory_with_format(bytes, format).map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })
})?;
let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_));
let float_image = image.into_rgba32f();
let (width, height) = float_image.dimensions();
let rgba = float_image.pixels().map(|pixel| pixel.0).collect();
Ok(DecodedImage { width, height, rgba, srgb })
}
@@ -63,15 +67,19 @@ mod tests {
#[test]
fn decodes_png_and_rejects_garbage() {
let mut png = Vec::new();
let img = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255]));
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let d = decode_image(&png).unwrap();
assert_eq!((d.width, d.height), (4, 2));
assert!(d.srgb);
assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3);
let image = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255]));
image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let decoded = decode_image(&png).unwrap();
assert_eq!((decoded.width, decoded.height), (4, 2));
assert!(decoded.srgb);
assert!((decoded.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3);
assert!(decode_image(b"not an image").is_err());
assert!(decode_image(&png[..png.len() / 2]).is_err());
let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap();
assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]);
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
}
@@ -80,11 +88,15 @@ mod tests {
fn tga_without_a_magic_signature_decodes_within_the_texel_budget() {
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap();
let image = decode_image_within(&bytes, 16).unwrap();
assert_eq!((image.width, image.height), (4, 4));
assert!((image.rgba[0][1] - 0.2).abs() < 1e-6);
assert!(image.srgb);
let header = &bytes[..18];
assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_))));
assert!(decode_image(header).is_err());
}
@@ -92,10 +104,11 @@ mod tests {
#[test]
fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() {
let png = {
let mut b = Vec::new();
image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap();
b
let mut bytes = Vec::new();
image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
bytes
};
assert_eq!(decode_image_within(&png, 64).unwrap().width, 8);
assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_))));
assert!(decode_image(&png).is_ok());
@@ -103,12 +116,13 @@ mod tests {
#[test]
fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() {
// An 18-byte TGA header: 16384² is inside the edge limit but far over 64 M texels.
// The edge limit permits 16384² but the default resource budget does not
let mut header = [0u8; 18];
header[2] = 2;
header[12..14].copy_from_slice(&16_384u16.to_le_bytes());
header[14..16].copy_from_slice(&16_384u16.to_le_bytes());
header[16] = 24;
assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_))));
}
}
+31 -20
View File
@@ -116,15 +116,20 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result<Vec<u8>> {
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> {
let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("out");
for attempt in 0..100u32 {
let tmp = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id()));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) {
Ok(file) => return Ok((tmp, file)),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e.into()),
let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out");
// Bound retries when stale files or concurrent writers occupy candidate names
const MAX_TEMP_ATTEMPTS: u32 = 100;
for attempt in 0..MAX_TEMP_ATTEMPTS {
let temporary_path = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id()));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&temporary_path) {
Ok(file) => return Ok((temporary_path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error.into()),
}
}
Err(FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not create a temporary file")))
}
@@ -132,14 +137,17 @@ pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf,
#[cfg(not(target_arch = "wasm32"))]
pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
let (tmp, mut file) = create_temp(path)?;
let res = file.write_all(bytes).and_then(|_| file.sync_all());
let (temporary_path, mut file) = create_temp(path)?;
let result = file.write_all(bytes).and_then(|_| file.sync_all());
drop(file);
let res = res.and_then(|_| std::fs::rename(&tmp, path));
if res.is_err() {
let _ = std::fs::remove_file(&tmp);
let result = result.and_then(|_| std::fs::rename(&temporary_path, path));
if result.is_err() {
let _ = std::fs::remove_file(&temporary_path);
}
Ok(res?)
Ok(result?)
}
#[cfg(all(test, unix))]
@@ -148,17 +156,20 @@ mod atomic_tests {
#[test]
fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir)?;
let target = dir.join("out.png");
let victim = dir.join("victim.txt");
let directory = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory)?;
let target = directory.join("out.png");
let victim = directory.join("victim.txt");
std::fs::write(&victim, b"safe")?;
std::os::unix::fs::symlink(&victim, dir.join("out.png.tmp"))?;
std::os::unix::fs::symlink(&victim, directory.join("out.png.tmp"))?;
write_atomic(&target, b"new").map_err(std::io::Error::other)?;
assert_eq!(std::fs::read(&victim)?, b"safe");
assert_eq!(std::fs::read(&target)?, b"new");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&directory);
Ok(())
}
}
+81 -33
View File
@@ -70,35 +70,53 @@ fn malformed(msg: impl Into<String>) -> FormatError {
FormatError::Malformed { kind: KIND, msg: msg.into() }
}
fn read_entry(name: &str, entry: impl Read, total_bytes: &mut u64) -> Result<Vec<u8>> {
// Earlier maps remain live while the next entry is read
let remaining_bytes = MAX_TOTAL.saturating_sub(*total_bytes);
let entry_limit = MAX_ENTRY.min(remaining_bytes);
let mut bytes = Vec::new();
entry.take(entry_limit + 1).read_to_end(&mut bytes).map_err(|error| malformed(format!("{name}: {error}")))?;
if bytes.len() as u64 > MAX_ENTRY {
return Err(FormatError::TooLarge(name.to_string()));
}
let next_total = total_bytes.saturating_add(bytes.len() as u64);
if next_total > MAX_TOTAL {
return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)")));
}
// Keep spare read capacity from accumulating across retained map entries
bytes.shrink_to_fit();
*total_bytes = next_total;
Ok(bytes)
}
/// Read `.mcmat` bytes.
pub fn read_mcmat(bytes: &[u8]) -> Result<PortableMaterial> {
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?;
let mut total = 0u64;
let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|error| malformed(error.to_string()))?;
let mut total_bytes = 0u64;
let mut read = |name: &str| -> Result<Vec<u8>> {
let mut out = Vec::new();
let f = z.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?;
f.take(MAX_ENTRY + 1).read_to_end(&mut out).map_err(|e| malformed(format!("{name}: {e}")))?;
if out.len() as u64 > MAX_ENTRY {
return Err(FormatError::TooLarge(name.to_string()));
}
total = total.saturating_add(out.len() as u64);
if total > MAX_TOTAL {
return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)")));
}
Ok(out)
let entry = archive.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?;
read_entry(name, entry, &mut total_bytes)
};
let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|e| malformed(format!("material.json: {e}")))?;
let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|error| malformed(format!("material.json: {error}")))?;
if manifest.format != FORMAT {
return Err(malformed(format!("format `{}`", manifest.format)));
}
if manifest.version > VERSION {
return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version)));
}
if manifest.maps.len() > MAX_MAPS {
return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len())));
}
let maps = manifest.maps.iter().map(|m| Ok((m.usage.clone(), read(&m.file)?))).collect::<Result<Vec<_>>>()?;
let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), read(&map.file)?))).collect::<Result<Vec<_>>>()?;
let source = read(&manifest.source)?;
Ok(PortableMaterial { manifest, maps, source })
}
@@ -165,16 +183,18 @@ mod tests {
#[test]
fn reads_manifest_maps_and_source() {
let bytes = sample(1);
assert!(is_mcmat(&bytes) && !is_mcraft(&bytes));
let m = read_mcmat(&bytes).unwrap();
assert_eq!(m.manifest.graph, "Brick_wall");
assert_eq!(m.manifest.parameters[0].id, "wear");
assert_eq!(m.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25}));
assert_eq!(m.manifest.presets[0].name, "Worn");
assert_eq!(m.manifest.inputs[0].identifier, "curvature");
assert_eq!(m.maps[0].0, "baseColor");
assert_eq!(crate::decode_image(&m.maps[0].1).unwrap().width, 4);
assert_eq!(m.source, b"pkg");
let material = read_mcmat(&bytes).unwrap();
assert_eq!(material.manifest.graph, "Brick_wall");
assert_eq!(material.manifest.parameters[0].id, "wear");
assert_eq!(material.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25}));
assert_eq!(material.manifest.presets[0].name, "Worn");
assert_eq!(material.manifest.inputs[0].identifier, "curvature");
assert_eq!(material.maps[0].0, "baseColor");
assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4);
assert_eq!(material.source, b"pkg");
assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_))));
assert!(read_mcmat(b"junk").is_err());
}
@@ -184,15 +204,43 @@ mod tests {
let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect();
let manifest =
serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"});
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let o = zip::write::SimpleFileOptions::default();
z.start_file("material.json", o).unwrap();
z.write_all(manifest.to_string().as_bytes()).unwrap();
z.start_file("maps/baseColor.png", o).unwrap();
z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap();
z.start_file("source.mcraft", o).unwrap();
z.write_all(b"pkg").unwrap();
assert!(read_mcmat(&z.finish().unwrap().into_inner()).is_err());
let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
archive.start_file("material.json", options).unwrap();
archive.write_all(manifest.to_string().as_bytes()).unwrap();
archive.start_file("maps/baseColor.png", options).unwrap();
archive.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap();
archive.start_file("source.mcraft", options).unwrap();
archive.write_all(b"pkg").unwrap();
let result = read_mcmat(&archive.finish().unwrap().into_inner());
assert!(matches!(result, Err(FormatError::Malformed { .. })));
}
#[test]
fn entry_read_stops_at_the_remaining_payload_budget() {
let payload = vec![7u8; 1024];
let mut input = Cursor::new(&payload);
let mut total_bytes = MAX_TOTAL - 8;
let result = read_entry("maps/extra.png", &mut input, &mut total_bytes);
assert!(matches!(result, Err(FormatError::TooLarge(_))));
assert_eq!(input.position(), 9, "only one byte beyond the remaining budget is needed to reject the entry");
assert_eq!(total_bytes, MAX_TOTAL - 8, "a rejected entry does not consume the payload budget");
}
#[test]
fn payload_budget_accepts_the_exact_limit_and_empty_entries() {
let mut total_bytes = MAX_TOTAL - 4;
let bytes = read_entry("map.png", Cursor::new([1, 2, 3, 4]), &mut total_bytes).unwrap();
assert_eq!(bytes, [1, 2, 3, 4]);
assert_eq!(total_bytes, MAX_TOTAL);
assert!(read_entry("empty.mcraft", Cursor::new([]), &mut total_bytes).unwrap().is_empty());
assert!(matches!(read_entry("extra.png", Cursor::new([1]), &mut total_bytes), Err(FormatError::TooLarge(_))));
}
#[test]
+42 -36
View File
@@ -245,62 +245,68 @@ impl<'a> Crate<'a> {
/// Paths are stored as a pre-order tree: element token (negative for properties) and a
/// jump per node (-2 leaf, -1 child only, 0 sibling only, >0 child and sibling at +jump).
fn read_paths(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> {
let total = s.count(0)?;
let n = s.count(0)?;
let index = s.ints(n, 4, budget)?;
let elements = s.ints(n, 4, budget)?;
let jumps = s.ints(n, 4, budget)?;
if total > MAX_PATHS {
return Err(FormatError::TooLarge(format!("the USD path table has {total} entries (limit {MAX_PATHS})")));
fn read_paths(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> {
let path_count = section.count(0)?;
let encoded_count = section.count(0)?;
let path_indices = section.ints(encoded_count, 4, budget)?;
let elements = section.ints(encoded_count, 4, budget)?;
let jumps = section.ints(encoded_count, 4, budget)?;
if path_count > MAX_PATHS {
return Err(FormatError::TooLarge(format!("the USD path table has {path_count} entries (limit {MAX_PATHS})")));
}
// Charge what the vector really allocates, not a guessed 64 bytes per entry.
budget.take(total.saturating_mul(std::mem::size_of::<Option<PathEl>>()))?;
self.paths = vec![None; total];
let mut work: Vec<(usize, Option<usize>)> = vec![(0, None)];
let mut steps = 0usize;
let bad = || malformed(KIND, "corrupt path table");
while let Some((mut i, mut parent)) = work.pop() {
// Account for the actual path slot allocation
budget.take(path_count.saturating_mul(std::mem::size_of::<Option<PathEl>>()))?;
self.paths = vec![None; path_count];
let mut pending_branches: Vec<(usize, Option<usize>)> = vec![(0, None)];
let mut visited_count = 0usize;
let path_error = || malformed(KIND, "corrupt path table");
while let Some((mut cursor_index, mut parent)) = pending_branches.pop() {
loop {
steps += 1;
if steps > n {
return Err(bad());
visited_count += 1;
if visited_count > encoded_count {
return Err(path_error());
}
let this = i;
i += 1;
let at = index.get(this).map(|v| *v as u32 as usize).filter(|p| *p < total).ok_or_else(bad)?;
let el = match parent {
let node_index = cursor_index;
cursor_index += 1;
let path_index =
path_indices.get(node_index).map(|v| *v as u32 as usize).filter(|parent_index| *parent_index < path_count).ok_or_else(path_error)?;
let path_element = match parent {
None => PathEl { text: "/".into(), parent: None, name: String::new(), prop: false },
Some(p) => {
let e = *elements.get(this).ok_or_else(bad)?;
let name = self.token(e.unsigned_abs())?.to_string();
let base = self.paths.get(p).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(bad)?;
let text = match (e < 0, base) {
(true, _) => format!("{base}.{name}"),
(false, _) if name.starts_with('{') => format!("{base}{name}"),
Some(parent_index) => {
let element_token = *elements.get(node_index).ok_or_else(path_error)?;
let name = self.token(element_token.unsigned_abs())?.to_string();
let parent_path = self.paths.get(parent_index).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(path_error)?;
let text = match (element_token < 0, parent_path) {
(true, _) => format!("{parent_path}.{name}"),
(false, _) if name.starts_with('{') => format!("{parent_path}{name}"),
(false, "/") => format!("/{name}"),
(false, _) => format!("{base}/{name}"),
(false, _) => format!("{parent_path}/{name}"),
};
budget.take(text.len())?;
PathEl { text, parent: Some(p), name, prop: e < 0 }
PathEl { text, parent: Some(parent_index), name, prop: element_token < 0 }
}
};
if let Some(slot) = self.paths.get_mut(at) {
*slot = Some(el);
if let Some(slot) = self.paths.get_mut(path_index) {
*slot = Some(path_element);
}
let jump = *jumps.get(this).ok_or_else(bad)?;
let jump = *jumps.get(node_index).ok_or_else(path_error)?;
let (child, sibling) = (jump > 0 || jump == -1, jump >= 0);
if child {
if sibling {
work.push((this.checked_add(usize::try_from(jump).map_err(|_| bad())?).ok_or_else(bad)?, parent));
pending_branches.push((node_index.checked_add(usize::try_from(jump).map_err(|_| path_error())?).ok_or_else(path_error)?, parent));
}
parent = Some(at);
parent = Some(path_index);
}
if !child && !sibling {
break;
}
}
}
Ok(())
}
+12 -10
View File
@@ -98,21 +98,23 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result<Vec<u8>> {
Ok(out.into_inner())
}
/// Save atomically: `<path>.tmp` first, then rename over `path`.
/// Save atomically through a newly created temporary file beside `path`.
#[cfg(not(target_arch = "wasm32"))]
pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> {
let (tmp, file) = crate::create_temp(path)?;
let res = (|| -> Result<()> {
pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Result<()> {
let (temporary_path, file) = crate::create_temp(path)?;
let result = (|| -> Result<()> {
let mut file = std::io::BufWriter::new(file);
write_project(&mut file, pf)?;
file.into_inner().map_err(|e| e.into_error())?.sync_all()?;
std::fs::rename(&tmp, path)?;
write_project(&mut file, project_file)?;
file.into_inner().map_err(|error| error.into_error())?.sync_all()?;
std::fs::rename(&temporary_path, path)?;
Ok(())
})();
if res.is_err() {
let _ = std::fs::remove_file(&tmp);
if result.is_err() {
let _ = std::fs::remove_file(&temporary_path);
}
res
result
}
fn zip_err(e: zip::result::ZipError) -> FormatError {