[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).
This commit is contained in:
Claude committed 2026-11-03 21:54:12 +00:00
1 parent b04b0502ea
commit 7491c7144b
19 files changed
+198 -189

No files matched your search

+1 -1
View File
@@ -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};
+4 -4
View File
@@ -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<V> = 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<String, Value>, 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<V> = c.pts.iter().map(|q| (q[0], q[1])).collect();
+1 -1
View File
@@ -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};
+1 -1
View File
@@ -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;
+2 -2
View File
@@ -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<String, Value>, 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(
+1 -1
View File
@@ -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};
+2 -2
View File
@@ -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};
+1 -1
View File
@@ -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};
+1 -1
View File
@@ -657,7 +657,7 @@ fn refs_of(g: &Value) -> Option<Vec<Option<DimRef>>> {
}
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 {
+1 -1
View File
@@ -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<String, Value>, key: &str, v: Option<Value>) {
+1 -164
View File
@@ -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>)>) -> Value {
let mut fields: Vec<(&str, Option<Value>, 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<usize> {
(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: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
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<E>(self, v: f64) -> Result<N, E> {
Ok(N(v))
}
fn visit_i64<E>(self, v: i64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_u64<E>(self, v: u64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_str<E>(self, v: &str) -> Result<N, E> {
Ok(N(num_of(Some(&Value::String(v.to_owned())))))
}
fn visit_unit<E>(self) -> Result<N, E> {
Ok(N(0.0))
}
fn visit_bool<E>(self, _: bool) -> Result<N, E> {
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)]
+2 -2
View File
@@ -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<T>(items: &[T], key: impl Fn(&T) -> String) -> Vec<Vec<usize>> {
/// LV95-Ursprung des Projekts (`projectGeoOrigin`: `geoAnchor.lv95 − geoAnchor.model`), ohne Bezug `None`.
pub fn project_geo_origin(root: &Map<String, Value>) -> 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")])
}
+1 -1
View File
@@ -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;
+3 -3
View File
@@ -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<String, Value>, 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 });
}
+171
View File
@@ -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>)>) -> Value {
let mut fields: Vec<(&str, Option<Value>, 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: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
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<E>(self, v: f64) -> Result<N, E> {
Ok(N(v))
}
fn visit_i64<E>(self, v: i64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_u64<E>(self, v: u64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_str<E>(self, v: &str) -> Result<N, E> {
Ok(N(num_of(Some(&Value::String(v.to_owned())))))
}
fn visit_unit<E>(self) -> Result<N, E> {
Ok(N(0.0))
}
fn visit_bool<E>(self, _: bool) -> Result<N, E> {
Ok(N(f64::NAN))
}
}
d.deserialize_any(V)
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ use std::collections::HashSet;
type Tree = Vec<Value>;
use crate::grips::truthy;
use crate::json_util::truthy;
fn code_of(c: &Value) -> Option<&str> {
c.get("code").and_then(Value::as_str)
+1
View File
@@ -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;
+1 -1
View File
@@ -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<String> {
+2 -2
View File
@@ -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;