Merge [K3d][K4] Plan-Puffer v2: planDomains binaer statt JSON, GPU kompiliert direkt aus dem Puffer, Chunk-Cache mit Inhalts-Hash (grosser Grundriss 386 -> 171 ms)
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
20 files changed
+2964
-743
No files matched your search
@@ -779,9 +779,10 @@ fn draw_circle_like(
|
||||
c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false);
|
||||
}
|
||||
|
||||
/// Flache Ausgabe (s. Modulkopf); leer bei unlesbarem Plan-Puffer.
|
||||
pub fn compile_flat(buf: &[f64], px_per_meter: f64, packed: bool) -> Vec<u32> {
|
||||
let Some(plan) = plan_buf::decode(buf) else { return Vec::new() };
|
||||
/// Flache Ausgabe (s. Modulkopf) für die Primitive `[from, to)` eines Plan-Puffers (v2); leer bei
|
||||
/// unlesbarem Puffer oder ungültigem Bereich.
|
||||
pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, packed: bool) -> Vec<u32> {
|
||||
let Some(plan) = plan_buf::View::parse(bytes).and_then(|v| v.gpu(from, to)) else { return Vec::new() };
|
||||
let o = compile(&plan, px_per_meter, packed);
|
||||
let mut meta: Vec<f64> = vec![
|
||||
o.origin.0,
|
||||
@@ -843,7 +844,6 @@ mod tests {
|
||||
weight_mm: 0.18,
|
||||
a: v2(ax, 0.0),
|
||||
b: v2(bx, 0.0),
|
||||
dash: vec![],
|
||||
chain,
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
@@ -926,8 +926,8 @@ mod tests {
|
||||
#[test]
|
||||
fn kreis_und_bogen() {
|
||||
let p = plan(vec![
|
||||
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: vec![] },
|
||||
Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0, dash: vec![] },
|
||||
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0 },
|
||||
Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0 },
|
||||
Prim::Placeholder,
|
||||
]);
|
||||
let o = compile(&p, 0.0, false);
|
||||
@@ -938,9 +938,26 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn kaputter_puffer_leer() {
|
||||
assert!(compile_flat(&[1.0, 2.0, 3.0], 90.0, true).is_empty());
|
||||
let enc = plan_buf::encode(&plan(vec![line(0.0, f64::NAN, false)]));
|
||||
let out = compile_flat(&enc, 90.0, true);
|
||||
assert!(!out.is_empty());
|
||||
assert!(compile_flat(&[1, 2, 3], 0, 0, 90.0, true).is_empty());
|
||||
let mut w = plan_buf::Writer::new(false);
|
||||
w.push(&crate::plan::prim::Primitive::Line {
|
||||
a: crate::model::Vec2 { x: 0.0, y: 0.0 },
|
||||
b: crate::model::Vec2 { x: f64::NAN, y: 0.0 },
|
||||
cls: "c".into(),
|
||||
weight_mm: 0.18,
|
||||
dash: None,
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: None,
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
let enc = w.finish();
|
||||
assert!(!compile_flat(&enc, 0, 1, 90.0, true).is_empty());
|
||||
assert!(compile_flat(&enc, 0, 2, 90.0, true).is_empty(), "Bereich ausserhalb");
|
||||
assert!(!compile_flat(&enc, 1, 1, 90.0, true).is_empty(), "leerer Bereich = leere Geometrie");
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ use crate::js_fmt::{js_number, to_fixed};
|
||||
use crate::jsnum::{max, min, round};
|
||||
use crate::model::*;
|
||||
use crate::plan_walls::{ceiling_outline_lines, wall_footprint, WallFootprint};
|
||||
use serde::Serialize;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Footprint-Farbe der Extrusionen (wie das 3D-Orange).
|
||||
@@ -96,9 +95,10 @@ impl<'a> Ctx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ergebnis der Abfrage `planDomains`: Primitive je Domäne (TS setzt sie an ihre Stelle in der
|
||||
/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen.
|
||||
#[derive(Serialize, Default)]
|
||||
/// Ergebnis der Plan-Erzeugung: Primitive je Domäne (TS setzt sie an ihre Stelle in der
|
||||
/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen. Über die Grenze geht es
|
||||
/// als Plan-Puffer v2 ([`plan_domains_buf`]).
|
||||
#[derive(Default)]
|
||||
pub struct DomainPrims {
|
||||
pub ceilings: Vec<Primitive>,
|
||||
/// Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand nacheinander.
|
||||
@@ -517,6 +517,21 @@ pub fn plan_domains(p: &Project, a: &PlanArgs) -> Result<DomainPrims, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reihenfolge der Gruppen im Plan-Puffer der Abfrage `planDomains`.
|
||||
pub const GROUPS: [&str; 9] = ["ceilings", "roofs", "rooms", "walls", "stairs", "columns", "solids", "context", "sections"];
|
||||
|
||||
/// Abfrage `planDomains` als Plan-Puffer v2 (s. `plan_buf.rs`): eine Gruppe je Domäne in der
|
||||
/// Reihenfolge [`GROUPS`], Ausmass im Kopf, Inhalts-Hashes für den GPU-Chunk-Cache.
|
||||
pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
|
||||
let d = plan_domains(p, a)?;
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections] {
|
||||
w.group(g);
|
||||
}
|
||||
w.bounds = d.bounds;
|
||||
Ok(w.finish())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -545,6 +560,22 @@ mod tests {
|
||||
assert!(r.bounds.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn puffer_gruppen_wie_domaenen() {
|
||||
let p = sample();
|
||||
let a = args("eg", 1.0, &["20", "21", "30", "40", "60"]);
|
||||
let d = plan_domains(&p, &a).unwrap();
|
||||
let buf = plan_domains_buf(&p, &a).unwrap();
|
||||
let (prims, groups, bounds) = crate::plan_buf::decode(&buf).unwrap();
|
||||
assert_eq!(groups.len(), GROUPS.len());
|
||||
let lists = [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections];
|
||||
for ((a, b), l) in groups.iter().zip(lists) {
|
||||
assert_eq!(serde_json::to_string(&prims[*a..*b]).unwrap(), serde_json::to_string(l).unwrap());
|
||||
}
|
||||
assert!(!d.walls.is_empty() && !d.rooms.is_empty());
|
||||
assert_eq!(bounds, d.bounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsichtbare_codes_fehlen() {
|
||||
let p = sample();
|
||||
@@ -605,4 +636,38 @@ mod tests {
|
||||
let col = Column { profile: ColumnProfile::Round { radius: 0.125 }, ..Default::default() };
|
||||
assert_eq!(column_label(&col), "Stütze Ø25");
|
||||
}
|
||||
|
||||
/// Messung (von Hand): `PLAN_BIG=projekt.obp cargo test --release --lib messung_plan_puffer -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn messung_plan_puffer() {
|
||||
let Ok(path) = std::env::var("PLAN_BIG") else { return };
|
||||
let mut doc = crate::document::Document::from_json(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
let p = doc.project().unwrap().clone();
|
||||
let codes: Vec<String> = p.flat_categories().iter().map(|c| c.code.clone()).collect();
|
||||
let t = serde_json::json!({ "floor": "eg", "show": codes, "grey": [], "global": true }).to_string();
|
||||
let a = PlanArgs::parse(1.0, &t).unwrap();
|
||||
let time = |name: &str, f: &mut dyn FnMut()| {
|
||||
f();
|
||||
let t0 = std::time::Instant::now();
|
||||
for _ in 0..5 {
|
||||
f();
|
||||
}
|
||||
println!("{name}: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 5.0);
|
||||
};
|
||||
time("plan_domains", &mut || {
|
||||
plan_domains(&p, &a).unwrap();
|
||||
});
|
||||
let d = plan_domains(&p, &a).unwrap();
|
||||
time("Puffer schreiben", &mut || {
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections] {
|
||||
w.group(g);
|
||||
}
|
||||
w.finish();
|
||||
});
|
||||
time("JSON (früher)", &mut || {
|
||||
serde_json::to_string(&(&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections)).unwrap();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,10 @@
|
||||
//! Zeichen für Zeichen die der TS-Objekte (camelCase, fehlende Felder fehlen).
|
||||
|
||||
use crate::model::*;
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
/// Aufgelöste Schraffur eines Polygons (`HatchRender`).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HatchRender {
|
||||
pub pattern: HatchPattern,
|
||||
@@ -38,7 +38,7 @@ pub struct HatchRender {
|
||||
}
|
||||
|
||||
/// Zeile unter dem Raum-Stempel.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct StampLine {
|
||||
pub text: String,
|
||||
pub align: Align,
|
||||
@@ -47,7 +47,12 @@ pub struct StampLine {
|
||||
/// `dash?: number[] | null`: fehlt (`None`), `null` (`Some(None)`) oder Muster.
|
||||
pub type Dash = Option<Option<Vec<f64>>>;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
/// Liest `dash` so, dass `null` (`Some(None)`) und fehlend (`None`, über `default`) verschieden bleiben.
|
||||
fn de_dash<'de, D: Deserializer<'de>>(d: D) -> Result<Dash, D::Error> {
|
||||
Option::<Vec<f64>>::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum Primitive {
|
||||
#[serde(rename = "polygon", rename_all = "camelCase")]
|
||||
@@ -92,7 +97,7 @@ pub enum Primitive {
|
||||
b: Vec2,
|
||||
cls: String,
|
||||
weight_mm: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
zigzag: Option<LineStyleZigzag>,
|
||||
@@ -119,7 +124,7 @@ pub enum Primitive {
|
||||
r: f64,
|
||||
cls: String,
|
||||
weight_mm: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opening_id: Option<String>,
|
||||
@@ -164,13 +169,82 @@ pub enum Primitive {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
/// Text entlang eines Pfads (2D-Zeichnung); erzeugt heute nur TS, s. Plan-Puffer v2.
|
||||
#[serde(rename = "drawingTextPath", rename_all = "camelCase")]
|
||||
DrawingTextPath {
|
||||
path_pts: Vec<Vec2>,
|
||||
text: String,
|
||||
height_m: f64,
|
||||
color: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
/// Eingebettetes Rasterbild (2D-Zeichnung).
|
||||
#[serde(rename = "drawingImage", rename_all = "camelCase")]
|
||||
DrawingImage {
|
||||
min: Vec2,
|
||||
max: Vec2,
|
||||
src: String,
|
||||
opacity: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
},
|
||||
/// Glatter Kreis (2D-Zeichnung).
|
||||
#[serde(rename = "drawingCircle", rename_all = "camelCase")]
|
||||
DrawingCircle {
|
||||
center: Vec2,
|
||||
r: f64,
|
||||
fill: String,
|
||||
stroke: String,
|
||||
weight_mm: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
/// Glatter Bogen (2D-Zeichnung), Winkel im Bogenmass (CCW).
|
||||
#[serde(rename = "drawingArc", rename_all = "camelCase")]
|
||||
DrawingArc {
|
||||
center: Vec2,
|
||||
r: f64,
|
||||
a0: f64,
|
||||
a1: f64,
|
||||
stroke: String,
|
||||
weight_mm: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
/// Setzt `greyed` (für Gruppen, deren Darstellungsmodus gedimmt ist).
|
||||
pub fn with_greyed(mut self, g: bool) -> Self {
|
||||
match &mut self {
|
||||
Primitive::Polygon { greyed, .. } | Primitive::Line { greyed, .. } | Primitive::Arc { greyed, .. } | Primitive::Text { greyed, .. } | Primitive::DrawingText { greyed, .. } => *greyed = Some(g),
|
||||
Primitive::Polygon { greyed, .. }
|
||||
| Primitive::Line { greyed, .. }
|
||||
| Primitive::Arc { greyed, .. }
|
||||
| Primitive::Text { greyed, .. }
|
||||
| Primitive::DrawingText { greyed, .. }
|
||||
| Primitive::DrawingTextPath { greyed, .. }
|
||||
| Primitive::DrawingImage { greyed, .. }
|
||||
| Primitive::DrawingCircle { greyed, .. }
|
||||
| Primitive::DrawingArc { greyed, .. } => *greyed = Some(g),
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
+1590
-411
File diff suppressed because it is too large.
Load diff
@@ -39,8 +39,15 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
|
||||
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
|
||||
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
|
||||
("planDomains", 1) => json(&crate::plan::domains::plan_domains(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?)?),
|
||||
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Abfragen mit binärer Antwort (Plan-Puffer v2, s. `plan_buf.rs`).
|
||||
pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<u8>, String> {
|
||||
match (name, args.len()) {
|
||||
("planDomains", 1) => crate::plan::domains::plan_domains_buf(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?),
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
@@ -177,3 +177,15 @@ pub fn doc_drawing_line_verts(h: u32) -> Vec<f32> {
|
||||
pub fn doc_serialize(h: u32) -> String {
|
||||
with_doc(h, |d| d.serialize()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Abfrage mit binärer Antwort (`crate::queries::run_bin`, z. B. `planDomains` als Plan-Puffer v2).
|
||||
/// Fehler kommen als Fehlerpuffer (`plan_buf::encode_error`).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query_bin(h: u32, name: &str, args: &[f64], text: &str) -> Vec<u8> {
|
||||
let result = with_doc(h, |d| {
|
||||
let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?;
|
||||
crate::queries::run_bin(&p, name, args, text)
|
||||
})
|
||||
.unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
result.unwrap_or_else(|e| crate::plan_buf::encode_error(&e))
|
||||
}
|
||||
@@ -2,11 +2,18 @@
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Plan-Puffer (ein Chunk) → Vertex-/Index-/Batch-Daten als ein `u32`-Puffer; leer bei
|
||||
/// unlesbarem Puffer.
|
||||
/// Primitive `[from, to)` eines Plan-Puffers (v2) → Vertex-/Index-/Batch-Daten als ein
|
||||
/// `u32`-Puffer; leer bei unlesbarem Puffer oder ungültigem Bereich.
|
||||
#[wasm_bindgen]
|
||||
pub fn gpu_compile_flat(buf: &[f64], px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
|
||||
crate::gpu_compile::compile_flat(buf, px_per_meter, packed_lines)
|
||||
pub fn gpu_compile_flat(buf: &[u8], from: u32, to: u32, px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
|
||||
crate::gpu_compile::compile_flat(buf, from as usize, to as usize, px_per_meter, packed_lines)
|
||||
}
|
||||
|
||||
/// Wie [`gpu_compile_flat`] auf einem gehaltenen Puffer (`plan_buf_hold`); leer, wenn er nicht
|
||||
/// mehr gehalten wird.
|
||||
#[wasm_bindgen]
|
||||
pub fn gpu_compile_held(id: u32, from: u32, to: u32, px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
|
||||
super::plan_buf::with_held(id, |b| crate::gpu_compile::compile_flat(b, from as usize, to as usize, px_per_meter, packed_lines)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Ear-Clipping eines Rings `[x, y, …]` → Dreiecks-Indizes.
|
||||
|
||||
@@ -1,10 +1,53 @@
|
||||
//! Bindungen des Plan-Puffers (`crate::plan_buf`). Format s. dort.
|
||||
//!
|
||||
//! Gehaltene Puffer: TS übergibt einen Plan-Puffer einmal (`plan_buf_hold`) und kompiliert danach
|
||||
//! beliebig viele GPU-Chunks daraus (`gpu_compile_held`), ohne ihn je Chunk erneut zu kopieren.
|
||||
//! Höchstens `MAX_HELD` Puffer bzw. `MAX_HELD_BYTES` bleiben liegen (ältester fällt weg);
|
||||
//! ein verdrängter Puffer liefert leere Ergebnisse, TS übergibt ihn dann neu.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
const MAX_HELD: usize = 8;
|
||||
const MAX_HELD_BYTES: usize = 96 << 20;
|
||||
|
||||
thread_local! {
|
||||
static HELD: RefCell<(u32, Vec<(u32, Vec<u8>)>)> = const { RefCell::new((0, Vec::new())) };
|
||||
}
|
||||
|
||||
/// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei
|
||||
/// fremder Version oder kaputtem Puffer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_buf_recode(buf: &[f64]) -> Vec<f64> {
|
||||
pub fn plan_buf_recode(buf: &[u8]) -> Vec<u8> {
|
||||
crate::plan_buf::recode(buf)
|
||||
}
|
||||
|
||||
/// Puffer im Kern halten; Ergebnis ist die Nummer (≥ 1), 0 bei unlesbarem Puffer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_buf_hold(buf: &[u8]) -> u32 {
|
||||
if crate::plan_buf::View::parse(buf).is_none() {
|
||||
return 0;
|
||||
}
|
||||
HELD.with(|h| {
|
||||
let mut h = h.borrow_mut();
|
||||
h.0 = h.0.wrapping_add(1).max(1);
|
||||
let id = h.0;
|
||||
h.1.push((id, buf.to_vec()));
|
||||
let mut bytes: usize = h.1.iter().map(|e| e.1.len()).sum();
|
||||
while h.1.len() > MAX_HELD || (bytes > MAX_HELD_BYTES && h.1.len() > 1) {
|
||||
bytes -= h.1.remove(0).1.len();
|
||||
}
|
||||
id
|
||||
})
|
||||
}
|
||||
|
||||
/// Gehaltenen Puffer freigeben (unbekannte Nummer: nichts).
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_buf_release(id: u32) {
|
||||
HELD.with(|h| h.borrow_mut().1.retain(|e| e.0 != id));
|
||||
}
|
||||
|
||||
/// Mit dem gehaltenen Puffer `id` rechnen; `None`, wenn er nicht (mehr) da ist.
|
||||
pub(crate) fn with_held<R>(id: u32, f: impl FnOnce(&[u8]) -> R) -> Option<R> {
|
||||
HELD.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| f(&e.1)))
|
||||
}
|
||||
Reference in new issue
Block a user