PhotoCraft: An open-source, photo editor written by scratch in pure Rust
document.pixel: no panic at i32::MAX, reject coordinates beyond i32 (#629)
Armaan Sandhu0aabb486872d
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex c69436b47..9d0f229cc 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -824,10 +824,11 @@ fn build() -> Vec<CommandSpec> {params: r##"{"x":i32,"y":i32}"##,enabled: has_doc,run: |s, p| {- let x = int(p, "x").unwrap_or(0) as i32;- let y = int(p, "y").unwrap_or(0) as i32;+ let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits")));+ let (x, y) = (coord("x")?, coord("y")?);let d = s.active().ok_or(EngineError::NoDocument)?;- let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px[0];+ // At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent.+ let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px.first().copied().unwrap_or_default();Ok(json!(px))},journal: false,diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex cd5ec3872..9b3c7f4cb 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -11,6 +11,17 @@ fn px(s: &mut Session, x: i32, y: i32) -> Vec<f32> {serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap()}+#[test]+fn document_pixel_at_the_coordinate_limits() {+ let mut s = session_with_doc();+ // The last representable column used to panic (its 1x1 rect saturated to empty).+ assert_eq!(px(&mut s, i32::MAX, 0), vec![0.0; 4]);+ assert_eq!(px(&mut s, i32::MIN, i32::MAX), vec![0.0; 4]);+ // Values beyond i32 used to wrap around onto the canvas (2^32 read column 0).+ let e = s.execute("document.pixel", json!({"x": 1i64 << 32, "y": 0})).unwrap_err();+ assert!(matches!(e, EngineError::BadParams { .. }), "{e}");+}+#[test]fn command_ids_are_unique_and_documented() {let mut seen = std::collections::HashSet::new();