From 7491c7144b3af85bb6babc7a0456081d7b9ff401 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 21:54:12 +0000 Subject: [PATCH] [124] Kern: JSON-Hilfen aus grips nach json_util field/num_of/num_or/truthy/js_num/pt/xy/with*/arr und die Anfrage-Zahl N stehen jetzt in json_util.rs; alle Aufrufer importieren von dort (kein Re-Export aus grips). --- src-tauri/core/src/cmd_create.rs | 2 +- src-tauri/core/src/cmd_draw.rs | 8 +- src-tauri/core/src/cmd_edit.rs | 2 +- src-tauri/core/src/cmd_paste.rs | 2 +- src-tauri/core/src/cmd_solid.rs | 4 +- src-tauri/core/src/cmd_split.rs | 2 +- src-tauri/core/src/cmd_transform.rs | 4 +- src-tauri/core/src/cmd_wall_edit.rs | 2 +- src-tauri/core/src/dim_assoc.rs | 2 +- src-tauri/core/src/geo_translate.rs | 2 +- src-tauri/core/src/grips.rs | 165 +------------------------- src-tauri/core/src/import_context.rs | 4 +- src-tauri/core/src/import_drawing.rs | 2 +- src-tauri/core/src/import_ifc.rs | 6 +- src-tauri/core/src/json_util.rs | 171 +++++++++++++++++++++++++++ src-tauri/core/src/layers.rs | 2 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/pens.rs | 2 +- src-tauri/core/src/selection_info.rs | 4 +- 19 files changed, 198 insertions(+), 189 deletions(-) create mode 100644 src-tauri/core/src/json_util.rs diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index a4c38a94..accad8e3 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -16,7 +16,7 @@ //! Elemente mit der Schlüsselreihenfolge der früheren Objekt-Literale. use crate::cmd_transform::{IdGen, Shapes}; -use crate::grips::{arr, field, js_num, num_of, pt, truthy, xy}; +use crate::json_util::{arr, field, js_num, num_of, pt, truthy, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index 5fb29a7c..08ff03ce 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -9,7 +9,7 @@ use crate::cmd_create::{ pts_of, pv, pvs, s, s_of, seg_len, to_p, type_thickness, wall_types, Ctx, Preview, V, EPS, }; use crate::cmd_transform::{IdGen, Shapes}; -use crate::grips::{arr, field, js_num, num_of, num_or, with, xy}; +use crate::json_util::{arr, field, js_num, num_of, num_or, with, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; @@ -373,7 +373,7 @@ fn straight_edges(g: &Value) -> Vec<(V, V)> { Some("polyline") => { let pts: Vec = arr(field(g, "pts")).iter().map(xy).collect(); let bulge = arr(field(g, "bulge")); - polyline_edges(&pts, crate::grips::truthy(field(g, "closed"))) + polyline_edges(&pts, crate::json_util::truthy(field(g, "closed"))) .into_iter() .enumerate() .filter(|(i, _)| num_or(bulge.get(*i), 0.0).abs() <= EPS) @@ -1182,11 +1182,11 @@ fn auto_dims(root: &Map, ctx: &Ctx, prefix: &str, scale: f64) -> Some((_, wi)) => format!("{prefix}-{}-arc-{}", ctx.level, id_of(walls[wi]).unwrap_or("")), None => format!("{prefix}-{}-{}-{}", ctx.level, SIDES[c.side as usize], CHAINS[c.chain as usize]), }; - let pts = Value::Array(c.pts.iter().map(|q| crate::grips::pt(q[0], q[1])).collect()); + let pts = Value::Array(c.pts.iter().map(|q| crate::json_util::pt(q[0], q[1])).collect()); let mut fields = vec![("shape", s("dimension")), ("pts", pts), ("offset", js_num(c.offset))]; // Bogenmass ([T2]): Kette auf dem Kreis um die Bogenmitte. if let Some((ctr, _)) = c.arc { - fields.push(("arcCenter", crate::grips::pt(ctr[0], ctr[1]))); + fields.push(("arcCenter", crate::json_util::pt(ctr[0], ctr[1]))); } // Assoziativ ([38]): je Punkt das Merkmal (Ecke, Leibung), aus dem er stammt. let chain: Vec = c.pts.iter().map(|q| (q[0], q[1])).collect(); diff --git a/src-tauri/core/src/cmd_edit.rs b/src-tauri/core/src/cmd_edit.rs index 51ab7113..a38dc770 100644 --- a/src-tauri/core/src/cmd_edit.rs +++ b/src-tauri/core/src/cmd_edit.rs @@ -13,7 +13,7 @@ use crate::cmd_transform::{IdGen, Shapes}; use crate::cmd_wall_edit as wall_edit; -use crate::grips::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, xy}; +use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; diff --git a/src-tauri/core/src/cmd_paste.rs b/src-tauri/core/src/cmd_paste.rs index a18830e0..08ba7ac8 100644 --- a/src-tauri/core/src/cmd_paste.rs +++ b/src-tauri/core/src/cmd_paste.rs @@ -12,7 +12,7 @@ //! fehlende kommen ans Ende, unbekannte Felder bleiben). use crate::cmd_transform::IdGen; -use crate::grips::{arr, field, with_all}; +use crate::json_util::{arr, field, with_all}; use crate::ops::{id_of, Op}; use serde_json::Value; use std::collections::HashMap; diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs index faacd381..201e07c3 100644 --- a/src-tauri/core/src/cmd_solid.rs +++ b/src-tauri/core/src/cmd_solid.rs @@ -7,7 +7,7 @@ use crate::cmd_create::{add_op, circle_pts, find, n_of, obj, opt_p, p_of, pts_of, pv, pvs, rect_corners, s, s_of, Ctx, Preview, V}; use crate::cmd_transform::{IdGen, Shapes}; -use crate::grips::{arr, field, js_num, num_of, num_or, truthy, with, xy}; +use crate::json_util::{arr, field, js_num, num_of, num_or, truthy, with, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; @@ -726,7 +726,7 @@ fn sectionline_ops(root: &Map, v: &Value, ids: &mut IdGen) -> Vec None | Some(Value::Null) => js_num(1.0), Some(x) => x.clone(), }; - return vec![Op::Replace { collection: "drawingLevels".into(), entity: crate::grips::with_all(z, vec![("linePoints", line), ("directionSign", sign)]) }]; + return vec![Op::Replace { collection: "drawingLevels".into(), entity: crate::json_util::with_all(z, vec![("linePoints", line), ("directionSign", sign)]) }]; } let name = s_of(v, "name").replace('\u{1}', &level_letters(of_kind.len())); add_op( diff --git a/src-tauri/core/src/cmd_split.rs b/src-tauri/core/src/cmd_split.rs index 9aa6041f..6b87f1a1 100644 --- a/src-tauri/core/src/cmd_split.rs +++ b/src-tauri/core/src/cmd_split.rs @@ -18,7 +18,7 @@ //! vorher über die Bindungen). use crate::cmd_transform::IdGen; -use crate::grips::{arr, field, js_num, num_of, pt, truthy, with_opt, xy}; +use crate::json_util::{arr, field, js_num, num_of, pt, truthy, with_opt, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; diff --git a/src-tauri/core/src/cmd_transform.rs b/src-tauri/core/src/cmd_transform.rs index 69a8c500..5198ae6c 100644 --- a/src-tauri/core/src/cmd_transform.rs +++ b/src-tauri/core/src/cmd_transform.rs @@ -10,9 +10,9 @@ //! dasselbe wie `a·x + b·y + e`). //! //! Rechnung auf der rohen Projekt-Wurzel (verlustfrei, Schlüsselreihenfolge wie das Objekt-Spreizen in -//! TS); Zahlen wie in JS (`jsnum`, `jsmath`), nicht endliche Ergebnisse als Marken (`grips::js_num`). +//! TS); Zahlen wie in JS (`jsnum`, `jsmath`), nicht endliche Ergebnisse als Marken (`json_util::js_num`). -use crate::grips::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N}; +use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::{id_of, Op}; diff --git a/src-tauri/core/src/cmd_wall_edit.rs b/src-tauri/core/src/cmd_wall_edit.rs index e73e5ad3..bd8119c9 100644 --- a/src-tauri/core/src/cmd_wall_edit.rs +++ b/src-tauri/core/src/cmd_wall_edit.rs @@ -21,7 +21,7 @@ //! Geschosses, 2D-Linien/-Polylinien (mit Bögen)/-Rechtecke/-Kreise/-Bögen und Achsraster der Ebene. use crate::cmd_transform::{IdGen, Shapes}; -use crate::grips::{arr, field, js_num, num_of, pt, truthy, with, with_all, xy}; +use crate::json_util::{arr, field, js_num, num_of, pt, truthy, with, with_all, xy}; use crate::joins::Line; use crate::model::{DimFeature, DimRef}; use crate::ops::{id_of, Op}; diff --git a/src-tauri/core/src/dim_assoc.rs b/src-tauri/core/src/dim_assoc.rs index 09387535..bb65bbaa 100644 --- a/src-tauri/core/src/dim_assoc.rs +++ b/src-tauri/core/src/dim_assoc.rs @@ -657,7 +657,7 @@ fn refs_of(g: &Value) -> Option>> { } fn pv(p: P) -> Value { - crate::grips::pt(p.0, p.1) + crate::json_util::pt(p.0, p.1) } fn with(v: &Value, key: &str, x: Value) -> Value { diff --git a/src-tauri/core/src/geo_translate.rs b/src-tauri/core/src/geo_translate.rs index 05d8ef9c..68866d77 100644 --- a/src-tauri/core/src/geo_translate.rs +++ b/src-tauri/core/src/geo_translate.rs @@ -20,7 +20,7 @@ fn shift_all(v: Option<&Value>, dx: f64, dy: f64) -> Value { Value::Array(v.and_then(Value::as_array).map(|a| a.iter().map(|p| shift(p, dx, dy)).collect()).unwrap_or_default()) } -use crate::grips::truthy; +use crate::json_util::truthy; /// `{...m, key: v}` — ein vorhandener Schlüssel behält seine Stelle; `None` = `undefined` (Feld entfällt). fn set(m: &mut Map, key: &str, v: Option) { diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 5f7825ec..e2b11ac6 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -17,132 +17,14 @@ pub use crate::document::Lookup; use crate::jsmath::hypot2; use crate::jsnum; +use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N}; use crate::ops::{id_of, Op}; use serde_json::{Map, Value}; -// ── JS-Zahlen in JSON ──────────────────────────────────────────────────────── - -/// Feld `k` eines Objekts. Kleine Objekte (Punkte, Elemente) werden linear durchsucht: das ist deutlich -/// billiger als der Hash (SipHash) der `IndexMap` je Zugriff — die Griff- und Objekt-Info-Rechnung liest -/// Dutzende Felder je Aufruf. -#[inline] -pub fn field<'a>(v: &'a Value, k: &str) -> Option<&'a Value> { - match v { - Value::Object(m) if m.len() <= 32 => m.iter().find(|(kk, _)| kk.as_str() == k).map(|(_, x)| x), - Value::Object(m) => m.get(k), - _ => None, - } -} - -/// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64; -/// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0. -pub fn js_num(x: f64) -> Value { - if x.is_nan() { - return Value::String("\u{1}NaN".into()); - } - if x.is_infinite() { - return Value::String(if x > 0.0 { "\u{1}Infinity" } else { "\u{1}-Infinity" }.into()); - } - if x.fract() == 0.0 { - if (0.0..18446744073709551616.0).contains(&x) { - return Value::from(x as u64); - } - if x < 0.0 && x >= -9223372036854775808.0 { - return Value::from(x as i64); - } - } - Value::from(x) -} - -/// Zahl eines JSON-Werts wie in JS-Arithmetik auf der Leseansicht: Zahl, Nicht-endlich-Marke, `null` = 0 -/// (so rechnet JS mit `null`; das Dokument speichert ein tief liegendes NaN als `null`, eine geladene -/// Datei liest es so zurück); fehlend und alles andere NaN. -pub fn num_of(v: Option<&Value>) -> f64 { - match v { - Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN), - Some(Value::Null) => 0.0, - Some(m) => match crate::ops::non_finite_mark(m) { - Some("Infinity") => f64::INFINITY, - Some("-Infinity") => f64::NEG_INFINITY, - _ => f64::NAN, - }, - None => f64::NAN, - } -} - -/// `a ?? b` für Zahlen (fehlend/`null` → `b`). -pub(crate) fn num_or(v: Option<&Value>, b: f64) -> f64 { - match v { - None | Some(Value::Null) => b, - v => num_of(v), - } -} - -/// JS-Wahrheitswert. -pub fn truthy(v: Option<&Value>) -> bool { - match v { - None | Some(Value::Null) => false, - Some(Value::Bool(b)) => *b, - Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()), - Some(Value::String(s)) => !s.is_empty(), - Some(_) => true, - } -} - fn nullish(v: Option<&Value>) -> bool { matches!(v, None | Some(Value::Null)) } -/// Punkt `{x, y}` (wie ein neues Objekt-Literal in TS). -pub fn pt(x: f64, y: f64) -> Value { - let mut m = Map::new(); - m.insert("x".into(), js_num(x)); - m.insert("y".into(), js_num(y)); - Value::Object(m) -} - -/// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN). -pub fn xy(v: &Value) -> (f64, f64) { - (num_of(field(v, "x")), num_of(field(v, "y"))) -} - -/// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert -/// (eine grosse Polylinie kostet sonst je Mausschritt eine Kopie mehr). -pub(crate) fn with(v: &Value, key: &str, val: Value) -> Value { - with_all(v, vec![(key, val)]) -} - -/// Wie [`with`] für mehrere Felder in einem Durchgang (`{...v, a, b}`). -pub(crate) fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value { - with_opt(v, fields.into_iter().map(|(k, x)| (k, Some(x))).collect()) -} - -/// Wie [`with_all`]; `None` = `undefined` (das Feld fällt weg, wie in JSON). -pub(crate) fn with_opt(v: &Value, fields: Vec<(&str, Option)>) -> Value { - let mut fields: Vec<(&str, Option, bool)> = fields.into_iter().map(|(k, x)| (k, x, false)).collect(); - let src = v.as_object(); - let mut m = Map::with_capacity(src.map_or(0, Map::len) + fields.len()); - for (k, x) in src.into_iter().flatten() { - match fields.iter_mut().find(|(f, _, _)| *f == k) { - Some((_, new, done)) => { - *done = true; - if let Some(n) = new.take() { - m.insert(k.clone(), n); - } - } - None => { - m.insert(k.clone(), x.clone()); - } - } - } - for (k, x, done) in fields { - if let (false, Some(x)) = (done, x) { - m.insert(k.into(), x); - } - } - Value::Object(m) -} - /// Zahl, die TS teils unverändert durchreicht (`ry: g.ry`): Wert für die Rechnung und JSON-Wert /// (`None` = fehlend/`undefined`; ein `null` bleibt `null`). #[derive(Clone)] @@ -161,10 +43,6 @@ fn calc(f: f64) -> Pass { Pass { f, v: Some(js_num(f)) } } -pub fn arr(v: Option<&Value>) -> &[Value] { - v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) -} - /// Ganzzahliger Index in `0..len` (JS: `list[i]` trifft nur dann ein Element). fn index_in(i: f64, len: usize) -> Option { (i.fract() == 0.0 && i >= 0.0 && i < len as f64).then_some(i as usize) @@ -209,47 +87,6 @@ fn with_geom(d: &Value, g: Value) -> Value { // ── Anfrage ────────────────────────────────────────────────────────────────── -/// Zahl der Anfrage: Zahl oder Nicht-endlich-Marke, `null` = 0 (wie `num_of`), fehlend = NaN. -#[derive(Clone, Copy, Debug)] -pub struct N(pub f64); - -impl Default for N { - fn default() -> Self { - N(f64::NAN) - } -} - -impl<'de> serde::Deserialize<'de> for N { - fn deserialize>(d: D) -> Result { - struct V; - impl serde::de::Visitor<'_> for V { - type Value = N; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("Zahl") - } - fn visit_f64(self, v: f64) -> Result { - Ok(N(v)) - } - fn visit_i64(self, v: i64) -> Result { - Ok(N(v as f64)) - } - fn visit_u64(self, v: u64) -> Result { - Ok(N(v as f64)) - } - fn visit_str(self, v: &str) -> Result { - Ok(N(num_of(Some(&Value::String(v.to_owned()))))) - } - fn visit_unit(self) -> Result { - Ok(N(0.0)) - } - fn visit_bool(self, _: bool) -> Result { - Ok(N(f64::NAN)) - } - } - d.deserialize_any(V) - } -} - /// Eine Änderung aus den Griff-Aktionen des Stores (`GripRequest` in `geometry/grips.ts`); Zahlen dürfen /// Nicht-endlich-Marken sein. Typisiert gelesen (je Mausschritt billiger als ein JSON-Baum). #[derive(serde::Deserialize, Default, Debug)] diff --git a/src-tauri/core/src/import_context.rs b/src-tauri/core/src/import_context.rs index 2fea29db..7f96e9b3 100644 --- a/src-tauri/core/src/import_context.rs +++ b/src-tauri/core/src/import_context.rs @@ -7,7 +7,7 @@ //! Positionen/Indizes; `fileio/src/mesh_import.rs`: Zahlenpuffer + Strings). Zahlen wie in der TS-Fassung //! (`Math.hypot`, `Math.round`), ids aus Zeit (Basis 36) + Zähler. -use crate::grips::js_num; +use crate::json_util::js_num; use crate::import_drawing::{next_seq, GENERIC_IMPORT_CODE}; use crate::jsmath; use crate::jsnum; @@ -195,7 +195,7 @@ fn group_by(items: &[T], key: impl Fn(&T) -> String) -> Vec> { /// LV95-Ursprung des Projekts (`projectGeoOrigin`: `geoAnchor.lv95 − geoAnchor.model`), ohne Bezug `None`. pub fn project_geo_origin(root: &Map) -> Option<[f64; 2]> { - let a = root.get("geoAnchor").filter(|a| crate::grips::truthy(Some(a)))?; + let a = root.get("geoAnchor").filter(|a| crate::json_util::truthy(Some(a)))?; let n = |p: &str, k: &str| a.get(p).and_then(|o| o.get(k)).and_then(Value::as_f64).unwrap_or(f64::NAN); Some([n("lv95", "e") - n("model", "x"), n("lv95", "n") - n("model", "y")]) } diff --git a/src-tauri/core/src/import_drawing.rs b/src-tauri/core/src/import_drawing.rs index 655329da..f6b22b7b 100644 --- a/src-tauri/core/src/import_drawing.rs +++ b/src-tauri/core/src/import_drawing.rs @@ -14,7 +14,7 @@ //! Zahlen und Texte wie in der TS-Fassung (`Math.round`, `toFixed`, `String(n)`, ids aus Zeit + Zähler), //! Schlüsselreihenfolge der erzeugten Objekte wie die früheren Objekt-Literale. -use crate::grips::js_num; +use crate::json_util::js_num; use crate::js_fmt::{js_number, to_fixed}; use crate::jsnum; use crate::ops::Op; diff --git a/src-tauri/core/src/import_ifc.rs b/src-tauri/core/src/import_ifc.rs index d66f3925..b9dd2d7e 100644 --- a/src-tauri/core/src/import_ifc.rs +++ b/src-tauri/core/src/import_ifc.rs @@ -8,7 +8,7 @@ //! Deckentypen nach Schichten (Material + Dicke, ±0.5 mm), Materialien nach Namen; Zahlen auf 1e-9 m bzw. //! 1e-6 gerundet (`Math.round(x / step) * step`). -use crate::grips::js_num; +use crate::json_util::js_num; use crate::import_context::{color_hex, color_of, context_ops, geo_shift, ifc_meshes, project_geo_origin, stamp36, IfcProduct}; use crate::import_drawing::next_seq; use crate::js_fmt::js_number; @@ -715,14 +715,14 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element ops.extend(grown_list_ops("drawingLevels", root.get("drawingLevels"), std::mem::take(&mut ctx.levels))); ops.extend(grown_list_ops("components", root.get("components"), std::mem::take(&mut ctx.components))); ops.extend(grown_list_ops("wallTypes", root.get("wallTypes"), wall_types)); - if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::grips::truthy(Some(v))) { + if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::json_util::truthy(Some(v))) { ops.extend(grown_list_ops("ceilingTypes", root.get("ceilingTypes"), ceiling_types)); } if !walls.is_empty() { ops.push(Op::Add { collection: "walls".into(), items: walls, at: None }); } for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms)] { - if root.get(key).is_some_and(|v| crate::grips::truthy(Some(v))) { + if root.get(key).is_some_and(|v| crate::json_util::truthy(Some(v))) { if !items.is_empty() { ops.push(Op::Add { collection: key.into(), items, at: None }); } diff --git a/src-tauri/core/src/json_util.rs b/src-tauri/core/src/json_util.rs new file mode 100644 index 00000000..726f4128 --- /dev/null +++ b/src-tauri/core/src/json_util.rs @@ -0,0 +1,171 @@ +//! Lese- und Bau-Hilfen für den rohen JSON-Baum des Projekts ([124], vorher in `grips.rs`): Felder +//! lesen, Zahlen wie JS (`null` = 0, Nicht-endlich-Marken), Wahrheitswerte, Punkte, Objekt-Spreizen +//! (`{...v, key: val}`) und Anfrage-Zahlen ([`N`]). +//! +//! Neuer Kern-Code liest das Projekt typisiert (`&Project`, `model`); diese Hilfen bleiben für Werte, +//! die verlustfrei durchgereicht werden müssen (unbekannte Felder, Schlüsselreihenfolge) und für +//! Anfragen der Hülle. + +use serde_json::{Map, Value}; + +/// Feld `k` eines Objekts. Kleine Objekte (Punkte, Elemente) werden linear durchsucht: das ist deutlich +/// billiger als der Hash (SipHash) der `IndexMap` je Zugriff — die Griff- und Objekt-Info-Rechnung liest +/// Dutzende Felder je Aufruf. +#[inline] +pub fn field<'a>(v: &'a Value, k: &str) -> Option<&'a Value> { + match v { + Value::Object(m) if m.len() <= 32 => m.iter().find(|(kk, _)| kk.as_str() == k).map(|(_, x)| x), + Value::Object(m) => m.get(k), + _ => None, + } +} + +/// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64; +/// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0. +pub fn js_num(x: f64) -> Value { + if x.is_nan() { + return Value::String("\u{1}NaN".into()); + } + if x.is_infinite() { + return Value::String(if x > 0.0 { "\u{1}Infinity" } else { "\u{1}-Infinity" }.into()); + } + if x.fract() == 0.0 { + if (0.0..18446744073709551616.0).contains(&x) { + return Value::from(x as u64); + } + if x < 0.0 && x >= -9223372036854775808.0 { + return Value::from(x as i64); + } + } + Value::from(x) +} + +/// Zahl eines JSON-Werts wie in JS-Arithmetik auf der Leseansicht: Zahl, Nicht-endlich-Marke, `null` = 0 +/// (so rechnet JS mit `null`; das Dokument speichert ein tief liegendes NaN als `null`, eine geladene +/// Datei liest es so zurück); fehlend und alles andere NaN. +pub fn num_of(v: Option<&Value>) -> f64 { + match v { + Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN), + Some(Value::Null) => 0.0, + Some(m) => match crate::ops::non_finite_mark(m) { + Some("Infinity") => f64::INFINITY, + Some("-Infinity") => f64::NEG_INFINITY, + _ => f64::NAN, + }, + None => f64::NAN, + } +} + +/// `a ?? b` für Zahlen (fehlend/`null` → `b`). +pub fn num_or(v: Option<&Value>, b: f64) -> f64 { + match v { + None | Some(Value::Null) => b, + v => num_of(v), + } +} + +/// JS-Wahrheitswert. +pub fn truthy(v: Option<&Value>) -> bool { + match v { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()), + Some(Value::String(s)) => !s.is_empty(), + Some(_) => true, + } +} + +/// Punkt `{x, y}` (wie ein neues Objekt-Literal in TS). +pub fn pt(x: f64, y: f64) -> Value { + let mut m = Map::new(); + m.insert("x".into(), js_num(x)); + m.insert("y".into(), js_num(y)); + Value::Object(m) +} + +/// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN). +pub fn xy(v: &Value) -> (f64, f64) { + (num_of(field(v, "x")), num_of(field(v, "y"))) +} + +/// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert +/// (eine grosse Polylinie kostet sonst je Mausschritt eine Kopie mehr). +pub fn with(v: &Value, key: &str, val: Value) -> Value { + with_all(v, vec![(key, val)]) +} + +/// Wie [`with`] für mehrere Felder in einem Durchgang (`{...v, a, b}`). +pub fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value { + with_opt(v, fields.into_iter().map(|(k, x)| (k, Some(x))).collect()) +} + +/// Wie [`with_all`]; `None` = `undefined` (das Feld fällt weg, wie in JSON). +pub fn with_opt(v: &Value, fields: Vec<(&str, Option)>) -> Value { + let mut fields: Vec<(&str, Option, bool)> = fields.into_iter().map(|(k, x)| (k, x, false)).collect(); + let src = v.as_object(); + let mut m = Map::with_capacity(src.map_or(0, Map::len) + fields.len()); + for (k, x) in src.into_iter().flatten() { + match fields.iter_mut().find(|(f, _, _)| *f == k) { + Some((_, new, done)) => { + *done = true; + if let Some(n) = new.take() { + m.insert(k.clone(), n); + } + } + None => { + m.insert(k.clone(), x.clone()); + } + } + } + for (k, x, done) in fields { + if let (false, Some(x)) = (done, x) { + m.insert(k.into(), x); + } + } + Value::Object(m) +} + +pub fn arr(v: Option<&Value>) -> &[Value] { + v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) +} + +/// Zahl der Anfrage: Zahl oder Nicht-endlich-Marke, `null` = 0 (wie `num_of`), fehlend = NaN. +#[derive(Clone, Copy, Debug)] +pub struct N(pub f64); + +impl Default for N { + fn default() -> Self { + N(f64::NAN) + } +} + +impl<'de> serde::Deserialize<'de> for N { + fn deserialize>(d: D) -> Result { + struct V; + impl serde::de::Visitor<'_> for V { + type Value = N; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("Zahl") + } + fn visit_f64(self, v: f64) -> Result { + Ok(N(v)) + } + fn visit_i64(self, v: i64) -> Result { + Ok(N(v as f64)) + } + fn visit_u64(self, v: u64) -> Result { + Ok(N(v as f64)) + } + fn visit_str(self, v: &str) -> Result { + Ok(N(num_of(Some(&Value::String(v.to_owned()))))) + } + fn visit_unit(self) -> Result { + Ok(N(0.0)) + } + fn visit_bool(self, _: bool) -> Result { + Ok(N(f64::NAN)) + } + } + d.deserialize_any(V) + } +} diff --git a/src-tauri/core/src/layers.rs b/src-tauri/core/src/layers.rs index e3f832c4..1b6da296 100644 --- a/src-tauri/core/src/layers.rs +++ b/src-tauri/core/src/layers.rs @@ -11,7 +11,7 @@ use std::collections::HashSet; type Tree = Vec; -use crate::grips::truthy; +use crate::json_util::truthy; fn code_of(c: &Value) -> Option<&str> { c.get("code").and_then(Value::as_str) diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 3a9ff1a3..a2bce28f 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -106,6 +106,7 @@ pub mod wasm_alloc; pub mod text_layout; pub mod plan_text; pub mod grips; +pub mod json_util; pub mod selection_info; pub mod project_refs; pub mod commands; diff --git a/src-tauri/core/src/pens.rs b/src-tauri/core/src/pens.rs index 160fb307..91106410 100644 --- a/src-tauri/core/src/pens.rs +++ b/src-tauri/core/src/pens.rs @@ -12,7 +12,7 @@ pub const PEN_FALLBACK_COLOR: &str = "#9aa0a6"; /// Strichstärke (mm) eines Stifts ohne Eintrag. pub const PEN_FALLBACK_WEIGHT: f64 = 0.18; -use crate::grips::truthy; +use crate::json_util::truthy; /// Schlüssel des Stifts als Objekt-Schlüssel (JS: `pens[penId]`, eine Zahl wird zu Text). fn key_of(v: &Value) -> Option { diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index 82f1cdd8..717f4790 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -9,14 +9,14 @@ //! nach einem Mausschritt an einer grossen Liste wäre deren Neueinlesen teurer als die Abfrage). Nur das //! gewählte Dach, die Treppe und die Stütze werden typisiert gelesen, wo die Geometrie schon typisiert im //! Kern steht (`roof.rs`, `stair.rs`, `model3d::column_footprint`). Zahlen wie in JS: `null` rechnet wie -//! 0 (`grips::num_of`), nicht endliche Ergebnisse reisen als Marken (`grips::js_num`). +//! 0 (`json_util::num_of`), nicht endliche Ergebnisse reisen als Marken (`json_util::js_num`). //! //! Wo TS warf (unbekannter Wandtyp, Deckentyp oder Bauteil), kommt dieselbe Meldung als Fehler. //! Der B-Rep-Körper einer Extrusion (`spec`) bleibt in TS (truck-Pipeline, `plan/extrudedSolidSpec.ts`). use crate::document::Lookup; use crate::model::helpers::heights; -use crate::grips::{arr, field, js_num, num_of, truthy, xy}; +use crate::json_util::{arr, field, js_num, num_of, truthy, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::ops::id_of;