diff --git a/ARROW_SCHEMA.md b/ARROW_SCHEMA.md new file mode 100644 index 0000000..c36ef64 --- /dev/null +++ b/ARROW_SCHEMA.md @@ -0,0 +1,142 @@ +# Arrow Schema Documentation + +This project uses Apache Arrow to represent GDSII (Graphic Data System II) library data. The schema is optimized for memory efficiency and fast access, employing several packed representations for common data types. + +## Top-Level Structure + +The top-level object is a `StructArray` representing the entire GDSII library. + +| Field | Type | Description | +|---|---|---| +| `meters_per_db_unit` | `Float64` | Database unit size in meters. | +| `user_units_per_db_unit` | `Float64` | Number of user units in one database unit. | +| `lib_name` | `Utf8` | The name of the GDSII library. | +| `mod_time` | `FixedSizeList(Int16, 6)` | Last modification time [year, month, day, hour, minute, second]. | +| `acc_time` | `FixedSizeList(Int16, 6)` | Last access time [year, month, day, hour, minute, second]. | +| `cells` | `List(Cell)` | A list of cells (structures) in the library. | +| `cell_names` | `List(Utf8)` | Names of all cells, indexed by their ID. | +| `layers` | `List(UInt32)` | List of packed layer/datatype pairs, indexed by their ID. | + +## Cell Structure + +Each cell in the `cells` list is a `StructArray`. + +| Field | Type | Description | +|---|---|---| +| `id` | `UInt32` | Unique identifier for the cell. | +| `file_offset` | `UInt64` | Byte offset immediately after the cell's `STRNAME` record (the first element, or `ENDSTR` for an empty cell). Identical for full and selected reads. | +| `srefs` | `List(SRef)` | Simple structure references (no properties). | +| `arefs` | `List(ARef)` | Array references (no properties). | +| `sref_props` | `List(SRefProp)` | Structure references with properties. | +| `aref_props` | `List(ARefProp)` | Array references with properties. | +| `rect_batches` | `List(RectBatch)` | Batches of rectangular boundaries (optimized). | +| `boundary_batches` | `List(BoundaryBatch)` | Batches of generic boundaries. | +| `boundary_props` | `List(BoundaryProp)` | Individual boundaries with properties. | +| `paths` | `List(Path)` | Path elements. | +| `nodes` | `List(BoxNode)` | Node elements. | +| `boxes` | `List(BoxNode)` | Box elements. | +| `texts` | `List(Text)` | Text labels. | + +## Hierarchy Scan Schema + +`scan_library` and `scan_bytes` return the same library metadata and `cell_names` +as a full read, with the following `cells` schema and no `layers` field: + +| Field | Type | Description | +|---|---|---| +| `id` | `UInt32` | Cell ID indexing this result's `cell_names`. | +| `struct_start_offset` | `UInt64` | Inclusive byte offset of the `BGNSTR` record. | +| `struct_end_offset` | `UInt64` | Exclusive byte offset immediately after `ENDSTR`. | +| `refs` | `List(ScanRef)` | SREFs and AREFs, including references with properties, sorted by target ID. | + +Each scan reference has `target`, `invert_y`, `scale`, `angle_rad`, `xy`, `xy0`, +`xy1`, and `counts`, using the ARef types and packed encodings described below. +SREFs use zero basis vectors and counts `(1, 1)`. Properties are omitted from the +scan output; geometry and text are skipped without decoding. + +Pass the half-open scan ranges to `read_selected_library` or `read_cells_bytes` +to obtain the full library schema for just those cells. Each range must contain +exactly one complete cell, from `BGNSTR` through `ENDSTR`. Cells appear in the +requested order. Cell and layer IDs are assigned within each result, so use +`cell_names` and `layers` from that result when resolving them; IDs can differ +from a full read or a scan. An empty selection returns metadata and empty lists. +The Rust random-access reader returns the original input slice as its remainder. + +## Element Types + +### Common Packed Encodings + +- **Layer ID (`UInt32`)**: A packed representation of `(layer, datatype)`. + - `layer = (layer_id >> 16) as i16` + - `datatype = (layer_id & 0xFFFF) as i16` +- **XY Coordinate (`UInt64`)**: A packed representation of a single point `(x, y)`. + - `x = (xy >> 32) as i32` + - `y = (xy & 0xFFFFFFFF) as i32` +- **Array Counts (`UInt32`)**: A packed representation of `(columns, rows)`. + - `columns = (counts >> 16) as i16` + - `rows = (counts & 0xFFFF) as i16` + +### Reference Elements (SRef / ARef) + +References point to other cells in the library. + +**SRef (Simple Reference)**: +- `target`: `UInt32` (Cell ID) +- `invert_y`: `Boolean` (Vertical flip) +- `scale`: `Float64` (Magnification) +- `angle_rad`: `Float64` (Rotation in radians) +- `xy`: `UInt64` (Packed origin point) + +**ARef (Array Reference)**: +- Same as SRef, plus: +- `xy0`: `UInt64` (Packed column basis vector increment) +- `xy1`: `UInt64` (Packed row basis vector increment) +- `counts`: `UInt32` (Packed columns and rows) + +**SRefProp / ARefProp**: +- Same as above, plus a `properties` field. + +### Boundary Elements + +Boundaries are grouped into batches for efficiency when they share properties or are simple rectangles. + +**RectBatch**: +- `layer`: `UInt32` (Packed Layer ID) +- `rects`: `List(Int32)` (Flattened list of `[min_x, min_y, max_x, max_y]` for each rectangle) + +**BoundaryBatch**: +- `layer`: `UInt32` (Packed Layer ID) +- `vertices`: `List(Int32)` (Flattened list of all vertices for all boundaries in the batch) +- `vertex_offsets`: `List(UInt32)` (Start index for each boundary in the `vertices` list) + +**BoundaryProp**: +- Individual boundary with `properties`. + +### Other Elements + +**Path**: +- `layer`: `UInt32` +- `path_type`: `Int16` (Optional) +- `extension_start`: `Int32` (Optional) +- `extension_end`: `Int32` (Optional) +- `width`: `Int32` (Optional; null when `WIDTH` is absent) +- `xy`: `List(Int32)` (centerline coordinates) +- `properties`: `List(Property)` + +**Text**: +- `layer`: `UInt32` +- `presentation_horiz`: `UInt8` +- `presentation_vert`: `UInt8` +- `presentation_font`: `UInt8` +- `path_type`: `Int16` +- `width`: `Int32` +- `invert_y`: `Boolean` +- `mag`: `Float64` +- `angle_deg`: `Float64` +- `xy`: `UInt64` (Packed position) +- `string`: `Utf8` +- `properties`: `List(Property)` + +**Property**: +- `key`: `Int16` +- `value`: `Utf8` diff --git a/README.md b/README.md new file mode 100644 index 0000000..2eb673a --- /dev/null +++ b/README.md @@ -0,0 +1,218 @@ +# klamath-rs + +A fast GDSII parser and writer in Rust, with Apache Arrow integration for efficient data handling. + +## Overview + +`klamath-rs` is designed to handle large GDSII files with high performance. It uses Apache Arrow as its primary in-memory data representation, allowing for efficient memory usage and easy integration with other tools in the Arrow ecosystem (like pandas, polars, or DuckDB via Python bindings). + +## Documentation + +- [Arrow Schema Documentation](ARROW_SCHEMA.md): Detailed information about the Arrow schema used for GDSII data. + +## Features + +- Fast parsing of GDSII files. +- Efficient memory representation using Apache Arrow. +- Support for common GDSII elements: SREF, AREF, Boundary, Path, Text, etc. +- Optimized "batch" representations for rectangles and boundaries sharing the same layer. +- C-compatible FFI for integration with other languages (e.g., Python). + +## Usage + +`read_path` exports a library through the Arrow C Data Interface. Allocate +initialized `ArrowArray` and `ArrowSchema` output structures, then check the +returned status: `0` means success and `-1` means failure. Only import the Arrow +outputs after success; the caller owns their release callbacks. Failed calls +leave the outputs unchanged. See `test.py` for a Python CFFI example. + +`last_error_message()` returns a UTF-8, null-terminated error string, or null +after a successful parser call. Errors belong to the calling thread. Copy the +message before making another parser call on that thread, and before the thread +exits; calls on other threads do not invalidate it. Parser panics that unwind +are converted into errors. + +For partial reads, call `scan_bytes` with a borrowed GDSII byte buffer to obtain +cell ranges and references without decoding geometry. Pass the desired ranges +to `read_cells_bytes` to load their full contents. Both calls use the same Arrow +outputs and status/error handling as `read_path`: + +```c +int scan_bytes(const uint8_t *data, size_t size, + struct ArrowArray *array, struct ArrowSchema *schema); +int read_cells_bytes(const uint8_t *data, size_t size, + const uint64_t *ranges, size_t range_count, + struct ArrowArray *array, struct ArrowSchema *schema); +``` + +`ranges` contains alternating inclusive start and exclusive end offsets, with +two native-endian `uint64_t` values per cell. Each range must cover one complete +cell. A null `ranges` pointer is accepted when `range_count` is zero. Likewise, +null `data` is accepted for zero bytes and produces an ordinary parse error for +the empty input. Nonempty buffers must be readable for the duration of the call; +range values must be aligned. Exported Arrow data owns its storage independently +of the input. See [Arrow Schema Documentation](ARROW_SCHEMA.md) for the scan +schema, offset definitions, and ID assignment. + +## Layout review CLI + +The review CLI uses the existing Rust dependencies: + +```sh +cargo build --bin klamath +target/debug/klamath dump chip.gds +target/debug/klamath dump chip.gds --records +target/debug/klamath diff old.gds new.gds --hierarchy ascii +target/debug/klamath diff old.gds new.gds --hierarchy mermaid --max-changes 20 +target/debug/klamath hierarchy chip.gds --format mermaid --depth 4 +target/debug/klamath diff old.gds new.gds --top CHIP --layer 1/0 +target/debug/klamath diff old.gds new.gds --show-layer 1/0 +target/debug/klamath name-layers chip.gds named.gds --cell CHIP --carrier 900/7 --name 1:0:WG +``` + +The object dump is deterministic and omits source offsets. Record dumps preserve +record order and show offsets, tags, sizes, and values, including records the +object reviewer does not support. They can inspect an invalid metadata declaration +without invoking object-level validation. Zero padding after ENDLIB is accepted. + +The fixed `klamath-object-v2` comparison profile: + +- Matches cells by name and layers by numeric pair. The default scope is the + entire library; explicit selectors are recorded in each report. +- Ignores library/cell timestamps, cell order, element order, and property order. +- Normalizes boundary/box starting vertex and winding, retaining other vertices. +- Preserves duplicate objects and duplicate properties as multisets. +- Compares paths, labels, references, array endpoints/counts, properties, and all + retained flags exactly. Explicit defaults and their omission remain distinct; + SREFs and single-element AREFs remain distinct. REAL8 encodings are retained. +- Reports library fields, including UNITS, separately. It does not rescale files + into a shared grid, infer cell renames, or perform geometric Boolean operations. +- Uses bounding boxes as coordinate envelopes, not evidence of equality. Path + envelopes do not include stroke width; text/reference envelopes are coordinates, + not rendered or recursively transformed bounds. +- Returns an incomplete result for unsupported records, future metadata versions, + unresolved references, or cycles. These cannot produce an equality claim. + +`diff` exits with **0** for equality under this profile, **1** for differences, +and **2** for invalid input or incomplete comparison. `--max-changes` limits the +number of object details displayed, not the comparison. Source offsets are +included in changed-object reports for tracing changes back to record dumps. + +Unmatched objects are paired for explanation only when candidates are unique by +type/layer/bounding box, then by type/layer among the remaining objects. +References additionally match by target. Ambiguous groups stay additions and +removals. Reports explain reference movement, array-count changes, path widths, +and polygons changed within the same bounds. Full before/after records remain +visible, and duplicate counts remain significant. Unchanged layer names appear +once as a legend for changed objects on those layers. + +### Comparison scope and display filters + +`--top NAME` compares that cell and its reachable subtree independently in each +revision. `--cell NAME` compares the exact cell, including its reference records, +without comparing descendant contents. Combine the two to select a cell within +a subtree. A selector absent from both revisions is an error; absence on one +side is an addition/deletion. + +`--layer L/T` selects objects on a numeric layer/type pair, plus references whose +targets use that layer transitively. Cells with no relevant content are omitted. +Unresolved references, cycles, and unsupported records with unknown layer effect +remain incomplete results. Unsupported objects on another known layer can be +excluded. Library fields, including units, remain compared. Scoped dumps and +hierarchy views accept the same selectors. Scope selection parses the complete +input: malformed record grammar and conflicting metadata are still errors. + +`--show-cell NAME` and `--show-layer L/T` filter object details in a diff report +without changing comparison status, totals, metadata changes, or hierarchy. +References have no numeric layer and are hidden by `--show-layer`. The comparison +scope and any display-only filter are printed explicitly. The Rust API accepts +one combined `Scope`; applying another scope to an already scoped document is +rejected rather than losing reference coverage information. + +Hierarchy output distinguishes directly changed cells, affected ancestors, and +unchanged targets of modified references. It includes edges from both revisions, +so removed branches remain visible. Counts are direct edge multiplicities, +including arrays, rather than expanded placements. Shared definitions are marked +as already shown in text and appear once in Mermaid. `--depth` limits displayed +descendants only. The CLI emits Mermaid source, requiring no diagram renderer. + +Layer names are read from labels in an existing cell. A label with the exact +string `KLAMATH_LAYER_NAMES_V1` identifies an annotation carrier `(layer, texttype)` +pair within that cell. All other labels on that same pair in that same cell must +be `layer:datatype:name` declarations, for example `1:0:WG`. The carrier pair is +not fixed; choose a suitable annotation layer in the design's technology. +Declarations split at the first two colons, allowing colons in names. Numeric +fields are unsigned 16-bit decimal integers. Names are nonempty UTF-8 strings. +Repeated identical declarations are accepted; conflicting declarations fail. +Names are collected across the library. Recognized metadata labels are omitted +from object comparison; mappings are compared separately and printed once per +numeric pair, so renaming a layer does not rewrite every shape description. + +`name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...` writes +this convention. It consolidates existing recognized declarations into one legend +in the chosen existing cell, retains existing names not explicitly updated, and +overrides the named pairs. The chosen carrier must contain no ordinary design +objects in that cell. Unrelated records, timestamps, unknown records and trailing +padding are copied byte-for-byte. No structures or references are added. Output +must be a new file: the CLI refuses to overwrite an existing destination, including +the input. Invalid declarations, conflicting arguments, oversized labels and +future metadata versions fail before output creation. + +The record-preserving review adapter retains information normalized or omitted +by the Arrow geometry reader; existing Arrow APIs are unchanged. Structured Rust +change records feed the text and hierarchy renderers. LayoutEditor's `LayerNames` +extension, layout extraction/remapping, and geometric Boolean comparison remain +outside the current CLI. + +### Git integration + +Install the executable on PATH with `cargo install --path . --bin klamath`. +The templates in [contrib/git/config](contrib/git/config) and +[contrib/git/attributes](contrib/git/attributes) provide two alternative drivers. +For structural summaries and affected hierarchy, add this attribute: + +```gitattributes +*.gds diff=klamath +``` + +Configure the native external driver in Git config: + +```gitconfig +[diff "klamath"] + command = klamath git-diff --hierarchy ascii -- + binary = true + trustExitCode = false +``` + +The adapter consumes Git's old/new temporary files directly, handles additions, +deletions and renames, and quotes display paths. It returns success after rendering +either equality or differences, as expected by the external-driver protocol. +Invalid or incomplete comparisons retain a nonzero exit and diagnostics. Scope +and display options can precede the final `--` in the configured command. Existing +repositories using `diff=layout` can put the same command under `[diff "layout"]`. + +For ordinary Git line diffs, use canonical textconv instead: + +```gitattributes +*.gds diff=klamath-text +``` + +Configure the driver in Git config: + +```gitconfig +[diff "klamath-text"] + textconv = klamath dump + binary = true + cachetextconv = true +``` + +This is a human review representation, not an applicable GDS patch. Invalidate +Git's textconv cache when changing the dump profile/tool version. For automated +equality checks, use `klamath diff` and its exit status directly. + +`tests/review.rs` contains ten initial fixture pairs, checked-in canonical/text/ +Mermaid goldens, metadata byte-preservation checks, scope and report regressions, +and actual Git integration tests. It also checks near-limit polygon records, +2048-cell hierarchies and arrays representing over a billion placements without +expanding them. Run `cargo test` and `cargo test --release` for debug and optimized +validation. No KLayout installation or Python package is required. diff --git a/contrib/git/attributes b/contrib/git/attributes new file mode 100644 index 0000000..051952d --- /dev/null +++ b/contrib/git/attributes @@ -0,0 +1,5 @@ +# Add these lines to the layout repository's .gitattributes. +*.gds diff=klamath + +# For canonical textconv instead, replace the line above with: +# *.gds diff=klamath-text diff --git a/contrib/git/config b/contrib/git/config new file mode 100644 index 0000000..2852e9a --- /dev/null +++ b/contrib/git/config @@ -0,0 +1,10 @@ +# Include this file from Git config after installing klamath on PATH. +[diff "klamath"] + command = klamath git-diff --hierarchy ascii -- + binary = true + trustExitCode = false + +[diff "klamath-text"] + textconv = klamath dump + binary = true + cachetextconv = true diff --git a/src/basic.rs b/src/basic.rs index 051d0ba..828c282 100644 --- a/src/basic.rs +++ b/src/basic.rs @@ -98,8 +98,7 @@ pub fn parse_bitarray(input: &[u8]) -> IResult<'_, [bool; 16]> { pub fn parse_ascii(input: &[u8], length: u16) -> IResult<'_, Vec> { let length = length as usize; let (input, data) = take_bytes(input, length)?; - let last = data[length - 1]; - let true_length = if last == 0 { length - 1 } else { length }; + let true_length = length - usize::from(data.last() == Some(&0)); let vec = data[..true_length].to_vec(); Ok((input, vec)) } diff --git a/src/bin/klamath.rs b/src/bin/klamath.rs new file mode 100644 index 0000000..5dc0c21 --- /dev/null +++ b/src/bin/klamath.rs @@ -0,0 +1,259 @@ +use klamath_rs_ext::review::{ + Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer, + parse_layer_name, write_layer_names, +}; +use std::{ + collections::BTreeMap, + ffi::OsString, + fs, + io::{self, Write}, + process::ExitCode, +}; + +const HELP: &str = "Usage: + klamath dump FILE [--records] + klamath diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T]\n [--show-cell NAME] [--show-layer L/T] [--hierarchy ascii|mermaid|none]\n [--max-changes N] [--depth N] + klamath hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n klamath git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE + klamath name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ... + +Object profile: ignore timestamps and element order, normalize polygon start/winding, +preserve duplicates, compare all retained fields exactly. No geometric XOR or tolerance. +Exit status: 0 equal/success, 1 different, 2 invalid/unsupported/incomplete. +"; + +fn value(args: &[OsString], index: &mut usize) -> Result { + *index += 1; + args.get(*index) + .and_then(|s| s.to_str()) + .map(str::to_owned) + .ok_or_else(|| "missing UTF-8 option value".to_string()) +} + +fn name_layers(args: &[OsString]) -> Result { + if args.len() < 2 { + return Err(HELP.to_string()); + } + let (mut cell, mut carrier) = (None, None); + let mut names = BTreeMap::new(); + let mut i = 2; + while i < args.len() { + match args[i].to_str() { + Some("--cell") => cell = Some(value(args, &mut i)?), + Some("--carrier") => carrier = Some(parse_layer(&value(args, &mut i)?)?), + Some("--name") => { + let (pair, name) = parse_layer_name(&value(args, &mut i)?)?; + if names.get(&pair).is_some_and(|old| old != &name) { + return Err("conflicting --name arguments".to_string()); + } + names.insert(pair, name); + } + _ => { + return Err( + "name-layers requires --cell, --carrier and --name arguments".to_string(), + ); + } + } + i += 1; + } + if names.is_empty() { + return Err("provide at least one --name".to_string()); + } + let input = fs::read(&args[0]).map_err(|e| format!("{:?}: {e}", args[0]))?; + let output = write_layer_names( + &input, + &cell.ok_or("provide --cell")?, + carrier.ok_or("provide --carrier")?, + &names, + )?; + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&args[1]) + .map_err(|e| format!("{:?}: {e}", args[1]))?; + if let Err(e) = file.write_all(&output).and_then(|_| file.sync_all()) { + drop(file); + let _ = fs::remove_file(&args[1]); + return Err(e.to_string()); + } + Ok(0) +} + +fn stdout(output: &str) -> Result<(), String> { + io::stdout() + .lock() + .write_all(output.as_bytes()) + .map_err(|e| e.to_string()) +} + +fn run() -> Result { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + if args.is_empty() || args[0] == "--help" || args[0] == "-h" { + stdout(HELP)?; + return Ok(0); + } + let command = args[0].to_str().ok_or("invalid command")?; + if command == "name-layers" { + return name_layers(&args[1..]); + } + let expected = match command { + "dump" | "hierarchy" => 1, + "diff" => 2, + "git-diff" => 7, + _ => return Err(HELP.to_string()), + }; + let compare = command == "diff" || command == "git-diff"; + let mut scope = Scope::default(); + let mut show = DisplayFilter::default(); + let mut raw = false; + let mut format = if compare { + "none".to_string() + } else { + "ascii".to_string() + }; + let mut max_changes = 100; + let mut depth = 8; + let mut paths = Vec::new(); + let mut literal = false; + let mut i = 1; + while i < args.len() { + if literal { + paths.push(args[i].clone()); + i += 1; + continue; + } + match args[i].to_str() { + Some("--") => literal = true, + Some("--help" | "-h") => { + stdout(HELP)?; + return Ok(0); + } + Some("--records") if command == "dump" => raw = true, + Some("--top") => scope.top = Some(value(&args, &mut i)?), + Some("--cell") => scope.cell = Some(value(&args, &mut i)?), + Some("--layer") => scope.layer = Some(parse_layer(&value(&args, &mut i)?)?), + Some("--show-cell") if compare => show.cell = Some(value(&args, &mut i)?), + Some("--show-layer") if compare => { + show.layer = Some(parse_layer(&value(&args, &mut i)?)?) + } + Some("--hierarchy") if compare => format = value(&args, &mut i)?, + Some("--format") if command == "hierarchy" => format = value(&args, &mut i)?, + Some("--max-changes") if compare => { + max_changes = value(&args, &mut i)? + .parse() + .map_err(|_| "invalid change limit")? + } + Some("--depth") if command != "dump" => { + depth = value(&args, &mut i)?.parse().map_err(|_| "invalid depth")? + } + Some(s) if s.starts_with('-') => return Err(format!("unknown option {s:?}")), + _ => paths.push(args[i].clone()), + } + i += 1; + } + if paths.len() != expected && !(command == "git-diff" && paths.len() == 9) { + return Err(HELP.to_string()); + } + if !matches!(format.as_str(), "ascii" | "mermaid" | "none") + || (command == "hierarchy" && format == "none") + { + return Err("format must be ascii or mermaid (diff also accepts none)".to_string()); + } + let read = |path: &OsString| fs::read(path).map_err(|e| format!("{path:?}: {e}")); + if raw { + if scope != Scope::default() { + return Err("record dumps do not accept object scope selectors".to_string()); + } + stdout(&dump_records(&read(&paths[0])?)?)?; + return Ok(0); + } + if !compare { + let bytes = read(&paths[0])?; + let doc = Document::parse(&bytes)?.selected(&scope, false)?; + let output = if command == "dump" { + doc.canonical_dump() + } else { + hierarchy(&doc, &doc, None, format == "mermaid", depth) + }; + stdout(&output)?; + if command == "hierarchy" { + for issue in &doc.issues { + eprintln!("INCOMPLETE: {issue}"); + } + } + return Ok(if doc.issues.is_empty() { 0 } else { 2 }); + } + let git = command == "git-diff"; + let old_missing = git && (paths[3] == "000000" || paths[3] == "."); + let new_missing = git && (paths[6] == "000000" || paths[6] == "."); + if old_missing && new_missing { + return Err("both Git revisions are absent".to_string()); + } + let old_bytes = if old_missing { + None + } else { + Some(read(&paths[if git { 1 } else { 0 }])?) + }; + let new_bytes = if new_missing { + None + } else { + Some(read(&paths[if git { 4 } else { 1 }])?) + }; + let old = old_bytes.as_ref().map(|b| Document::parse(b)).transpose()?; + let new = new_bytes.as_ref().map(|b| Document::parse(b)).transpose()?; + let old = old.unwrap_or_else(|| new.as_ref().unwrap().empty_like()); + let new = new.unwrap_or_else(|| old.empty_like()); + scope.validate_pair(&old, &new)?; + let old = old.selected(&scope, true)?; + let new = new.selected(&scope, true)?; + let diff = Comparison::between(&old, &new); + let mut output = String::new(); + if git { + if paths.len() == 9 { + output.push_str(&format!("layout {:?} -> {:?}\n", paths[0], paths[7])); + } else { + output.push_str(&format!("layout {:?}\n", paths[0])); + } + if old_missing { + output.push_str("layout added\n"); + } else if new_missing { + output.push_str("layout deleted\n"); + } + if paths[3] != paths[6] { + output.push_str(&format!("mode {:?} -> {:?}\n", paths[3], paths[6])); + } + } + output.push_str(&diff.text_filtered(max_changes, &show)); + if format != "none" { + if format == "mermaid" { + output.push_str("```mermaid\n"); + } + output.push_str(&hierarchy( + &old, + &new, + Some(&diff), + format == "mermaid", + depth, + )); + if format == "mermaid" { + output.push_str("```\n"); + } + } + stdout(&output)?; + // Git's external driver expects successful rendering for either equality + // or differences. Actual comparison/input failures remain nonzero. + Ok(if git && diff.exit_code() == 1 { + 0 + } else { + diff.exit_code() + }) +} + +fn main() -> ExitCode { + match run() { + Ok(status) => ExitCode::from(status), + Err(message) => { + eprintln!("klamath: {message}"); + ExitCode::from(2) + } + } +} diff --git a/src/elements.rs b/src/elements.rs index e42e3f8..9541b5d 100644 --- a/src/elements.rs +++ b/src/elements.rs @@ -71,6 +71,18 @@ struct ARefRecord { properties: Vec, } +#[derive(Clone)] +pub struct ScanRefRecord { + pub target_id: u32, + pub invert_y: bool, + pub scale: f64, + pub angle_rad: f64, + pub xy: u64, + pub xy0: u64, + pub xy1: u64, + pub counts: u32, +} + enum RefRecord { SRef(SRefRecord), ARef(ARefRecord), @@ -78,6 +90,7 @@ enum RefRecord { const UNIT_COUNTS: u32 = (1_u32 << 16) | 1_u32; +const ZERO_XY: u64 = 0; fn layer_id_for( @@ -280,6 +293,38 @@ pub fn read_elements<'a>( } +pub fn scan_elements<'a>( + input: &'a [u8], + names: &mut HashMap, + ) -> IResult<'a, Vec> { + let mut input = input; + let mut refs = Vec::::new(); + let (_, mut header) = RecordHeader::read(input)?; + while header.tag != records::RTAG_ENDSTR { + (input, _) = match header.tag { + records::RTAG_SREF | records::RTAG_AREF => { + let (next_input, ref_record) = read_ref(input, header.tag, names)?; + refs.push(scan_ref_from_record(ref_record)); + (next_input, ()) + }, + records::RTAG_BOUNDARY + | records::RTAG_PATH + | records::RTAG_NODE + | records::RTAG_BOX + | records::RTAG_TEXT => skip_element(input)?, + _ => { + let result = take_bytes(input, header.data_size + 4)?; + (result.0, ()) + } + }; + (_, header) = RecordHeader::read(input)?; + } + refs.sort_by_key(|scan_ref| scan_ref.target_id); + (input, _) = take_bytes(input, 4_usize)?; + Ok((input, refs)) +} + + fn append_sref( sref_builder: &mut DListBuilder, sref: SRefRecord, @@ -301,6 +346,45 @@ fn append_sref( } +fn scan_ref_from_record(ref_record: RefRecord) -> ScanRefRecord { + match ref_record { + RefRecord::SRef(sref) => ScanRefRecord { + target_id: sref.target_id, + invert_y: sref.invert_y, + scale: sref.scale, + angle_rad: sref.angle_rad, + xy: sref.xy, + xy0: ZERO_XY, + xy1: ZERO_XY, + counts: UNIT_COUNTS, + }, + RefRecord::ARef(aref) => ScanRefRecord { + target_id: aref.target_id, + invert_y: aref.invert_y, + scale: aref.scale, + angle_rad: aref.angle_rad, + xy: aref.xy, + xy0: aref.xy0, + xy1: aref.xy1, + counts: aref.counts, + }, + } +} + + +fn skip_element<'a>(input: &'a [u8]) -> IResult<'a, ()> { + let mut input = input; + loop { + let (next_input, header) = RecordHeader::read(input)?; + let (next_input, _) = take_bytes(next_input, header.data_size)?; + input = next_input; + if header.tag == ENDEL::tag() { + return Ok((input, ())); + } + } +} + + fn append_aref( aref_builder: &mut DListBuilder, aref: ARefRecord, @@ -802,6 +886,9 @@ fn read_ref<'a>( angle_rad = _angle_deg.to_radians(); }, records::RTAG_COLROW => { + if header.data_size != 4 { + return fail(input, "COLROW must contain two counts".to_string()); + } let mut _colrow; (input, _colrow) = COLROW::read_data(input, header.data_size)?; colrow = Some((_colrow.next().unwrap(), _colrow.next().unwrap())); @@ -815,6 +902,10 @@ fn read_ref<'a>( (input, header) = RecordHeader::read(input)?; } + let expected_xy_size = if is_aref { 24 } else { 8 }; + if header.data_size != expected_xy_size { + return fail(input, format!("Expected {expected_xy_size} bytes of reference coordinates, got {}", header.data_size)); + } let (input, mut xy_iter) = XY::read_data(input, header.data_size)?; let xx = xy_iter.next().unwrap(); let yy = xy_iter.next().unwrap(); @@ -826,11 +917,20 @@ fn read_ref<'a>( return fail(input, "AREF without COLROW before XY".to_string()) } let (count0, count1) = colrow.unwrap(); + if count0 <= 0 || count1 <= 0 { + return fail(input, "AREF column and row counts must be positive".to_string()); + } - let x0a = (xy_iter.next().unwrap() - xx) / (count0 as i32); - let y0a = (xy_iter.next().unwrap() - yy) / (count0 as i32); - let x1a = (xy_iter.next().unwrap() - xx) / (count1 as i32); - let y1a = (xy_iter.next().unwrap() - yy) / (count1 as i32); + let pitch = |end: i32, origin: i32, count: i16| { + let value = (i64::from(end) - i64::from(origin)) / i64::from(count); + i32::try_from(value).map_err(|_| (input, crate::basic::ErrType::Failed( + "AREF pitch exceeds signed 32-bit coordinate range".to_string() + ))) + }; + let x0a = pitch(xy_iter.next().unwrap(), xx, count0)?; + let y0a = pitch(xy_iter.next().unwrap(), yy, count0)?; + let x1a = pitch(xy_iter.next().unwrap(), xx, count1)?; + let y1a = pitch(xy_iter.next().unwrap(), yy, count1)?; let xy0a = ((x0a as u32 as u64) << 32) | (y0a as u32 as u64); let xy1a = ((x1a as u32 as u64) << 32) | (y1a as u32 as u64); diff --git a/src/iface.rs b/src/iface.rs deleted file mode 100644 index 6e88dce..0000000 --- a/src/iface.rs +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Shapes: - * layer, dtype (2x i16) - * bounds (4x i32) - * offset/ptr (usize) - * cell_id (usize) - * - * Cell: - * name (??) - * offset (usize) - * len (usize) - * - * Refs: - * name_ind (usize) - * invert (bool) - * mag (f64) - * angle (f64) - * offset/ptr (usize) - * - */ - - -use arrow; -use arrow::array::{LargeStringArray, DictionaryArray, UInt64Array, Int32Array, UInt16Array} -use arrow::builder::{LargeStringDictionaryBuilder, UInt64Builder, Int32Builder, Int64Builder, BooleanBuilder}; -use library::FileHeader; - -use std::collections::HashMap; - -pub use crate::record; -pub use crate::record::{RecordHeader, Record}; -pub use crate::records; -pub use crate::elements; -pub use crate::elements::{Element}; -pub use crate::basic::{IResult, OResult, take_bytes, fail}; - - - -const DEFAULT_DATE: [i16; 6] = [1900, 0, 0, 0, 0, 0]; - -#[derive(Debug, Clone)] -pub struct LibraryBuilder { - cell_name: LargeStringDictionaryBuilder, - cell_offset: UInt64Builder, - - ref_parent: UInt64Builder, - ref_name: LargeStringDictionaryBuilder, - ref_mirror: BooleanBuilder, - ref_mag: Float64Builder, - ref_angle: Float64Builder, - ref_offset: UInt64Builder, - - shape_parent: UInt64Builder, - shape_offset: UInt64Builder, - shape_type: UInt8Builder, - shape_layer: UInt16Builder, - shape_dtype: UInt16Builder, - shape_xmin: Int32Builder, - shape_ymin: Int32Builder, - shape_xmax: Int32Builder, - shape_ymax: Int32Builder, - shape_data: LargeListArrayBuilder, - - text_parent: UInt64Builder, - text_string: LargeStringDictionaryBuilder, - text_x: Int32Builder, - text_y: Int32Builder, - - - - boundaries: Vec, - paths: Vec, - nodes: Vec, - boxes: Vec, - texts: Vec, - refs: Vec, -} - -impl Cell { - /// Build an empty cell - pub fn new(name: Vec) -> Self { - Cell{ - name: name, - boundaries: Vec::new(), - paths: Vec::new(), - nodes: Vec::new(), - boxes: Vec::new(), - texts: Vec::new(), - refs: Vec::new(), - } - } - - /// Skip to the next structure and attempt to read it. - /// - /// Args: - /// input: Seekable input to read from. - /// - /// Returns: - /// (name, elements) if a structure was found. - /// None if no structure was found before the end of the library. - /// - pub fn read(input: &[u8]) -> IResult> { - let (input, success) = records::BGNSTR::skip_past(input)?; - if !success { - return Ok((input, None)) - } - - let (input, name) = records::STRNAME::read(input)?; - let mut cell = Cell::new(name); - let (input, _) = cell.read_elements(input)?; - Ok((input, Some(cell))) - } - - /// Read elements from the input until an ENDSTR - /// record is encountered. The ENDSTR record is also - /// consumed. - /// - /// Args: - /// input: Seekable input to read from. - /// - /// Returns: - /// List of element objects. - /// - pub fn read_elements<'a>(&mut self, input: &'a [u8]) -> IResult<'a, ()> { - let (mut input, mut header) = RecordHeader::read(input)?; - while header.tag != records::RTAG_ENDSTR { - match header.tag { - records::RTAG_BOUNDARY => { - let boundary; - (input, _) = records::BOUNDARY::read(input)?; - (input, boundary) = elements::Boundary::read(input)?; - self.boundaries.push(boundary); - }, - records::RTAG_PATH => { - let path; - (input, _) = records::PATH::read(input)?; - (input, path) = elements::Path::read(input)?; - self.paths.push(path); - }, - records::RTAG_NODE => { - let node; - (input, _) = records::NODE::read(input)?; - (input, node) = elements::Node::read(input)?; - self.nodes.push(node); - }, - records::RTAG_BOX => { - let gds_box; - (input, _) = records::BOX::read(input)?; - (input, gds_box) = elements::GDSBox::read(input)?; - self.boxes.push(gds_box); - }, - records::RTAG_TEXT => { - let txt; - (input, _) = records::TEXT::read(input)?; - (input, txt) = elements::Text::read(input)?; - self.texts.push(txt); - }, - records::RTAG_SREF => { - let sref; - (input, _) = records::SREF::read(input)?; - (input, sref) = elements::Reference::read(input)?; - self.refs.push(sref); - }, - records::RTAG_AREF => { - let aref; - (input, _) = records::AREF::read(input)?; - (input, aref) = elements::Reference::read(input)?; - self.refs.push(aref); - }, - _ => { - // don't care, skip - (input, _) = take_bytes(input, header.data_size)?; - } - } - (input, header) = RecordHeader::read(input)?; - } - Ok((input, ())) - } - - /// - /// Write a structure to the provided input. - /// - /// Args: - /// name: Structure name (ascii-encoded). - /// elements: List of Elements containing the geometry and text in this struct. - /// cre_time: Creation time (optional). - /// mod_time: Modification time (optional). - /// - /// Return: - /// Number of bytes written - /// - pub fn write( - &self, - ww: &mut W, - cre_time: Option<[i16; 6]>, - mod_time: Option<[i16; 6]>, - ) -> OResult { - let mut size = 0; - size += records::BGNSTR::write(ww, &[cre_time.unwrap_or(DEFAULT_DATE), - mod_time.unwrap_or(DEFAULT_DATE)])?; - size += records::STRNAME::write(ww, &self.name)?; - size += self.write_elements(ww)?; - size += records::ENDSTR::write(ww, &())?; - Ok(size) - } - - pub fn write_elements(&self, ww: &mut W) -> OResult { - let mut size = 0; - for boundary in &self.boundaries { - size += boundary.write(ww)?; - } - for path in &self.paths { - size += path.write(ww)?; - } - for node in &self.nodes { - size += node.write(ww)?; - } - for gds_box in &self.boxes { - size += gds_box.write(ww)?; - } - for text in &self.texts { - size += text.write(ww)?; - } - for reference in &self.refs { - size += reference.write(ww)?; - } - Ok(size) - } -} - - - -pub fn make_table(input: &[u8]) -> IResult, usize>> { - let input_size = input.len(); - let mut names = LargeStringDictionaryBuilder::new(); - let mut positions = UInt64Builder::new(); - - let (mut input, mut header) = RecordHeader::read(input)?; - while header.tag != records::RTAG_ENDLIB { - (input, let record_bytes) = take_bytes(input, header.data_size)?; - if header.tag == records::RTAG_BGNSTR { - let position = input_size - input.len(); - - let name; - (input, name) = records::STRNAME::read(record_bytes)?; - - names.append(name); - positions.append(position); - - - pub fn read_elements<'a>(&mut self, input: &'a [u8]) -> IResult<'a, ()> { - let (mut input, mut header) = RecordHeader::read(input)?; - while header.tag != records::RTAG_ENDSTR { - match header.tag { - records::RTAG_BOUNDARY => { - let boundary; - (input, _) = records::BOUNDARY::read(input)?; - (input, boundary) = elements::Boundary::read(input)?; - self.boundaries.push(boundary); - }, - records::RTAG_PATH => { - let path; - (input, _) = records::PATH::read(input)?; - (input, path) = elements::Path::read(input)?; - self.paths.push(path); - }, - records::RTAG_NODE => { - let node; - (input, _) = records::NODE::read(input)?; - (input, node) = elements::Node::read(input)?; - self.nodes.push(node); - }, - records::RTAG_BOX => { - let gds_box; - (input, _) = records::BOX::read(input)?; - (input, gds_box) = elements::GDSBox::read(input)?; - self.boxes.push(gds_box); - }, - records::RTAG_TEXT => { - let txt; - (input, _) = records::TEXT::read(input)?; - (input, txt) = elements::Text::read(input)?; - self.texts.push(txt); - }, - records::RTAG_SREF => { - let sref; - (input, _) = records::SREF::read(input)?; - (input, sref) = elements::Reference::read(input)?; - self.refs.push(sref); - }, - records::RTAG_AREF => { - let aref; - (input, _) = records::AREF::read(input)?; - (input, aref) = elements::Reference::read(input)?; - self.refs.push(aref); - }, - _ => { - // don't care, skip - (input, _) = take_bytes(input, header.data_size)?; - } - } - (input, header) = RecordHeader::read(input)?; - } - Ok((input, ())) - } - - - - } - (input, header) = RecordHeader::read(input)?; - } - Ok((input, positions)) -} - - - - -pub struct References { - invert_y: Vec, - mag_and_angle_deg: Vec, - xy: Vec, - - names: Vec, - name_inds: Vec, - - has_prop: Vec, - has_rep: Vec, -} - -pub struct Repetitions { - colrow_vecs: Vec, // 4 per - colrow_counts: Vec, // 2 per -} - -pub struct Shapes { - layers_and_dtypes: Vec, // 2 per - xy: Vec, // variable per - has_prop: Vec, -} - - - -pub struct References { - invert_y: bool, - mag: f64, - angle_deg: f64, - - xy: (i32, i32), - - // Use id to look up these... maybe include has_props and has_rep? - struct_name: Vec, - properties: HashMap::>, - - col_vec: (i32 i32), - row_vec: (i32, i32), - colrow: (i16, i16), -} - -pub struct Boundary { - /// (layer, data_type) tuple - layer: (i16, i16), - /// Ordered vertices of the shape. First and last points should be identical. Order x0, y0, x1,... - xy: Vec, - /// Properties for the element. - properties: HashMap::>, -} - -pub struct Path { - /// (layer, data_type) tuple - layer: (i16, i16), - /// End-cap type (0: flush, 1: circle, 2: square, 4: custom) - path_type: i16, - /// Path width - width: i32, - /// Extension when using path_type=4. Ignored otherwise. - extension: (i32, i32), - /// Path centerline coordinates. [x0, y0, x1, y1,...] - xy: Vec, - /// Properties for the element. - properties: HashMap::>, -} - -pub struct GDSBox { - /// (layer, box_type) tuple - layer: (i16, i16), - /// Box coordinates (5 pairs) - xy: Vec, - /// Properties for the element. - properties: HashMap::>, -} -pub struct Node { - /// (layer, box_type) tuple - layer: (i16, i16), - /// 1-50 pairs of coordinates. - xy: Vec, - /// Properties for the element. - properties: HashMap::>, -} -pub struct Text { - /// (layer, node_type) tuple - layer: (i16, i16), - - /// Bit array. Default all zeros. - /// bits 0-1: 00 left/01 center/10 right - /// bits 2-3: 00 top/01 middle/10 bottom - /// bits 4-5: font number - presentation: [bool; 16], - - /// Default 0 - path_type: i16, - /// Default 0 - width: i32, - /// Vertical inversion. Default false. - invert_y: bool, - /// Scaling factor. Default 1. - mag: f64, - /// Rotation (ccw). Default 0. - angle_deg: f64, - /// Position (1 pair only) - xy: Vec, - /// Text content - string: Vec, - /// Properties for the element. - properties: HashMap::> -} diff --git a/src/lib.rs b/src/lib.rs index 39081ab..0698e3e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,42 +5,215 @@ pub mod record; pub mod records; pub mod elements; pub mod library; +pub mod review; -use crate::library::read_library; +use crate::library::{read_library, read_selected_library, scan_library}; use byteorder::{ByteOrder, BigEndian}; +use std::any::Any; +use std::cell::RefCell; use std::mem::size_of; -use std::ffi::{CStr, OsStr, c_char}; -use std::os::unix::ffi::OsStrExt; +use std::ffi::{CStr, CString, c_char}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::{Path, PathBuf}; +use std::ptr; +#[cfg(unix)] +use std::os::unix::ffi::OsStringExt; use std::str; use std::fs; -use std::path::Path; +use std::slice; use arrow::ffi::{to_ffi, FFI_ArrowArray, FFI_ArrowSchema}; -use arrow::array::Array; +use arrow::array::{Array, StructArray}; +thread_local! { + static LAST_ERROR: RefCell> = const { RefCell::new(None) }; +} + + +fn clear_last_error() { + LAST_ERROR.with(|last_error| *last_error.borrow_mut() = None); +} + + +fn set_last_error(message: String) -> i32 { + let sanitized = message.replace('\0', "\\0"); + LAST_ERROR.with(|last_error| *last_error.borrow_mut() = Some(CString::new(sanitized).unwrap())); + -1 +} + + +fn describe_panic(payload: Box) -> String { + if let Some(message) = payload.downcast_ref::<&str>() { + (*message).to_string() + } else if let Some(message) = payload.downcast_ref::() { + message.clone() + } else { + "unexpected panic".to_string() + } +} + + +fn describe_parse_error(input: &[u8], (remaining, reason): (&[u8], crate::basic::ErrType)) -> String { + // Selected-cell errors may contain a bounded range rather than a file suffix. + let offset = remaining.as_ptr() as usize - input.as_ptr() as usize; + let message = match reason { + crate::basic::ErrType::Failed(message) => message, + crate::basic::ErrType::Incomplete(Some(size)) => format!("Unexpected end of input; need {size} bytes"), + crate::basic::ErrType::Incomplete(None) => "Unexpected end of input".to_string(), + }; + format!("at byte {offset}: {message}") +} + + +fn export_struct_array( + op_name: &str, + arr: *mut FFI_ArrowArray, + schema: *mut FFI_ArrowSchema, + build: impl FnOnce() -> Result, + ) -> i32 { + clear_last_error(); + if arr.is_null() || schema.is_null() { + return set_last_error(format!("{op_name}: Arrow output pointer was null")); + } + match catch_unwind(AssertUnwindSafe(build)) { + Ok(Ok(struct_arr)) => match to_ffi(&struct_arr.to_data()) { + Ok((ffi_arr, ffi_schema)) => { + unsafe { + *arr = ffi_arr; + *schema = ffi_schema; + } + 0 + }, + Err(err) => set_last_error(format!("{op_name}: failed to export Arrow data: {err}")), + }, + Ok(Err(message)) => set_last_error(format!("{op_name}: {message}")), + Err(payload) => set_last_error(format!("{op_name}: {}", describe_panic(payload))), + } +} + + +fn pathbuf_from_c(cpath: *const c_char) -> Result { + if cpath.is_null() { + return Err("path pointer was null".to_string()); + } + + let cstr = unsafe { CStr::from_ptr(cpath) }; + #[cfg(unix)] + { + return Ok(PathBuf::from(std::ffi::OsString::from_vec(cstr.to_bytes().to_vec()))); + } + #[cfg(windows)] + { + let ustr = str::from_utf8(cstr.to_bytes()) + .map_err(|_| "Non-UTF8 paths are not supported".to_string())?; + return Ok(PathBuf::from(ustr)); + } + #[allow(unreachable_code)] + Err("Unsupported OS".to_string()) +} + + +/// Return this thread's last parser error, or null if its last call succeeded. +/// The returned string remains valid until this thread's next parser call or exit. +#[unsafe(no_mangle)] +pub extern "C" fn last_error_message() -> *const c_char { + LAST_ERROR.with(|last_error| last_error.borrow() + .as_ref() + .map_or(ptr::null(), |message| message.as_ptr())) +} + + +/// Read a GDSII file and export its Arrow data. Return 0 on success or -1 on error. +/// +/// # Safety +/// `cpath` must point to a null-terminated path. Non-null output pointers must +/// point to initialized, writable Arrow FFI structures. Null pointers are rejected. #[unsafe(no_mangle)] pub unsafe extern "C" fn read_path( cpath: *const c_char, arr: *mut FFI_ArrowArray, schema: *mut FFI_ArrowSchema, - ) { - let cstr = unsafe { CStr::from_ptr(cpath) }; - let path: &Path; - if cfg!(unix) { - let osstr = OsStr::from_bytes(cstr.to_bytes()); - path = osstr.as_ref(); - } else if cfg!(windows) { - let ustr = str::from_utf8(cstr.to_bytes()).expect("Non-UTF8 paths are not supported"); - path = ustr.as_ref(); - } else { - panic!("Unsupported OS"); - } + ) -> i32 { + export_struct_array("read_path", arr, schema, || { + let path = pathbuf_from_c(cpath)?; + let input = fs::read(Path::new(&path)) + .map_err(|err| format!("file read failed for {}: {err}", path.display()))?; + let (_input, struct_arr) = read_library(&input) + .map_err(|err| format!("read failed {}", describe_parse_error(&input, err)))?; + Ok(struct_arr) + }) +} - let input = fs::read(path).expect("File read failed"); - let (_input, struct_arr) = read_library(&input).expect("Read failed"); - unsafe { (*arr, *schema) = to_ffi(&struct_arr.to_data()).unwrap(); } + +unsafe fn input_slice<'a, T>(data: *const T, size: usize, name: &str) -> Result<&'a [T], String> { + if size == 0 { + return Ok(&[]); + } + if data.is_null() { + return Err(format!("{name} pointer was null")); + } + if !data.is_aligned() { + return Err(format!("{name} pointer was misaligned")); + } + if size.checked_mul(size_of::()).is_none_or(|bytes| bytes > isize::MAX as usize) { + return Err(format!("{name} length is too large")); + } + Ok(unsafe { slice::from_raw_parts(data, size) }) +} + + +/// Scan cell ranges and hierarchy references. Return 0 on success or -1 on error. +/// +/// # Safety +/// Non-null `data` must point to `size` readable bytes. Null is allowed when +/// `size` is zero. Output pointers have the same requirements as `read_path`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn scan_bytes( + data: *const u8, + size: usize, + arr: *mut FFI_ArrowArray, + schema: *mut FFI_ArrowSchema, + ) -> i32 { + export_struct_array("scan_bytes", arr, schema, || { + let input = unsafe { input_slice(data, size, "data") }?; + let (_input, struct_arr) = scan_library(input) + .map_err(|err| format!("scan failed {}", describe_parse_error(input, err)))?; + Ok(struct_arr) + }) +} + + +/// Read the cells in half-open byte ranges. Return 0 on success or -1 on error. +/// +/// # Safety +/// `data` has the same requirements as `scan_bytes`. Non-null `ranges` must +/// point to `range_count * 2` readable, aligned u64 values, alternating start +/// and end offsets. Null is allowed for zero ranges. Output pointers have the +/// same requirements as `read_path`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn read_cells_bytes( + data: *const u8, + size: usize, + ranges: *const u64, + range_count: usize, + arr: *mut FFI_ArrowArray, + schema: *mut FFI_ArrowSchema, + ) -> i32 { + export_struct_array("read_cells_bytes", arr, schema, || { + let input = unsafe { input_slice(data, size, "data") }?; + let range_size = range_count.checked_mul(2) + .ok_or_else(|| "range count is too large".to_string())?; + let flat_ranges = unsafe { input_slice(ranges, range_size, "ranges") }?; + let cell_ranges: Vec<(u64, u64)> = flat_ranges + .chunks_exact(2) + .map(|chunk| (chunk[0], chunk[1])) + .collect(); + let (_input, struct_arr) = read_selected_library(input, &cell_ranges) + .map_err(|err| format!("selected-cell read failed {}", describe_parse_error(input, err)))?; + Ok(struct_arr) + }) } @@ -49,12 +222,15 @@ macro_rules! impl_i16be { { let sl = unsafe { std::slice::from_raw_parts_mut($arr, $size) }; for xx in sl.iter_mut() { - if *xx < i16::MIN as $tt { return *xx } - if *xx > i16::MAX as $tt { return *xx } + // All source types represent the target bounds exactly in f64. + let value = *xx as f64; + if !value.is_finite() || value < i16::MIN as f64 || value > i16::MAX as f64 { + return *xx; + } let mut buf = [0; size_of::<$tt>()]; BigEndian::write_i16(&mut buf, *xx as i16); - *xx = <$tt>::from_le_bytes(buf); + *xx = <$tt>::from_ne_bytes(buf); } 0 as $tt } @@ -67,12 +243,14 @@ macro_rules! impl_i32be { { let sl = unsafe { std::slice::from_raw_parts_mut($arr, $size) }; for xx in sl.iter_mut() { - if *xx < i32::MIN as $tt { return *xx } - if *xx > i32::MAX as $tt { return *xx } + let value = *xx as f64; + if !value.is_finite() || value < i32::MIN as f64 || value > i32::MAX as f64 { + return *xx; + } let mut buf = [0; size_of::<$tt>()]; BigEndian::write_i32(&mut buf, *xx as i32); - *xx = <$tt>::from_le_bytes(buf); + *xx = <$tt>::from_ne_bytes(buf); } 0 as $tt } @@ -116,4 +294,3 @@ pub unsafe extern "C" fn u16_to_i16(arr: *mut u16, size: usize) -> u16 { impl_i1 #[unsafe(no_mangle)] pub unsafe extern "C" fn i16_to_i16(arr: *mut i16, size: usize) -> i16 { impl_i16be!(i16, arr, size) } - diff --git a/src/library.rs b/src/library.rs index bf4c890..862c85f 100644 --- a/src/library.rs +++ b/src/library.rs @@ -9,7 +9,7 @@ pub use crate::record; pub use crate::record::{RecordHeader, Record}; pub use crate::records; pub use crate::elements; -pub use crate::elements::{read_elements, DListBuilder, FListBuilder}; +pub use crate::elements::{read_elements, scan_elements, DListBuilder, FListBuilder, ScanRefRecord}; pub use crate::basic::{IResult, OResult, take_bytes, fail}; use std::string::String; @@ -18,7 +18,7 @@ use std::sync::Arc; use arrow::datatypes::{DataType, Field, Fields}; use arrow::array::{ - StructBuilder, StringBuilder, UInt64Builder, UInt32Builder, Int16Builder, Float64Builder, + BooleanBuilder, StructBuilder, StringBuilder, UInt64Builder, UInt32Builder, Int16Builder, Float64Builder, StructArray, }; @@ -98,9 +98,38 @@ impl FileHeader { } -pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { - let input_size = input.len(); +fn make_name_list_type() -> DataType { + DataType::List(Arc::new( + Field::new_list_field(DataType::Utf8, false) + )) +} + +fn make_time_type() -> DataType { + DataType::FixedSizeList(Arc::new( + Field::new_list_field(DataType::Int16, false), + ), + 6, + ) +} + + +fn make_top_level_builder(cells_field: Field, extra_fields: Vec) -> StructBuilder { + let mut fields = vec![ + Field::new("meters_per_db_unit", DataType::Float64, false), + Field::new("user_units_per_db_unit", DataType::Float64, false), + Field::new("lib_name", DataType::Utf8, false), + Field::new("mod_time", make_time_type(), false), + Field::new("acc_time", make_time_type(), false), + cells_field, + Field::new("cell_names", make_name_list_type(), false), + ]; + fields.extend(extra_fields); + StructBuilder::from_fields(fields, 0) +} + + +fn make_library_builder() -> StructBuilder { let property_t = DataType::Struct(Fields::from(vec![ Field::new("key", DataType::Int16, false), Field::new("value", DataType::Utf8, false), @@ -197,7 +226,7 @@ pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { Field::new("path_type", DataType::Int16, true), Field::new("extension_start", DataType::Int32, true), Field::new("extension_end", DataType::Int32, true), - Field::new("width", DataType::Int32, false), + Field::new("width", DataType::Int32, true), Field::new("xy", coords_t.clone(), false), Field::new("properties", property_list_t.clone(), true), ])); @@ -248,20 +277,10 @@ pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { Field::new_list_field(boxnode_struct_t, false) )); - let name_list_t = DataType::List(Arc::new( - Field::new_list_field(DataType::Utf8, false) - )); - let layer_list_t = DataType::List(Arc::new( Field::new_list_field(DataType::UInt32, false) )); - let time_t = DataType::FixedSizeList(Arc::new( - Field::new_list_field(DataType::Int16, false), - ), - 6, - ); - let cell_struct_t = DataType::Struct(Fields::from(vec![ Field::new("id", DataType::UInt32, false), Field::new("file_offset", DataType::UInt64, false), @@ -282,26 +301,59 @@ pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { Field::new_list_field(cell_struct_t, false) )); - let mut lib_builder = StructBuilder::from_fields(vec![ - Field::new("meters_per_db_unit", DataType::Float64, false), - Field::new("user_units_per_db_unit", DataType::Float64, false), - Field::new("lib_name", DataType::Utf8, false), - Field::new("mod_time", time_t.clone(), false), - Field::new("acc_time", time_t.clone(), false), - Field::new("cells", cells_list_t, false), - Field::new("cell_names", name_list_t, false), + make_top_level_builder( + Field::new("cells", cells_list_t, false), + vec![ Field::new("layers", layer_list_t, false), ], - 0, - ); + ) +} - let (input, header) = FileHeader::read(input)?; + +fn make_scan_builder() -> StructBuilder { + let scan_ref_struct_t = DataType::Struct(Fields::from(vec![ + Field::new("target", DataType::UInt32, false), + Field::new("invert_y", DataType::Boolean, false), + Field::new("scale", DataType::Float64, false), + Field::new("angle_rad", DataType::Float64, false), + Field::new("xy", DataType::UInt64, false), + Field::new("xy0", DataType::UInt64, false), + Field::new("xy1", DataType::UInt64, false), + Field::new("counts", DataType::UInt32, false), + ])); + + let scan_ref_list_t = DataType::List(Arc::new( + Field::new_list_field(scan_ref_struct_t, false) + )); + + let scan_cell_struct_t = DataType::Struct(Fields::from(vec![ + Field::new("id", DataType::UInt32, false), + Field::new("struct_start_offset", DataType::UInt64, false), + Field::new("struct_end_offset", DataType::UInt64, false), + Field::new("refs", scan_ref_list_t, false), + ])); + + let scan_cells_list_t = DataType::List(Arc::new( + Field::new_list_field(scan_cell_struct_t, false) + )); + + make_top_level_builder( + Field::new("cells", scan_cells_list_t, false), + Vec::new(), + ) +} + + +fn append_file_header( + lib_builder: &mut StructBuilder, + header: &FileHeader, + ) { let dbu_builder = lib_builder.field_builder::(0).unwrap(); dbu_builder.append_value(header.meters_per_db_unit); let uu_builder = lib_builder.field_builder::(1).unwrap(); uu_builder.append_value(header.user_units_per_db_unit); let libname_builder = lib_builder.field_builder::(2).unwrap(); - libname_builder.append_value(String::from_utf8(header.name).unwrap()); + libname_builder.append_value(String::from_utf8(header.name.clone()).unwrap()); let mtl_builder = lib_builder.field_builder::(3).unwrap(); let mt_builder = mtl_builder.values().as_any_mut().downcast_mut::().unwrap(); mt_builder.append_values(&header.mod_time, &[true; 6]); @@ -310,47 +362,28 @@ pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { let at_builder = atl_builder.values().as_any_mut().downcast_mut::().unwrap(); at_builder.append_values(&header.acc_time, &[true; 6]); atl_builder.append(true); +} - let mut names = HashMap::::new(); - let mut layers = HashMap::::new(); - let cells_builder = lib_builder.field_builder::(5).unwrap(); - - let (mut input, mut header) = RecordHeader::read(input)?; - while header.tag != records::RTAG_ENDLIB { - (input, _) = take_bytes(input, header.data_size)?; - if header.tag == records::RTAG_BGNSTR { - let name_bytes; - (input, name_bytes) = records::STRNAME::read(input)?; - let name = String::from_utf8(name_bytes).unwrap(); - //println!("{name}"); - - let next_id = names.len(); - let id = names.entry(name).or_insert(next_id.try_into().unwrap()); - let position = input_size - input.len(); - - let cell_builder = cells_builder.values().as_any_mut().downcast_mut::().unwrap(); - let id_builder = cell_builder.field_builder::(0).unwrap(); - id_builder.append_value(*id); - - let offset_builder = cell_builder.field_builder::(1).unwrap(); - offset_builder.append_value(position.try_into().unwrap()); - - (input, _) = read_elements(input, cell_builder, &mut names, &mut layers)?; - - cell_builder.append(true); - } - (input, header) = RecordHeader::read(input)?; - } - cells_builder.append(true); +fn append_names( + lib_builder: &mut StructBuilder, + field_index: usize, + names: HashMap, + ) { let mut ids: HashMap = names.into_iter().map(|(kk, vv)| (vv, kk)).collect(); - let names_builder = lib_builder.field_builder::(6).unwrap(); + let names_builder = lib_builder.field_builder::(field_index).unwrap(); let name_builder = names_builder.values().as_any_mut().downcast_mut::().unwrap(); for id in 0..ids.len() { name_builder.append_value(ids.remove(&id.try_into().unwrap()).unwrap()); } names_builder.append(true); +} + +fn append_layers( + lib_builder: &mut StructBuilder, + layers: HashMap, + ) { let mut layer_ids: HashMap = layers.into_iter().map(|(kk, vv)| (vv, kk)).collect(); let layers_builder = lib_builder.field_builder::(7).unwrap(); let layer_builder = layers_builder.values().as_any_mut().downcast_mut::().unwrap(); @@ -358,6 +391,211 @@ pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { layer_builder.append_value(layer_ids.remove(&layer_id.try_into().unwrap()).unwrap()); } layers_builder.append(true); +} + + +fn append_scan_ref( + refs_builder: &mut DListBuilder, + scan_ref: ScanRefRecord, + ) { + let ref_builder = refs_builder.values().as_any_mut().downcast_mut::().unwrap(); + let target_builder = ref_builder.field_builder::(0).unwrap(); + target_builder.append_value(scan_ref.target_id); + let invert_builder = ref_builder.field_builder::(1).unwrap(); + invert_builder.append_value(scan_ref.invert_y); + let scale_builder = ref_builder.field_builder::(2).unwrap(); + scale_builder.append_value(scan_ref.scale); + let angle_builder = ref_builder.field_builder::(3).unwrap(); + angle_builder.append_value(scan_ref.angle_rad); + let xy_builder = ref_builder.field_builder::(4).unwrap(); + xy_builder.append_value(scan_ref.xy); + let xy0_builder = ref_builder.field_builder::(5).unwrap(); + xy0_builder.append_value(scan_ref.xy0); + let xy1_builder = ref_builder.field_builder::(6).unwrap(); + xy1_builder.append_value(scan_ref.xy1); + let counts_builder = ref_builder.field_builder::(7).unwrap(); + counts_builder.append_value(scan_ref.counts); + ref_builder.append(true); +} + + +fn intern_name(names: &mut HashMap, name: String) -> u32 { + let next_id = names.len(); + *names.entry(name).or_insert(next_id.try_into().unwrap()) +} + + +fn append_full_cell<'a>( + cells_builder: &mut DListBuilder, + names: &mut HashMap, + layers: &mut HashMap, + struct_input: &'a [u8], + id: u32, + file_offset: u64, + ) -> IResult<'a, ()> { + let cell_builder = cells_builder.values().as_any_mut().downcast_mut::().unwrap(); + let id_builder = cell_builder.field_builder::(0).unwrap(); + id_builder.append_value(id); + + let offset_builder = cell_builder.field_builder::(1).unwrap(); + offset_builder.append_value(file_offset); + + let (next_input, _) = read_elements(struct_input, cell_builder, names, layers)?; + cell_builder.append(true); + Ok((next_input, ())) +} + + +fn walk_structs<'a, F>( + input: &'a [u8], + base_offset: usize, + names: &mut HashMap, + mut on_struct: F, + ) -> IResult<'a, ()> +where + F: FnMut(&'a [u8], usize, u32, &mut HashMap) -> IResult<'a, ()>, +{ + let input_size = input.len(); + let (mut input, mut header) = RecordHeader::read(input)?; + while header.tag != records::RTAG_ENDLIB { + let record_start = base_offset + input_size - input.len() - 4; + (input, _) = take_bytes(input, header.data_size)?; + if header.tag == records::RTAG_BGNSTR { + let name_bytes; + (input, name_bytes) = records::STRNAME::read(input)?; + let name = String::from_utf8(name_bytes).unwrap(); + let id = intern_name(names, name); + let (next_input, ()) = on_struct(input, record_start, id, names)?; + input = next_input; + } + (input, header) = RecordHeader::read(input)?; + } + Ok((input, ())) +} + + +pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> { + let full_input_size = input.len(); + let mut lib_builder = make_library_builder(); + + let (input, header) = FileHeader::read(input)?; + append_file_header(&mut lib_builder, &header); + let base_offset = full_input_size - input.len(); + + let mut names = HashMap::::new(); + let mut layers = HashMap::::new(); + let cells_builder = lib_builder.field_builder::(5).unwrap(); + + let walk_input_size = input.len(); + let (input, ()) = walk_structs(input, base_offset, &mut names, |struct_input, _record_start, id, names| { + let position = base_offset + walk_input_size - struct_input.len(); + append_full_cell( + cells_builder, + names, + &mut layers, + struct_input, + id, + position.try_into().unwrap(), + ) + })?; + cells_builder.append(true); + + append_names(&mut lib_builder, 6, names); + append_layers(&mut lib_builder, layers); + + lib_builder.append(true); + let lib = lib_builder.finish(); + Ok((input, lib)) +} + + +/// Scan cell byte ranges and references without decoding geometry. +pub fn scan_library(input: &[u8]) -> IResult<'_, StructArray> { + let full_input_size = input.len(); + let mut lib_builder = make_scan_builder(); + + let (input, header) = FileHeader::read(input)?; + append_file_header(&mut lib_builder, &header); + let base_offset = full_input_size - input.len(); + + let mut names = HashMap::::new(); + let cells_builder = lib_builder.field_builder::(5).unwrap(); + + let walk_input_size = input.len(); + let (input, ()) = walk_structs(input, base_offset, &mut names, |struct_input, record_start, id, names| { + let (after_cell, refs) = scan_elements(struct_input, names)?; + let struct_end = base_offset + walk_input_size - after_cell.len(); + let cell_builder = cells_builder.values().as_any_mut().downcast_mut::().unwrap(); + let id_builder = cell_builder.field_builder::(0).unwrap(); + id_builder.append_value(id); + + let start_builder = cell_builder.field_builder::(1).unwrap(); + start_builder.append_value(record_start.try_into().unwrap()); + + let end_builder = cell_builder.field_builder::(2).unwrap(); + end_builder.append_value(struct_end.try_into().unwrap()); + + let refs_builder = cell_builder.field_builder::(3).unwrap(); + for scan_ref in refs { + append_scan_ref(refs_builder, scan_ref); + } + refs_builder.append(true); + cell_builder.append(true); + Ok((after_cell, ())) + })?; + cells_builder.append(true); + + append_names(&mut lib_builder, 6, names); + + lib_builder.append(true); + let lib = lib_builder.finish(); + Ok((input, lib)) +} + + +/// Read exact half-open cell ranges returned by `scan_library`, in caller order. +/// Each range includes BGNSTR through ENDSTR. Cell and layer IDs are local to +/// this result. This random-access operation returns the original input slice +/// as its remainder; it does not advance a sequential parsing cursor. +pub fn read_selected_library<'a>(input: &'a [u8], ranges: &[(u64, u64)]) -> IResult<'a, StructArray> { + let mut lib_builder = make_library_builder(); + let (_, header) = FileHeader::read(input)?; + append_file_header(&mut lib_builder, &header); + + let mut names = HashMap::::new(); + let mut layers = HashMap::::new(); + let cells_builder = lib_builder.field_builder::(5).unwrap(); + + for (start_u64, end_u64) in ranges { + if start_u64 >= end_u64 || *end_u64 > input.len() as u64 { + return fail(input, format!("Cell byte range out of bounds: [{start_u64}, {end_u64})")); + } + let start = usize::try_from(*start_u64).unwrap(); + let end = usize::try_from(*end_u64).unwrap(); + + let struct_input = &input[start..end]; + let (struct_input, _) = records::BGNSTR::read(struct_input)?; + let (struct_input, name_bytes) = records::STRNAME::read(struct_input)?; + let name = String::from_utf8(name_bytes).unwrap(); + let file_offset = end - struct_input.len(); + + let id = intern_name(&mut names, name); + let (remaining_struct, _) = append_full_cell( + cells_builder, + &mut names, + &mut layers, + struct_input, + id, + file_offset.try_into().unwrap(), + )?; + if !remaining_struct.is_empty() { + return fail(remaining_struct, "Cell byte range extends past ENDSTR".to_string()); + } + } + cells_builder.append(true); + + append_names(&mut lib_builder, 6, names); + append_layers(&mut lib_builder, layers); lib_builder.append(true); let lib = lib_builder.finish(); diff --git a/src/record.rs b/src/record.rs index 8bc482c..c2c0149 100644 --- a/src/record.rs +++ b/src/record.rs @@ -1,8 +1,7 @@ /// /// Generic record-level read/write functionality. /// -use std::io::Write; -use std::convert::TryInto; +use std::io::{self, Write}; use byteorder::{ByteOrder, BigEndian}; @@ -27,12 +26,15 @@ impl RecordHeader { pub fn read(input: &[u8]) -> IResult<'_, RecordHeader> { let (input, size) = parse_u16(input)?; let (input, tag) = parse_u16(input)?; - Ok((input, RecordHeader{tag, data_size:size - 4})) + let Some(data_size) = size.checked_sub(4) else { + return fail(input, format!("Record size {size} is smaller than its header")); + }; + Ok((input, RecordHeader{tag, data_size})) } pub fn pack_into(&self) -> [u8; 4] { - assert!(self.data_size < 0xffff - 4, "Record too big!"); - let vals = [self.data_size, self.tag]; + let size = self.data_size.checked_add(4).expect("Record too big!"); + let vals = [size, self.tag]; let mut buf = [0x77; 4]; BigEndian::write_u16_into(&vals, &mut buf); buf @@ -40,7 +42,8 @@ impl RecordHeader { pub fn write(&self, ww: &mut W) -> OResult { let bytes = self.pack_into(); - ww.write(&bytes) + ww.write_all(&bytes)?; + Ok(bytes.len()) } } @@ -138,11 +141,12 @@ pub trait Record { fn write(ww: &mut W, data: &RData::InData) -> OResult { let packed_data = RData::pack(data); let data_bytes = packed_data.as_ref(); - let len: u16 = data_bytes.len().try_into().expect("Record longer than max size (u16)!"); - let mut size = 0; - size += Self::write_header(ww, len)?; - size += ww.write(data_bytes)?; - Ok(size) + let len = u16::try_from(data_bytes.len()).ok() + .filter(|len| *len <= u16::MAX - 4) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Record longer than max size (u16)"))?; + Self::write_header(ww, len)?; + ww.write_all(data_bytes)?; + Ok(usize::from(len) + 4) } } @@ -232,7 +236,7 @@ impl RecordData for Int2Array { } fn pack(data: &Self::InData) -> Self::ByteData { - let mut buf = Vec::with_capacity(data.len() * 2); + let mut buf = vec![0; data.len() * 2]; Self::pack_into(&mut buf, data); buf } @@ -273,7 +277,7 @@ impl RecordData for Int4Array { } fn pack(data: &Self::InData) -> Self::ByteData { - let mut buf = Vec::with_capacity(data.len() * 4); + let mut buf = vec![0; data.len() * 4]; Self::pack_into(&mut buf, data); buf } @@ -332,7 +336,7 @@ impl RecordData for Real8Pair { } fn pack_into(buf: &mut [u8], data: &Self::InData) { - pack_real8(&mut buf[8 * 0..], data.0).unwrap_or_else(|_| panic!("Float.0 {0} too big for Real8", data.0)); + pack_real8(buf, data.0).unwrap_or_else(|_| panic!("Float.0 {0} too big for Real8", data.0)); pack_real8(&mut buf[8 * 1..], data.1).unwrap_or_else(|_| panic!("Float.1 {0} too big for Real8", data.1)); } @@ -363,7 +367,7 @@ impl RecordData for ASCII { } fn pack(data: &Self::InData) -> Self::ByteData { - let mut buf = Vec::with_capacity(data.len() * 4); + let mut buf = vec![0; data.len() + data.len() % 2]; Self::pack_into(&mut buf, data); buf } @@ -384,7 +388,7 @@ impl RecordData for DateTimePair { } fn pack_into(buf: &mut [u8], data: &Self::InData) { - pack_datetime(&mut buf[6 * 2 * 0..], &data[0]); + pack_datetime(buf, &data[0]); pack_datetime(&mut buf[6 * 2 * 1..], &data[1]); } diff --git a/src/records.rs b/src/records.rs index 27f7eaf..3731c9f 100644 --- a/src/records.rs +++ b/src/records.rs @@ -137,7 +137,7 @@ impl Record for ENDLIB { pub struct BGNSTR; impl Record for BGNSTR { fn tag() -> u16 { RTAG_BGNSTR } - fn expected_size() -> Option { Some(2 * 6) } + fn expected_size() -> Option { Some(2 * 6 * 2) } } pub struct STRNAME; @@ -545,3 +545,23 @@ impl Record for CONTACT { fn tag() -> u16 { RTAG_CONTACT } fn expected_size() -> Option { Some(0) } } + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bgnstr_reads_both_timestamps() { + let mut bytes = vec![0, 28, 0x05, 0x02]; + for value in [126_i16, 11, 14, 12, 30, 0, 125, 10, 13, 9, 15, 1] { + bytes.extend_from_slice(&value.to_be_bytes()); + } + bytes.extend_from_slice(&[0, 4, 0x07, 0]); + + let (remaining, timestamps) = BGNSTR::read(&bytes).unwrap(); + + assert_eq!(timestamps, [[2026, 11, 14, 12, 30, 0], [2025, 10, 13, 9, 15, 1]]); + assert_eq!(remaining, &[0, 4, 0x07, 0]); + } +} diff --git a/src/review.rs b/src/review.rs new file mode 100644 index 0000000..4ee01fd --- /dev/null +++ b/src/review.rs @@ -0,0 +1,1371 @@ +//! Deterministic GDS object review without the normalization performed by the +//! Arrow reader. Raw payloads borrow the file; only polygon keys are copied. + +use crate::{basic::decode_real8, record::RecordHeader, records::*}; +use std::{ + borrow::Cow, + collections::{BTreeMap, BTreeSet}, + fmt::Write, +}; + +mod names; +pub use names::{parse_layer, parse_layer_name, write_layer_names}; +mod selection; +pub use selection::{DisplayFilter, Scope}; +mod changes; +pub use changes::Replacement; + +pub const PROFILE: &str = "klamath-object-v2"; +pub const LAYER_SENTINEL: &str = "KLAMATH_LAYER_NAMES_V1"; +pub type Layer = (u16, u16); +pub type Bounds = [i32; 4]; + +#[derive(Clone, Debug)] +pub struct Record<'a> { + pub offset: usize, + pub tag: u16, + pub data: &'a [u8], +} + +#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] +struct Key<'a> { + kind: u16, + fields: Vec<(u16, Cow<'a, [u8]>)>, + properties: Vec<(u16, &'a [u8])>, +} + +#[derive(Debug)] +pub struct Object<'a> { + pub offset: usize, + pub end_offset: usize, + pub kind: u16, + pub layer: Option, + pub bounds: Option, + pub target: Option, + pub multiplicity: u64, + key: Key<'a>, + metadata: bool, + issues: Vec, +} + +impl Object<'_> { + fn field(&self, tag: u16) -> Option<&[u8]> { + self.key + .fields + .iter() + .find(|(t, _)| *t == tag) + .map(|(_, v)| v.as_ref()) + } + + pub fn description(&self) -> String { + let mut out = kind_name(self.kind).to_string(); + for (tag, value) in &self.key.fields { + write!(out, " {}={}", tag_name(*tag), format_data(*tag, value)).unwrap(); + } + for (attribute, value) in &self.key.properties { + write!(out, " property[{attribute}]={}", quoted(value)).unwrap(); + } + out + } +} + +#[derive(Debug)] +pub struct Cell<'a> { + pub offset: usize, + /// Start of ENDSTR, for inserting records without rewriting the cell. + pub end_offset: usize, + pub objects: Vec>, + attributes: Vec<(u16, &'a [u8])>, + issues: Vec, +} + +#[derive(Debug)] +pub struct Document<'a> { + pub records: Vec>, + pub cells: BTreeMap>, + pub layer_names: BTreeMap, + /// Unsupported features or invalid reference graphs prevent an equality claim. + pub issues: Vec, + header: Vec<(u16, &'a [u8])>, + global_issues: Vec, + known_cells: BTreeSet, + pub scope: Scope, + present: bool, +} + +fn error(offset: usize, message: impl std::fmt::Display) -> String { + format!("at byte {offset}: {message}") +} + +fn string(data: &[u8], offset: usize) -> Result { + decoded_string(unpad(data), offset) +} + +fn decoded_string(data: &[u8], offset: usize) -> Result { + if data.contains(&0) { + return Err(error(offset, "name or metadata contains an embedded NUL")); + } + std::str::from_utf8(data) + .map(str::to_owned) + .map_err(|_| error(offset, "name or metadata is not UTF-8")) +} + +fn unpad(data: &[u8]) -> &[u8] { + if data.last() == Some(&0) { + &data[..data.len() - 1] + } else { + data + } +} + +fn integer(data: &[u8]) -> u16 { + u16::from_be_bytes(data.try_into().unwrap()) +} + +fn points(data: &[u8]) -> Vec<[i32; 2]> { + data.chunks_exact(8) + .map(|p| { + [ + i32::from_be_bytes(p[..4].try_into().unwrap()), + i32::from_be_bytes(p[4..].try_into().unwrap()), + ] + }) + .collect() +} + +// Booth's least-rotation algorithm avoids quadratic work on repeated vertices. +fn least_rotation(points: &[[i32; 2]]) -> Vec<[i32; 2]> { + let n = points.len(); + let (mut i, mut j, mut k) = (0, 1, 0); + while i < n && j < n && k < n { + match points[(i + k) % n].cmp(&points[(j + k) % n]) { + std::cmp::Ordering::Equal => k += 1, + std::cmp::Ordering::Greater => { + i += k + 1; + if i <= j { + i = j + 1; + } + k = 0; + } + std::cmp::Ordering::Less => { + j += k + 1; + if j <= i { + j = i + 1; + } + k = 0; + } + } + } + let start = i.min(j); + (0..n).map(|k| points[(start + k) % n]).collect() +} + +fn canonical_ring(data: &[u8]) -> Vec { + let mut ring = points(data); + ring.pop(); // The caller has checked closure. + let forward = least_rotation(&ring); + ring.reverse(); + let backward = least_rotation(&ring); + let mut ring = forward.min(backward); + ring.push(ring[0]); + ring.into_iter() + .flatten() + .flat_map(i32::to_be_bytes) + .collect() +} + +fn validate_payload(record: &Record<'_>) -> Result<(), String> { + let size = record.data.len(); + let valid = match record.tag { + RTAG_BGNLIB | RTAG_BGNSTR => size == 24, + RTAG_UNITS => size == 16, + RTAG_HEADER | RTAG_LAYER | RTAG_DATATYPE | RTAG_TEXTTYPE | RTAG_NODETYPE | RTAG_BOXTYPE + | RTAG_PROPATTR | RTAG_PATHTYPE | RTAG_STRANS | RTAG_PRESENTATION | RTAG_ELFLAGS + | RTAG_STRCLASS | RTAG_GENERATIONS => size == 2, + RTAG_WIDTH | RTAG_BGNEXTN | RTAG_ENDEXTN | RTAG_PLEX | RTAG_COLROW => size == 4, + RTAG_MAG | RTAG_ANGLE => size == 8, + RTAG_XY => size % 8 == 0, + RTAG_ENDLIB | RTAG_ENDSTR | RTAG_ENDEL | RTAG_BOUNDARY | RTAG_PATH | RTAG_SREF + | RTAG_AREF | RTAG_TEXT | RTAG_NODE | RTAG_BOX | RTAG_ENDMASKS => size == 0, + _ => true, + }; + if !valid { + return Err(error( + record.offset, + format!("invalid payload size {size} for {}", tag_name(record.tag)), + )); + } + if record.tag == RTAG_UNITS + && record.data.chunks_exact(8).any(|bytes| { + let value = decode_real8(u64::from_be_bytes(bytes.try_into().unwrap())); + !value.is_finite() || value <= 0.0 + }) + { + return Err(error(record.offset, "UNITS must be positive finite values")); + } + Ok(()) +} + +fn is_element(tag: u16) -> bool { + matches!( + tag, + RTAG_BOUNDARY | RTAG_PATH | RTAG_SREF | RTAG_AREF | RTAG_TEXT | RTAG_NODE | RTAG_BOX + ) +} + +fn allowed_field(kind: u16, tag: u16) -> bool { + if matches!(tag, RTAG_ELFLAGS | RTAG_PLEX | RTAG_XY) { + return true; + } + match kind { + RTAG_BOUNDARY => matches!(tag, RTAG_LAYER | RTAG_DATATYPE), + RTAG_BOX => matches!(tag, RTAG_LAYER | RTAG_BOXTYPE), + RTAG_NODE => matches!(tag, RTAG_LAYER | RTAG_NODETYPE), + RTAG_PATH => matches!( + tag, + RTAG_LAYER | RTAG_DATATYPE | RTAG_WIDTH | RTAG_PATHTYPE | RTAG_BGNEXTN | RTAG_ENDEXTN + ), + RTAG_SREF => matches!(tag, RTAG_SNAME | RTAG_STRANS | RTAG_MAG | RTAG_ANGLE), + RTAG_AREF => matches!( + tag, + RTAG_SNAME | RTAG_STRANS | RTAG_MAG | RTAG_ANGLE | RTAG_COLROW + ), + RTAG_TEXT => matches!( + tag, + RTAG_LAYER + | RTAG_TEXTTYPE + | RTAG_STRING + | RTAG_STRANS + | RTAG_MAG + | RTAG_ANGLE + | RTAG_PRESENTATION + | RTAG_PATHTYPE + | RTAG_WIDTH + ), + _ => false, + } +} + +fn object<'a>(records: &[Record<'a>], issues: &mut Vec) -> Result, String> { + let first = &records[0]; + let mut fields = Vec::new(); + let mut properties = Vec::new(); + let mut seen = BTreeSet::new(); + let mut i = 1; + while i + 1 < records.len() { + let record = &records[i]; + if record.tag == RTAG_PROPATTR { + let value = records + .get(i + 1) + .filter(|r| r.tag == RTAG_PROPVALUE) + .ok_or_else(|| error(record.offset, "PROPATTR without PROPVALUE"))?; + properties.push((integer(record.data), unpad(value.data))); + i += 2; + continue; + } + if !allowed_field(first.tag, record.tag) { + issues.push(error( + record.offset, + format!( + "unsupported record 0x{:04x} in {}", + record.tag, + kind_name(first.tag) + ), + )); + } + if !seen.insert(record.tag) { + return Err(error(record.offset, "duplicate element field")); + } + let mut data = Cow::Borrowed(record.data); + if record.tag & 0xff == 6 { + data = Cow::Borrowed(unpad(record.data)); + } + if record.tag == RTAG_XY && matches!(first.tag, RTAG_BOUNDARY | RTAG_BOX) { + let p = points(record.data); + if p.len() < 4 || p.first() != p.last() { + return Err(error( + record.offset, + "polygon must have at least three vertices and be closed", + )); + } + data = Cow::Owned(canonical_ring(record.data)); + } + fields.push((record.tag, data)); + i += 1; + } + fields.sort(); + properties.sort(); + let mut object = Object { + offset: first.offset, + end_offset: records.last().unwrap().offset + 4, + kind: first.tag, + layer: None, + bounds: None, + target: None, + multiplicity: 1, + key: Key { + kind: first.tag, + fields, + properties, + }, + metadata: false, + issues: Vec::new(), + }; + let xy = object + .field(RTAG_XY) + .ok_or_else(|| error(first.offset, "element has no XY record"))?; + let p = points(xy); + let valid_count = match first.tag { + RTAG_TEXT | RTAG_SREF => p.len() == 1, + RTAG_AREF => p.len() == 3, + RTAG_PATH => p.len() >= 2, + RTAG_NODE => !p.is_empty(), + RTAG_BOX => p.len() == 5, + _ => true, + }; + if !valid_count { + return Err(error(first.offset, "invalid coordinate count")); + } + object.bounds = Some([ + p.iter().map(|p| p[0]).min().unwrap(), + p.iter().map(|p| p[1]).min().unwrap(), + p.iter().map(|p| p[0]).max().unwrap(), + p.iter().map(|p| p[1]).max().unwrap(), + ]); + if matches!(first.tag, RTAG_SREF | RTAG_AREF) { + object.target = Some(decoded_string( + object + .field(RTAG_SNAME) + .ok_or_else(|| error(first.offset, "reference has no SNAME"))?, + first.offset, + )?); + if first.tag == RTAG_AREF { + let counts = object + .field(RTAG_COLROW) + .ok_or_else(|| error(first.offset, "array has no COLROW"))?; + let a = i16::from_be_bytes(counts[..2].try_into().unwrap()); + let b = i16::from_be_bytes(counts[2..].try_into().unwrap()); + if a <= 0 || b <= 0 { + return Err(error(first.offset, "array counts must be positive")); + } + object.multiplicity = a as u64 * b as u64; + } + } else { + let dtype = match first.tag { + RTAG_TEXT => RTAG_TEXTTYPE, + RTAG_BOX => RTAG_BOXTYPE, + RTAG_NODE => RTAG_NODETYPE, + _ => RTAG_DATATYPE, + }; + object.layer = Some(( + integer( + object + .field(RTAG_LAYER) + .ok_or_else(|| error(first.offset, "element has no LAYER"))?, + ), + integer( + object + .field(dtype) + .ok_or_else(|| error(first.offset, "element has no datatype/texttype"))?, + ), + )); + if first.tag == RTAG_TEXT && object.field(RTAG_STRING).is_none() { + return Err(error(first.offset, "text has no STRING")); + } + } + Ok(object) +} + +fn read_records(input: &[u8]) -> Result>, String> { + let mut records = Vec::new(); + let mut offset = 0; + while offset < input.len() { + let (payload, header) = RecordHeader::read(&input[offset..]) + .map_err(|(_, e)| error(offset, format!("invalid record header: {e:?}")))?; + let size = header.data_size as usize; + if (size + 4) % 2 != 0 { + return Err(error(offset, "odd record length")); + } + let data = payload + .get(..size) + .ok_or_else(|| error(offset, "truncated record"))?; + let record = Record { + offset, + tag: header.tag, + data, + }; + offset += size + 4; + let ended = record.tag == RTAG_ENDLIB; + records.push(record); + if ended { + if input[offset..].iter().any(|b| *b != 0) { + return Err(error(offset, "nonzero data after ENDLIB")); + } + break; + } + } + Ok(records) +} + +impl<'a> Document<'a> { + pub fn parse(input: &'a [u8]) -> Result { + let records = read_records(input)?; + for record in &records { + validate_payload(record)?; + } + if records.first().map(|r| r.tag) != Some(RTAG_HEADER) + || records.get(1).map(|r| r.tag) != Some(RTAG_BGNLIB) + || records.last().map(|r| r.tag) != Some(RTAG_ENDLIB) + { + return Err("expected HEADER, BGNLIB, and a final ENDLIB".to_string()); + } + let mut doc = Self { + records, + cells: BTreeMap::new(), + layer_names: BTreeMap::new(), + issues: Vec::new(), + header: Vec::new(), + global_issues: Vec::new(), + known_cells: BTreeSet::new(), + scope: Scope::default(), + present: true, + }; + let mut i = 2; + let mut global_seen = BTreeSet::new(); + let mut cells_started = false; + doc.header.push((RTAG_HEADER, doc.records[0].data)); + while i + 1 < doc.records.len() { + let record = &doc.records[i]; + if record.tag != RTAG_BGNSTR { + if cells_started { + return Err(error( + record.offset, + "library field outside the library header", + )); + } + if record.tag != RTAG_MASK && !global_seen.insert(record.tag) { + return Err(error(record.offset, "duplicate library field")); + } + if !matches!( + record.tag, + RTAG_LIBNAME + | RTAG_UNITS + | RTAG_REFLIBS + | RTAG_FONTS + | RTAG_GENERATIONS + | RTAG_ATTRTABLE + | RTAG_FORMAT + | RTAG_MASK + | RTAG_ENDMASKS + | RTAG_LIBDIRSIZE + | RTAG_SRFNAME + | RTAG_LIBSECUR + ) { + doc.global_issues.push(error( + record.offset, + format!("unsupported library record 0x{:04x}", record.tag), + )); + } + doc.header.push(( + record.tag, + if record.tag & 0xff == 6 { + unpad(record.data) + } else { + record.data + }, + )); + i += 1; + continue; + } + if !global_seen.contains(&RTAG_LIBNAME) || !global_seen.contains(&RTAG_UNITS) { + return Err(error(record.offset, "LIBNAME and UNITS must precede cells")); + } + cells_started = true; + let offset = record.offset; + i += 1; + let name_record = doc + .records + .get(i) + .filter(|r| r.tag == RTAG_STRNAME) + .ok_or_else(|| error(offset, "BGNSTR must be followed by STRNAME"))?; + let name = string(name_record.data, name_record.offset)?; + if name.is_empty() { + return Err(error(name_record.offset, "empty cell name")); + } + i += 1; + let mut cell = Cell { + offset, + end_offset: 0, + objects: Vec::new(), + attributes: Vec::new(), + issues: Vec::new(), + }; + loop { + let record = doc + .records + .get(i) + .ok_or_else(|| error(offset, "missing ENDSTR"))?; + if record.tag == RTAG_ENDSTR { + cell.end_offset = record.offset; + i += 1; + break; + } + if is_element(record.tag) { + let start = i; + i += 1; + while doc.records.get(i).is_some_and(|r| r.tag != RTAG_ENDEL) { + if matches!(doc.records[i].tag, RTAG_ENDSTR | RTAG_ENDLIB | RTAG_BGNSTR) + || is_element(doc.records[i].tag) + { + return Err(error(doc.records[i].offset, "missing ENDEL")); + } + i += 1; + } + if i == doc.records.len() { + return Err(error(offset, "missing ENDEL")); + } + let mut issues = Vec::new(); + let mut parsed = object(&doc.records[start..=i], &mut issues)?; + parsed.issues = issues; + cell.objects.push(parsed); + i += 1; + } else { + if matches!(record.tag, RTAG_ENDLIB | RTAG_BGNSTR) { + return Err(error(record.offset, "missing ENDSTR")); + } + if record.tag != RTAG_STRCLASS { + cell.issues.push(error( + record.offset, + format!("unsupported cell record 0x{:04x}", record.tag), + )); + } else if !cell.objects.is_empty() + || cell.attributes.iter().any(|(tag, _)| *tag == RTAG_STRCLASS) + { + return Err(error( + record.offset, + "STRCLASS must occur once before elements", + )); + } + cell.attributes.push((record.tag, record.data)); + i += 1; + } + } + cell.attributes.sort(); + cell.objects.sort_by(|a, b| a.key.cmp(&b.key)); + if doc.cells.insert(name.clone(), cell).is_some() { + return Err(error(offset, format!("duplicate cell name {name:?}"))); + } + } + if !global_seen.contains(&RTAG_LIBNAME) || !global_seen.contains(&RTAG_UNITS) { + return Err("library must contain LIBNAME and UNITS".to_string()); + } + doc.header.sort(); + doc.read_metadata()?; + doc.known_cells = doc.cells.keys().cloned().collect(); + doc.refresh_issues(); + Ok(doc) + } + + fn read_metadata(&mut self) -> Result<(), String> { + for cell in self.cells.values_mut() { + for object in cell.objects.iter_mut().filter(|o| o.kind == RTAG_TEXT) { + let text = object.field(RTAG_STRING).unwrap(); + if text.starts_with(b"KLAMATH_LAYER_NAMES_") && text != LAYER_SENTINEL.as_bytes() { + object.issues.push(error( + object.offset, + "unsupported layer-name metadata version", + )); + } + } + let carriers: BTreeSet<_> = cell + .objects + .iter() + .filter(|o| { + o.kind == RTAG_TEXT && o.field(RTAG_STRING) == Some(LAYER_SENTINEL.as_bytes()) + }) + .filter_map(|o| o.layer) + .collect(); + for object in &mut cell.objects { + if object.kind != RTAG_TEXT || !object.layer.is_some_and(|l| carriers.contains(&l)) + { + continue; + } + let text = decoded_string(object.field(RTAG_STRING).unwrap(), object.offset)?; + if text != LAYER_SENTINEL { + let ((layer, dtype), name) = + parse_layer_name(&text).map_err(|message| error(object.offset, message))?; + if self + .layer_names + .get(&(layer, dtype)) + .is_some_and(|old| old != &name) + { + return Err(error( + object.offset, + format!("conflicting names for {layer}/{dtype}"), + )); + } + self.layer_names.insert((layer, dtype), name.to_string()); + } + object.metadata = true; + } + } + Ok(()) + } + + fn check_graph(&mut self) { + let edges = self.edges(); + for (parent, target) in edges.keys() { + if !self.known_cells.contains(target) { + self.issues + .push(format!("cell {parent:?}: unresolved reference {target:?}")); + } + } + let mut state = BTreeMap::<&str, u8>::new(); + for root in self.cells.keys() { + let mut stack = vec![(root.as_str(), false)]; + while let Some((name, leaving)) = stack.pop() { + if leaving { + state.insert(name, 2); + continue; + } + match state.get(name) { + Some(2) => continue, + Some(1) => { + self.issues + .push(format!("cyclic hierarchy involving {name:?}")); + continue; + } + _ => (), + } + state.insert(name, 1); + stack.push((name, true)); + if let Some(cell) = self.cells.get(name) { + for object in &cell.objects { + if let Some(target) = &object.target { + stack.push((target, false)); + } + } + } + } + } + } + + pub fn edges(&self) -> BTreeMap<(String, String), u64> { + let mut edges = BTreeMap::new(); + for (name, cell) in &self.cells { + for object in &cell.objects { + if let Some(target) = &object.target { + let count = edges.entry((name.clone(), target.clone())).or_insert(0_u64); + *count = count.saturating_add(object.multiplicity); + } + } + } + edges + } + + pub fn canonical_dump(&self) -> String { + let mut out = format!( + "profile {PROFILE}\n{}\ncoordinates: integer database units; bounds: coordinate envelopes\n", + self.scope.description() + ); + for (tag, data) in &self.header { + writeln!(out, "{}={}", tag_name(*tag), format_data(*tag, data)).unwrap(); + } + for ((layer, dtype), name) in &self.layer_names { + writeln!(out, "layer {layer}/{dtype} name={name:?}").unwrap(); + } + for (name, cell) in &self.cells { + writeln!(out, "cell {name:?}").unwrap(); + for (tag, data) in &cell.attributes { + writeln!(out, " {}={}", tag_name(*tag), format_data(*tag, data)).unwrap(); + } + for object in cell.objects.iter().filter(|o| !o.metadata) { + writeln!(out, " {}", object.description()).unwrap(); + } + } + for issue in &self.issues { + writeln!(out, "INCOMPLETE: {issue}").unwrap(); + } + out + } + + pub fn record_dump(&self) -> String { + format_records(&self.records) + } +} + +/// Inspect record boundaries even when object grammar or metadata is invalid. +pub fn dump_records(input: &[u8]) -> Result { + Ok(format_records(&read_records(input)?)) +} + +fn format_records(records: &[Record<'_>]) -> String { + let mut out = String::new(); + for record in records { + writeln!( + out, + "{:010} {:04x} {} size={} {}", + record.offset, + record.tag, + tag_name(record.tag), + record.data.len() + 4, + format_data( + record.tag, + if record.tag & 0xff == 6 { + unpad(record.data) + } else { + record.data + } + ) + ) + .unwrap(); + } + out +} + +#[derive(Debug)] +pub struct ObjectChange { + pub offset: usize, + pub kind: u16, + pub layer: Option, + pub bounds: Option, + pub target: Option, + pub origin: Option<[i32; 2]>, + pub width: Option, + pub counts: Option<[u16; 2]>, + pub description: String, +} + +impl From<&Object<'_>> for ObjectChange { + fn from(object: &Object<'_>) -> Self { + Self { + offset: object.offset, + kind: object.kind, + layer: object.layer, + bounds: object.bounds, + target: object.target.clone(), + origin: object.field(RTAG_XY).map(|data| { + [ + i32::from_be_bytes(data[..4].try_into().unwrap()), + i32::from_be_bytes(data[4..8].try_into().unwrap()), + ] + }), + width: object + .field(RTAG_WIDTH) + .map(|data| i32::from_be_bytes(data.try_into().unwrap())), + counts: object.target.as_ref().map(|_| { + object + .field(RTAG_COLROW) + .map(|data| [integer(&data[..2]), integer(&data[2..])]) + .unwrap_or([1, 1]) + }), + description: object.description(), + } + } +} + +#[derive(Debug)] +pub struct CellChange { + pub name: String, + pub old_offset: Option, + pub new_offset: Option, + pub attributes_changed: bool, + pub removed: Vec, + pub added: Vec, + pub replacements: Vec, +} + +#[derive(Debug)] +pub struct LayerNameChange { + pub layer: Layer, + pub old: Option, + pub new: Option, +} + +#[derive(Debug)] +pub struct LibraryFieldChange { + pub field: String, + pub old: Vec, + pub new: Vec, +} + +#[derive(Debug)] +pub struct Comparison { + pub scope: Scope, + /// Unchanged names are displayed once when objects on that layer change. + pub layer_legend: BTreeMap, + pub library_fields: Vec, + pub layer_names: Vec, + pub cells: Vec, + pub issues: Vec, +} + +impl Comparison { + pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self { + let mut result = Self { + scope: old.scope.clone(), + layer_legend: old + .layer_names + .iter() + .filter(|(pair, name)| new.layer_names.get(pair) == Some(*name)) + .map(|(pair, name)| (*pair, name.clone())) + .collect(), + library_fields: Vec::new(), + layer_names: Vec::new(), + cells: Vec::new(), + issues: Vec::new(), + }; + if old.scope != new.scope { + result.issues.push("comparison scopes differ".to_string()); + } + if old.present != new.present { + result.library_fields.push(LibraryFieldChange { + field: "presence".to_string(), + old: vec![if old.present { "present" } else { "absent" }.to_string()], + new: vec![if new.present { "present" } else { "absent" }.to_string()], + }); + } + for (side, doc) in [("old", old), ("new", new)] { + result + .issues + .extend(doc.issues.iter().map(|i| format!("{side}: {i}"))); + } + let header_tags: BTreeSet<_> = old + .header + .iter() + .chain(&new.header) + .map(|(tag, _)| *tag) + .collect(); + for tag in header_tags { + let a: Vec<_> = old + .header + .iter() + .filter(|(t, _)| *t == tag) + .map(|(_, value)| *value) + .collect(); + let b: Vec<_> = new + .header + .iter() + .filter(|(t, _)| *t == tag) + .map(|(_, value)| *value) + .collect(); + if a != b { + result.library_fields.push(LibraryFieldChange { + field: tag_name(tag), + old: a.iter().map(|data| format_data(tag, data)).collect(), + new: b.iter().map(|data| format_data(tag, data)).collect(), + }); + } + } + let layers: BTreeSet<_> = old + .layer_names + .keys() + .chain(new.layer_names.keys()) + .copied() + .collect(); + for layer in layers { + if old.layer_names.get(&layer) != new.layer_names.get(&layer) { + result.layer_names.push(LayerNameChange { + layer, + old: old.layer_names.get(&layer).cloned(), + new: new.layer_names.get(&layer).cloned(), + }); + } + } + let names: BTreeSet<_> = old.cells.keys().chain(new.cells.keys()).collect(); + for name in names { + let a = old.cells.get(name); + let b = new.cells.get(name); + let mut change = CellChange { + name: name.clone(), + old_offset: a.map(|c| c.offset), + new_offset: b.map(|c| c.offset), + attributes_changed: a.map(|c| &c.attributes) != b.map(|c| &c.attributes), + removed: Vec::new(), + added: Vec::new(), + replacements: Vec::new(), + }; + let a: Vec<_> = a + .into_iter() + .flat_map(|c| &c.objects) + .filter(|o| !o.metadata) + .collect(); + let b: Vec<_> = b + .into_iter() + .flat_map(|c| &c.objects) + .filter(|o| !o.metadata) + .collect(); + let (mut i, mut j) = (0, 0); + while i < a.len() || j < b.len() { + let order = match (a.get(i), b.get(j)) { + (Some(a), Some(b)) => a.key.cmp(&b.key), + (Some(_), None) => std::cmp::Ordering::Less, + _ => std::cmp::Ordering::Greater, + }; + match order { + std::cmp::Ordering::Equal => { + i += 1; + j += 1; + } + std::cmp::Ordering::Less => { + change.removed.push(a[i].into()); + i += 1; + } + std::cmp::Ordering::Greater => { + change.added.push(b[j].into()); + j += 1; + } + } + } + if change.old_offset.is_none() + || change.new_offset.is_none() + || change.attributes_changed + || !change.removed.is_empty() + || !change.added.is_empty() + { + change.replacements = changes::replacements(&change.removed, &change.added); + result.cells.push(change); + } + } + result + } + + pub fn is_equal(&self) -> bool { + self.issues.is_empty() + && self.library_fields.is_empty() + && self.layer_names.is_empty() + && self.cells.is_empty() + } + + pub fn exit_code(&self) -> u8 { + if !self.issues.is_empty() { + 2 + } else if self.is_equal() { + 0 + } else { + 1 + } + } + + /// Limit presentation only: the complete comparison has already been made. + pub fn text(&self, max_objects: usize) -> String { + self.text_filtered(max_objects, &DisplayFilter::default()) + } + + pub fn text_filtered(&self, max_objects: usize, show: &DisplayFilter) -> String { + let mut out = format!("profile {PROFILE}\n{}\n", self.scope.description()); + if show.cell.is_some() || show.layer.is_some() { + writeln!(out, "display-only filter cell={:?} layer={:?}; status, totals and hierarchy are unfiltered", show.cell, show.layer).unwrap(); + } + for change in &self.library_fields { + writeln!( + out, + "library {}: {:?} -> {:?}", + change.field, change.old, change.new + ) + .unwrap(); + } + if self.library_fields.iter().any(|c| c.field == "UNITS") { + out.push_str("UNITS changed; coordinates remain in each file's database units\n"); + } + for change in &self.layer_names { + writeln!( + out, + "layer {}/{} name: {:?} -> {:?}", + change.layer.0, change.layer.1, change.old, change.new + ) + .unwrap(); + } + let changed_layers: BTreeSet<_> = self + .cells + .iter() + .filter(|cell| show.cell.as_ref().is_none_or(|name| name == &cell.name)) + .flat_map(|cell| cell.removed.iter().chain(&cell.added)) + .filter_map(|object| object.layer) + .filter(|layer| show.layer.is_none_or(|selected| selected == *layer)) + .collect(); + for layer in changed_layers { + if let Some(name) = self.layer_legend.get(&layer) { + writeln!(out, "layer {}/{} name={name:?}", layer.0, layer.1).unwrap(); + } + } + let total: usize = self + .cells + .iter() + .map(|c| c.removed.len() + c.added.len()) + .sum(); + let mut shown: usize = 0; + for cell in &self.cells { + if show.cell.as_ref().is_some_and(|name| name != &cell.name) { + continue; + } + writeln!( + out, + "cell {:?} old@{:?} new@{:?}{}", + cell.name, + cell.old_offset, + cell.new_offset, + if cell.attributes_changed { + " [cell/header changed]" + } else { + "" + } + ) + .unwrap(); + let mut paired_old = BTreeSet::new(); + let mut paired_new = BTreeSet::new(); + for replacement in &cell.replacements { + let a = &cell.removed[replacement.removed]; + let b = &cell.added[replacement.added]; + if shown.saturating_add(2) <= max_objects + && show + .layer + .is_none_or(|layer| a.layer == Some(layer) && b.layer == Some(layer)) + { + writeln!(out, " ~ {}", replacement.explanation).unwrap(); + writeln!( + out, + " - @{} bbox={:?} {}", + a.offset, a.bounds, a.description + ) + .unwrap(); + writeln!( + out, + " + @{} bbox={:?} {}", + b.offset, b.bounds, b.description + ) + .unwrap(); + paired_old.insert(replacement.removed); + paired_new.insert(replacement.added); + shown += 2; + } + } + for (sign, objects, paired) in [ + ("-", &cell.removed, &paired_old), + ("+", &cell.added, &paired_new), + ] { + for (index, object) in objects.iter().enumerate() { + if paired.contains(&index) { + continue; + } + if show.layer.is_some_and(|layer| object.layer != Some(layer)) { + continue; + } + if shown < max_objects { + writeln!( + out, + " {sign} @{} bbox={:?} {}", + object.offset, object.bounds, object.description + ) + .unwrap(); + shown += 1; + } + } + } + } + writeln!( + out, + "{} changed cells; {shown} of {total} object changes shown; {} layer-name changes", + self.cells.len(), + self.layer_names.len() + ) + .unwrap(); + for issue in &self.issues { + writeln!(out, "INCOMPLETE: {issue}").unwrap(); + } + if self.is_equal() { + out.push_str("equal under this profile\n"); + } + out + } +} + +/// The graph joins both revisions, retaining removed branches and old callers. +pub fn hierarchy( + old: &Document<'_>, + new: &Document<'_>, + diff: Option<&Comparison>, + mermaid: bool, + max_depth: usize, +) -> String { + let old_edges = old.edges(); + let new_edges = new.edges(); + let edges: BTreeSet<_> = old_edges.keys().chain(new_edges.keys()).cloned().collect(); + let direct: BTreeSet<_> = diff + .into_iter() + .flat_map(|d| d.cells.iter().map(|c| c.name.clone())) + .collect(); + let changed_refs: BTreeSet<_> = diff + .into_iter() + .flat_map(|d| &d.cells) + .flat_map(|c| { + c.removed + .iter() + .chain(&c.added) + .filter_map(|o| o.target.as_ref().map(|t| (c.name.clone(), t.clone()))) + }) + .collect(); + let mut parents = BTreeMap::<&str, Vec<&str>>::new(); + for (parent, child) in &edges { + parents.entry(child).or_default().push(parent); + } + let mut affected = direct.clone(); + let mut pending: Vec<_> = direct.iter().cloned().collect(); + while let Some(child) = pending.pop() { + for parent in parents.get(child.as_str()).into_iter().flatten() { + if affected.insert((*parent).to_string()) { + pending.push((*parent).to_string()); + } + } + } + let visible: BTreeSet<_> = if diff.is_some() { + affected + .iter() + .cloned() + .chain(changed_refs.iter().map(|(_, t)| t.clone())) + .collect() + } else { + old.cells + .keys() + .chain(new.cells.keys()) + .cloned() + .chain(edges.iter().map(|(_, t)| t.clone())) + .collect() + }; + let mut children = BTreeMap::>::new(); + let mut targets = BTreeSet::new(); + for (parent, target) in &edges { + if visible.contains(parent) && visible.contains(target) { + children + .entry(parent.clone()) + .or_default() + .push(target.clone()); + targets.insert(target.clone()); + } + } + let roots: Vec<_> = visible.difference(&targets).cloned().collect(); + // Distinguish rootless cycles from descendants hidden by the depth limit. + let mut reachable = BTreeSet::new(); + let mut pending = roots.clone(); + while let Some(name) = pending.pop() { + if reachable.insert(name.clone()) { + pending.extend(children.get(&name).into_iter().flatten().cloned()); + } + } + let mut included = BTreeSet::new(); + let mut rows = Vec::new(); + let mut stack: Vec<_> = roots + .iter() + .rev() + .map(|n| (n.clone(), 0, None::)) + .collect(); + while let Some((name, depth, parent)) = stack.pop() { + let seen = !included.insert(name.clone()); + let descendants = children.get(&name).map(Vec::as_slice).unwrap_or(&[]); + rows.push(( + name.clone(), + depth, + parent, + seen, + depth >= max_depth && !descendants.is_empty(), + )); + if !seen && depth < max_depth { + for child in descendants.iter().rev() { + stack.push((child.clone(), depth + 1, Some(name.clone()))); + } + } + } + for name in visible.difference(&reachable) { + rows.push((name.clone(), 0, None, false, true)); + } + let status = |name: &String| { + if !old.cells.contains_key(name) && !new.cells.contains_key(name) { + if old.known_cells.contains(name) || new.known_cells.contains(name) { + " [outside scope]" + } else { + " [unresolved]" + } + } else if direct.contains(name) { + " [cell changed]" + } else if affected.contains(name) { + " [affected]" + } else if diff.is_some() { + " [cell unchanged]" + } else { + "" + } + }; + let edge_label = |parent: &String, target: &String| { + let key = (parent.clone(), target.clone()); + let a = old_edges.get(&key).copied().unwrap_or(0); + let b = new_edges.get(&key).copied().unwrap_or(0); + let count = if a == b { + format!("x{b}") + } else { + format!("x{a} -> x{b}") + }; + format!( + "{count}{}", + if changed_refs.contains(&key) { + " [reference changed]" + } else { + "" + } + ) + }; + if mermaid { + let ids: BTreeMap<_, _> = rows + .iter() + .map(|r| &r.0) + .collect::>() + .into_iter() + .enumerate() + .map(|(i, n)| (n, i)) + .collect(); + let mut out = format!("flowchart TD\n %% {}\n", new.scope.description()); + for (name, id) in &ids { + let label = format!("{name}{}", status(name)); + let label = label + .replace('&', "&") + .replace('"', """) + .replace('<', "<") + .replace('>', ">") + .replace(['\r', '\n'], " "); + writeln!(out, " n{id}[\"{label}\"]").unwrap(); + } + for (parent, target) in &edges { + if let (Some(a), Some(b)) = (ids.get(parent), ids.get(target)) { + writeln!(out, " n{a} -->|\"{}\"| n{b}", edge_label(parent, target)).unwrap(); + } + } + if rows.is_empty() { + out.push_str(" empty[\"No changed hierarchy\"]\n"); + } + out + } else { + let mut out = format!("{}\n", new.scope.description()); + for (name, depth, parent, seen, limited) in rows { + let count = parent + .map(|p| edge_label(&p, &name)) + .unwrap_or_else(|| "x1".to_string()); + writeln!( + out, + "{}{name:?} {count}{}{}{}", + " ".repeat(depth), + status(&name), + if seen { " [shown above]" } else { "" }, + if limited { " [children omitted]" } else { "" } + ) + .unwrap(); + } + if visible.is_empty() { + out.push_str("No changed hierarchy\n"); + } + out + } +} + +fn quoted(data: &[u8]) -> String { + let mut out = "\"".to_string(); + for byte in data { + for escaped in std::ascii::escape_default(*byte) { + out.push(escaped as char); + } + } + out.push('"'); + out +} + +fn format_data(tag: u16, data: &[u8]) -> String { + if matches!( + tag, + RTAG_LAYER | RTAG_DATATYPE | RTAG_TEXTTYPE | RTAG_BOXTYPE | RTAG_NODETYPE + ) && data.len() == 2 + { + return integer(data).to_string(); + } + match tag & 0xff { + 0 if data.is_empty() => String::new(), + 2 if data.len() % 2 == 0 => format!( + "{:?}", + data.chunks_exact(2) + .map(|b| i16::from_be_bytes(b.try_into().unwrap())) + .collect::>() + ), + 3 if data.len() % 4 == 0 => format!( + "{:?}", + data.chunks_exact(4) + .map(|b| i32::from_be_bytes(b.try_into().unwrap())) + .collect::>() + ), + 5 if data.len() % 8 == 0 => format!( + "{:?} raw={}", + data.chunks_exact(8) + .map(|b| decode_real8(u64::from_be_bytes(b.try_into().unwrap()))) + .collect::>(), + hex(data) + ), + 6 => quoted(data), + _ => hex(data), + } +} + +fn hex(data: &[u8]) -> String { + let mut out = "0x".to_string(); + for byte in data { + write!(out, "{byte:02x}").unwrap(); + } + out +} + +fn kind_name(tag: u16) -> &'static str { + match tag { + RTAG_BOUNDARY => "BOUNDARY", + RTAG_PATH => "PATH", + RTAG_SREF => "SREF", + RTAG_AREF => "AREF", + RTAG_TEXT => "TEXT", + RTAG_NODE => "NODE", + RTAG_BOX => "BOX", + _ => "UNKNOWN", + } +} + +fn tag_name(tag: u16) -> String { + let name = match tag { + RTAG_HEADER => "HEADER", + RTAG_BGNLIB => "BGNLIB", + RTAG_LIBNAME => "LIBNAME", + RTAG_UNITS => "UNITS", + RTAG_ENDLIB => "ENDLIB", + RTAG_BGNSTR => "BGNSTR", + RTAG_STRNAME => "STRNAME", + RTAG_ENDSTR => "ENDSTR", + RTAG_ENDEL => "ENDEL", + RTAG_LAYER => "layer", + RTAG_DATATYPE => "datatype", + RTAG_TEXTTYPE => "texttype", + RTAG_XY => "xy", + RTAG_SNAME => "target", + RTAG_COLROW => "counts", + RTAG_STRANS => "strans", + RTAG_MAG => "mag", + RTAG_ANGLE => "angle", + RTAG_WIDTH => "width", + RTAG_PATHTYPE => "pathtype", + RTAG_STRING => "string", + RTAG_PROPATTR => "PROPATTR", + RTAG_PROPVALUE => "PROPVALUE", + RTAG_PRESENTATION => "presentation", + RTAG_BGNEXTN => "bgnextn", + RTAG_ENDEXTN => "endextn", + RTAG_BOXTYPE => "boxtype", + RTAG_NODETYPE => "nodetype", + RTAG_ELFLAGS => "elflags", + RTAG_PLEX => "plex", + RTAG_STRCLASS => "STRCLASS", + tag if is_element(tag) => kind_name(tag), + _ => return format!("record_{tag:04x}"), + }; + name.to_string() +} diff --git a/src/review/changes.rs b/src/review/changes.rs new file mode 100644 index 0000000..c962766 --- /dev/null +++ b/src/review/changes.rs @@ -0,0 +1,117 @@ +use super::*; + +#[derive(Debug)] +pub struct Replacement { + pub removed: usize, + pub added: usize, + pub explanation: String, +} + +type Group = (u16, Option, Option, Option); + +fn group(object: &ObjectChange, bounds: bool) -> Group { + ( + object.kind, + object.layer, + object.target.clone(), + if bounds && object.target.is_none() { + object.bounds + } else { + None + }, + ) +} + +/// Pair only unique candidates in the remaining multisets. Ambiguous groups +/// remain additions/removals; no identity or geometric equivalence is inferred. +pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec { + let (mut used_old, mut used_new) = (BTreeSet::new(), BTreeSet::new()); + let mut result = Vec::new(); + for bounds in [true, false] { + let (mut a, mut b) = ( + BTreeMap::>::new(), + BTreeMap::>::new(), + ); + for (i, object) in old + .iter() + .enumerate() + .filter(|(i, _)| !used_old.contains(i)) + { + a.entry(group(object, bounds)).or_default().push(i); + } + for (i, object) in new + .iter() + .enumerate() + .filter(|(i, _)| !used_new.contains(i)) + { + b.entry(group(object, bounds)).or_default().push(i); + } + for (key, indices) in a { + if let (1, Some(others)) = (indices.len(), b.get(&key)) { + if others.len() == 1 { + let (i, j) = (indices[0], others[0]); + result.push(Replacement { + removed: i, + added: j, + explanation: explain(&old[i], &new[j]), + }); + used_old.insert(i); + used_new.insert(j); + } + } + } + } + result.sort_by_key(|r| (r.removed, r.added)); + result +} + +fn explain(old: &ObjectChange, new: &ObjectChange) -> String { + let mut parts = vec![format!( + "{} modified{}", + kind_name(old.kind), + old.target + .as_ref() + .map(|t| format!(" target={t:?}")) + .unwrap_or_default() + )]; + if old.target.is_some() && old.origin != new.origin { + if let (Some(a), Some(b)) = (old.origin, new.origin) { + parts.push(format!( + "origin {a:?} -> {b:?}, delta=({}, {}) dbu", + i64::from(b[0]) - i64::from(a[0]), + i64::from(b[1]) - i64::from(a[1]) + )); + } + } + if old.counts != new.counts { + let counts = |c: Option<[u16; 2]>| { + c.map(|[a, b]| format!("{a} x {b}")) + .unwrap_or_else(|| "absent".to_string()) + }; + parts.push(format!( + "columns/rows {} -> {}", + counts(old.counts), + counts(new.counts) + )); + } + if old.width != new.width { + let width = |n: Option| { + n.map(|n| n.to_string()) + .unwrap_or_else(|| "absent".to_string()) + }; + parts.push(format!( + "width {} -> {} dbu", + width(old.width), + width(new.width) + )); + } + if old.bounds == new.bounds { + parts.push("coordinate bounds unchanged".to_string()); + } else { + parts.push(format!( + "coordinate bounds {:?} -> {:?}", + old.bounds, new.bounds + )); + } + parts.join("; ") +} diff --git a/src/review/names.rs b/src/review/names.rs new file mode 100644 index 0000000..bea3228 --- /dev/null +++ b/src/review/names.rs @@ -0,0 +1,120 @@ +use super::*; + +pub fn parse_layer(value: &str) -> Result { + let (a, b) = value + .split_once('/') + .ok_or("expected layer/type, for example 900/7")?; + Ok((decimal(a)?, decimal(b)?)) +} + +fn decimal(value: &str) -> Result { + if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { + return Err("layer numbers must be unsigned decimal integers".to_string()); + } + value + .parse() + .map_err(|_| "layer number exceeds 65535".to_string()) +} + +pub fn parse_layer_name(value: &str) -> Result<(Layer, String), String> { + let mut parts = value.splitn(3, ':'); + let a = parts.next().ok_or("expected layer:datatype:name")?; + let b = parts.next().ok_or("expected layer:datatype:name")?; + let name = parts + .next() + .filter(|s| !s.is_empty() && !s.contains('\0')) + .ok_or("layer name must be nonempty and contain no NUL")?; + Ok(((decimal(a)?, decimal(b)?), name.to_string())) +} + +fn record(output: &mut Vec, tag: u16, payload: &[u8]) -> Result<(), String> { + let padding = usize::from(tag & 0xff == 6 && payload.len() % 2 != 0); + let size = payload + .len() + .checked_add(padding + 4) + .and_then(|n| u16::try_from(n).ok()) + .ok_or("metadata label exceeds GDS record size")?; + output.extend_from_slice(&size.to_be_bytes()); + output.extend_from_slice(&tag.to_be_bytes()); + output.extend_from_slice(payload); + if padding != 0 { + output.push(0); + } + Ok(()) +} + +fn label(output: &mut Vec, carrier: Layer, text: &str) -> Result<(), String> { + record(output, RTAG_TEXT, &[])?; + record(output, RTAG_LAYER, &carrier.0.to_be_bytes())?; + record(output, RTAG_TEXTTYPE, &carrier.1.to_be_bytes())?; + record(output, RTAG_XY, &[0; 8])?; + record(output, RTAG_STRING, text.as_bytes())?; + record(output, RTAG_ENDEL, &[]) +} + +/// Consolidate recognized metadata into an explicitly chosen existing cell and +/// carrier. Other records, including timestamps and unknown records, are copied +/// byte-for-byte. Updates override existing names; the input is never modified. +pub fn write_layer_names( + input: &[u8], + cell_name: &str, + carrier: Layer, + updates: &BTreeMap, +) -> Result, String> { + let doc = Document::parse(input)?; + if doc + .issues + .iter() + .any(|i| i.contains("unsupported layer-name metadata version")) + { + return Err("cannot rewrite an unsupported layer-name metadata version".to_string()); + } + let cell = doc + .cells + .get(cell_name) + .ok_or_else(|| format!("cell {cell_name:?} does not exist"))?; + if cell + .objects + .iter() + .any(|o| o.layer == Some(carrier) && !o.metadata) + { + return Err( + "carrier pair already contains ordinary design objects in the selected cell" + .to_string(), + ); + } + let mut names = doc.layer_names.clone(); + for (&pair, name) in updates { + if name.is_empty() || name.contains('\0') { + return Err("layer names must be nonempty and contain no NUL".to_string()); + } + names.insert(pair, name.clone()); + } + let mut legend = Vec::new(); + label(&mut legend, carrier, LAYER_SENTINEL)?; + for ((layer, dtype), name) in names { + label(&mut legend, carrier, &format!("{layer}:{dtype}:{name}"))?; + } + let mut edits: Vec<_> = doc + .cells + .values() + .flat_map(|c| &c.objects) + .filter(|o| o.metadata) + .map(|o| (o.offset, o.end_offset, None)) + .collect(); + edits.push((cell.end_offset, cell.end_offset, Some(legend.as_slice()))); + edits.sort_by_key(|(start, end, _)| (*start, *end)); + let mut result = Vec::with_capacity(input.len() + legend.len()); + let mut cursor = 0; + for (start, end, replacement) in edits { + result.extend_from_slice(&input[cursor..start]); + if let Some(bytes) = replacement { + result.extend_from_slice(bytes); + } + cursor = end; + } + result.extend_from_slice(&input[cursor..]); + // Validate the final declaration set before the CLI creates an output file. + Document::parse(&result)?; + Ok(result) +} diff --git a/src/review/selection.rs b/src/review/selection.rs new file mode 100644 index 0000000..42e09f2 --- /dev/null +++ b/src/review/selection.rs @@ -0,0 +1,221 @@ +use super::*; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Scope { + pub top: Option, + pub cell: Option, + pub layer: Option, +} + +/// Presentation filters never modify comparison status, totals, or hierarchy. +#[derive(Clone, Debug, Default)] +pub struct DisplayFilter { + pub cell: Option, + pub layer: Option, +} + +impl Scope { + pub fn description(&self) -> String { + let top = self + .top + .as_ref() + .map(|s| format!("{s:?}")) + .unwrap_or_else(|| "all".to_string()); + let cell = self + .cell + .as_ref() + .map(|s| format!("{s:?}")) + .unwrap_or_else(|| "all".to_string()); + let layer = self + .layer + .map(|(a, b)| format!("{a}/{b}")) + .unwrap_or_else(|| "all".to_string()); + format!("scope top={top} cell={cell} layer={layer}") + } + + pub fn validate_pair(&self, old: &Document<'_>, new: &Document<'_>) -> Result<(), String> { + for (kind, name) in [("top", &self.top), ("cell", &self.cell)] { + if let Some(name) = name { + if !old.cells.contains_key(name) && !new.cells.contains_key(name) { + return Err(format!( + "selected {kind} {name:?} exists in neither revision" + )); + } + } + } + if let (Some(top), Some(cell)) = (&self.top, &self.cell) { + if !old.reachable(top).contains(cell) && !new.reachable(top).contains(cell) { + return Err(format!( + "selected cell {cell:?} is not reachable from {top:?}" + )); + } + } + Ok(()) + } +} + +impl<'a> Document<'a> { + /// A missing Git revision has no cells or declarations. Retain the other + /// revision's library header to avoid inventing a unit/name change. + pub fn empty_like(&self) -> Self { + Self { + records: Vec::new(), + cells: BTreeMap::new(), + layer_names: BTreeMap::new(), + issues: Vec::new(), + header: self.header.clone(), + global_issues: Vec::new(), + known_cells: BTreeSet::new(), + scope: self.scope.clone(), + present: false, + } + } + fn reachable(&self, root: &str) -> BTreeSet { + let mut found = BTreeSet::new(); + let mut pending = vec![root.to_string()]; + while let Some(name) = pending.pop() { + if let Some(cell) = self.cells.get(&name) { + if found.insert(name) { + pending.extend(cell.objects.iter().filter_map(|o| o.target.clone())); + } + } + } + found + } + + pub(super) fn refresh_issues(&mut self) { + self.issues = self.global_issues.clone(); + for (name, cell) in &self.cells { + for issue in cell + .issues + .iter() + .chain(cell.objects.iter().flat_map(|o| &o.issues)) + { + self.issues.push(format!("cell {name:?}: {issue}")); + } + } + self.check_graph(); + } + + /// Project a parsed document. Missing selectors are allowed only for one + /// side of a comparison, after Scope::validate_pair has checked both sides. + pub fn selected(mut self, scope: &Scope, allow_missing: bool) -> Result { + if self.scope != Scope::default() { + return Err("document is already scoped; combine selectors in one Scope".to_string()); + } + if !allow_missing { + scope.validate_pair(&self, &self)?; + } + let mut wanted = scope + .top + .as_ref() + .map(|t| self.reachable(t)) + .unwrap_or_else(|| self.cells.keys().cloned().collect()); + if let Some(cell) = &scope.cell { + wanted.retain(|n| n == cell); + } + // Determine layer coverage before projecting cells: exact-cell scopes + // still need to know whether a referenced definition uses this layer. + let relevant = scope.layer.map(|layer| { + let mut relevant: BTreeSet<_> = self + .cells + .iter() + .filter(|(_, c)| { + !c.issues.is_empty() + || c.objects.iter().any(|o| { + !o.metadata + && (o.layer == Some(layer) + || (!o.issues.is_empty() && o.layer.is_none())) + }) + }) + .map(|(n, _)| n.clone()) + .collect(); + let mut parents = BTreeMap::>::new(); + for (parent, cell) in &self.cells { + for o in &cell.objects { + if let Some(target) = &o.target { + parents + .entry(target.clone()) + .or_default() + .push(parent.clone()); + if !self.known_cells.contains(target) { + relevant.insert(parent.clone()); + } + } + } + } + let mut pending: Vec<_> = relevant.iter().cloned().collect(); + // A cycle cannot be proven to have no effect on a layer. Preserve + // cycles (and their descendants) so graph validation remains visible. + let mut indegree: BTreeMap<_, usize> = + self.cells.keys().map(|n| (n.clone(), 0)).collect(); + for cell in self.cells.values() { + for target in cell.objects.iter().filter_map(|o| o.target.as_ref()) { + if let Some(n) = indegree.get_mut(target) { + *n += 1; + } + } + } + let mut ready: Vec<_> = indegree + .iter() + .filter(|(_, n)| **n == 0) + .map(|(n, _)| n.clone()) + .collect(); + while let Some(name) = ready.pop() { + for target in self.cells[&name] + .objects + .iter() + .filter_map(|o| o.target.as_ref()) + { + if let Some(n) = indegree.get_mut(target) { + *n -= 1; + if *n == 0 { + ready.push(target.clone()); + } + } + } + } + for (name, _) in indegree.iter().filter(|(_, n)| **n != 0) { + if relevant.insert(name.clone()) { + pending.push(name.clone()); + } + } + while let Some(child) = pending.pop() { + for parent in parents.get(&child).into_iter().flatten() { + if relevant.insert(parent.clone()) { + pending.push(parent.clone()); + } + } + } + relevant + }); + self.cells.retain(|name, _| { + wanted.contains(name) && relevant.as_ref().is_none_or(|r| r.contains(name)) + }); + if let (Some(layer), Some(relevant)) = (scope.layer, relevant) { + for cell in self.cells.values_mut() { + cell.objects.retain(|o| { + o.metadata + || o.layer == Some(layer) + || o.target + .as_ref() + .is_some_and(|t| relevant.contains(t) || !self.known_cells.contains(t)) + || (!o.issues.is_empty() && o.layer.is_none()) + }); + } + self.layer_names.retain(|pair, _| *pair == layer); + } else if scope.top.is_some() || scope.cell.is_some() { + let layers: BTreeSet<_> = self + .cells + .values() + .flat_map(|c| &c.objects) + .filter(|o| !o.metadata) + .filter_map(|o| o.layer) + .collect(); + self.layer_names.retain(|pair, _| layers.contains(pair)); + } + self.scope = scope.clone(); + self.refresh_issues(); + Ok(self) + } +} diff --git a/test.py b/test.py index 788df2e..5421f47 100644 --- a/test.py +++ b/test.py @@ -16,10 +16,16 @@ clib = ffi.dlopen('target/debug/libklamath_rs_ext.so') ret_ptr_array = ffi.new('struct ArrowArray[]', 1) ret_ptr_schema = ffi.new('struct ArrowSchema[]', 1) -ffi.cdef('void read_path(char* path, struct ArrowArray* array, struct ArrowSchema* schema);') +ffi.cdef(''' + int read_path(const char* path, struct ArrowArray* array, struct ArrowSchema* schema); + const char* last_error_message(void); +''') print(f'{ret_ptr_array[0]=}, {ret_ptr_schema[0]=}') -clib.read_path(path.encode(), ret_ptr_array, ret_ptr_schema) +status = clib.read_path(path.encode(), ret_ptr_array, ret_ptr_schema) +if status != 0: + message = ffi.string(clib.last_error_message()).decode('utf-8', errors='replace') + raise RuntimeError(message) ptr_schema = int(ffi.cast('uintptr_t', ret_ptr_schema)) ptr_array = int(ffi.cast('uintptr_t', ret_ptr_array)) diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..e0cc662 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,20 @@ +use klamath_rs_ext::{basic::encode_real8, records}; + +pub fn record(out: &mut Vec, tag: u16, data: &[u8]) { + out.extend_from_slice(&u16::try_from(data.len() + 4).unwrap().to_be_bytes()); + out.extend_from_slice(&tag.to_be_bytes()); + out.extend_from_slice(data); +} + +pub fn library_header() -> Vec { + let mut bytes = Vec::new(); + record(&mut bytes, records::RTAG_HEADER, &600_i16.to_be_bytes()); + record(&mut bytes, records::RTAG_BGNLIB, &[0; 24]); + record(&mut bytes, records::RTAG_LIBNAME, b"test"); + let units: Vec = [0.001, 1e-9] + .into_iter() + .flat_map(|v| encode_real8(v).unwrap().to_be_bytes()) + .collect(); + record(&mut bytes, records::RTAG_UNITS, &units); + bytes +} diff --git a/tests/ffi_errors.rs b/tests/ffi_errors.rs new file mode 100644 index 0000000..68186e2 --- /dev/null +++ b/tests/ffi_errors.rs @@ -0,0 +1,157 @@ +mod common; + +use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; +use klamath_rs_ext::{last_error_message, read_path, read_cells_bytes, scan_bytes, records}; +use std::{ffi::{CStr, CString}, fs, path::PathBuf, ptr}; + +struct TestFile(PathBuf); + +impl TestFile { + fn new(name: &str, contents: &[u8]) -> Self { + let path = std::env::temp_dir().join(format!("klamath-{name}-{}.gds", std::process::id())); + fs::write(&path, contents).unwrap(); + Self(path) + } + + fn cpath(&self) -> CString { + CString::new(self.0.to_str().unwrap()).unwrap() + } +} + +impl Drop for TestFile { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +fn error_message() -> String { + let message = last_error_message(); + assert!(!message.is_null()); + unsafe { CStr::from_ptr(message) }.to_str().unwrap().to_owned() +} + +#[test] +fn path_errors_preserve_outputs_and_convert_parser_panics() { + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!(unsafe { read_path(ptr::null(), &mut array, &mut schema) }, -1); + assert!(error_message().contains("path pointer was null")); + assert!(array.is_released()); + + // A mismatched timestamp size currently makes Record::read panic. + let mut bytes = Vec::new(); + common::record(&mut bytes, records::RTAG_HEADER, &600_i16.to_be_bytes()); + common::record(&mut bytes, records::RTAG_BGNLIB, &[0; 12]); + let file = TestFile::new("invalid-timestamps", &bytes); + assert_eq!(unsafe { read_path(file.cpath().as_ptr(), &mut array, &mut schema) }, -1); + assert!(error_message().contains("Expected record size")); + assert!(array.is_released()); + + let mut bytes = common::library_header(); + common::record(&mut bytes, records::RTAG_ENDLIB, &[]); + let file = TestFile::new("valid-empty", &bytes); + assert_eq!(unsafe { read_path(file.cpath().as_ptr(), &mut array, &mut schema) }, 0); + assert!(!array.is_released()); + assert!(last_error_message().is_null()); +} + +#[test] +fn other_threads_do_not_clear_or_free_error_messages() { + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!(unsafe { read_path(ptr::null(), &mut array, &mut schema) }, -1); + let pointer = last_error_message(); + let message = error_message(); + + std::thread::spawn(|| { + assert!(last_error_message().is_null()); + let mut bytes = common::library_header(); + common::record(&mut bytes, records::RTAG_ENDLIB, &[]); + let file = TestFile::new("thread-empty", &bytes); + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!(unsafe { read_path(ptr::null(), &mut array, &mut schema) }, -1); + assert_eq!(unsafe { read_path(file.cpath().as_ptr(), &mut array, &mut schema) }, 0); + assert!(last_error_message().is_null()); + }).join().unwrap(); + + assert_eq!(last_error_message(), pointer); + assert_eq!(unsafe { CStr::from_ptr(pointer) }.to_str().unwrap(), message); +} + +#[test] +fn null_arrow_outputs_return_an_error() { + assert_eq!(unsafe { read_path(ptr::null(), ptr::null_mut(), ptr::null_mut()) }, -1); + assert!(error_message().contains("Arrow output pointer was null")); +} + +#[test] +fn large_malformed_inputs_report_offsets_without_dumping_contents() { + let mut bytes = vec![0; 1024 * 1024 + 4]; + bytes[..4].copy_from_slice(&[0, 4, 0xff, 0xff]); + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + let file = TestFile::new("large-malformed", &bytes); + assert_eq!( + unsafe { scan_bytes(bytes.as_ptr(), bytes.len(), &mut array, &mut schema) }, + -1 + ); + let scan_message = error_message(); + assert_eq!( + unsafe { read_path(file.cpath().as_ptr(), &mut array, &mut schema) }, + -1 + ); + let read_message = error_message(); + assert_eq!( + unsafe { + read_cells_bytes( + bytes.as_ptr(), + bytes.len(), + ptr::null(), + 0, + &mut array, + &mut schema, + ) + }, + -1 + ); + let selected_message = error_message(); + for message in [scan_message, read_message, selected_message] { + assert!(message.contains("at byte 4"), "{message}"); + assert!(message.contains("Unexpected record"), "{message}"); + assert!(message.len() < 256); + } + assert!(array.is_released()); +} + +#[test] +fn selected_cell_errors_use_file_offsets_for_bounded_ranges() { + let mut bytes = common::library_header(); + let start = bytes.len() as u64; + common::record(&mut bytes, records::RTAG_BGNSTR, &[0; 24]); + common::record(&mut bytes, records::RTAG_STRNAME, b"top\0"); + common::record(&mut bytes, records::RTAG_ENDSTR, &[]); + let cell_end = bytes.len(); + common::record(&mut bytes, records::RTAG_ENDLIB, &[]); + let range_end = bytes.len() as u64; + bytes.resize(bytes.len() + 1024, 0); + let ranges = [start, range_end]; + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!( + unsafe { + read_cells_bytes( + bytes.as_ptr(), + bytes.len(), + ranges.as_ptr(), + 1, + &mut array, + &mut schema, + ) + }, + -1 + ); + assert!(error_message().contains(&format!( + "at byte {cell_end}: Cell byte range extends past ENDSTR" + ))); +} diff --git a/tests/golden/review-canonical.txt b/tests/golden/review-canonical.txt new file mode 100644 index 0000000..3cdc7ea --- /dev/null +++ b/tests/golden/review-canonical.txt @@ -0,0 +1,9 @@ +profile klamath-object-v2 +scope top=all cell=all layer=all +coordinates: integer database units; bounds: coordinate envelopes +HEADER=[600] +LIBNAME="test" +UNITS=[0.001, 9.999999999999999e-10] raw=0x3f04189374bc6a7f3a044b82fa09b5a5 +layer 1/0 name="WG" +cell "CHIP" + BOUNDARY layer=1 datatype=0 xy=[0, 0, 0, 10, 10, 10, 10, 0, 0, 0] diff --git a/tests/golden/review-diff.txt b/tests/golden/review-diff.txt new file mode 100644 index 0000000..57e6c09 --- /dev/null +++ b/tests/golden/review-diff.txt @@ -0,0 +1,7 @@ +profile klamath-object-v2 +scope top=all cell=all layer=all +cell "CHIP" old@Some(62) new@Some(62) + ~ BOUNDARY modified; coordinate bounds unchanged + - @98 bbox=Some([0, 0, 10, 10]) BOUNDARY layer=1 datatype=0 xy=[0, 0, 0, 10, 10, 10, 10, 0, 0, 0] + + @98 bbox=Some([0, 0, 10, 10]) BOUNDARY layer=1 datatype=0 xy=[0, 0, 0, 10, 10, 0, 0, 0] +1 changed cells; 2 of 2 object changes shown; 0 layer-name changes diff --git a/tests/golden/review-hierarchy.mmd b/tests/golden/review-hierarchy.mmd new file mode 100644 index 0000000..dcc963b --- /dev/null +++ b/tests/golden/review-hierarchy.mmd @@ -0,0 +1,10 @@ +flowchart TD + %% scope top=all cell=all layer=all + n0["CHIP [affected]"] + n1["leaf [cell changed]"] + n2["left [affected]"] + n3["right [affected]"] + n0 -->|"x1"| n2 + n0 -->|"x1"| n3 + n2 -->|"x2"| n1 + n3 -->|"x3"| n1 diff --git a/tests/golden/review-hierarchy.txt b/tests/golden/review-hierarchy.txt new file mode 100644 index 0000000..fa40d79 --- /dev/null +++ b/tests/golden/review-hierarchy.txt @@ -0,0 +1,6 @@ +scope top=all cell=all layer=all +"CHIP" x1 [affected] + "left" x1 [affected] + "leaf" x2 [cell changed] + "right" x1 [affected] + "leaf" x3 [cell changed] [shown above] diff --git a/tests/numeric_packing.rs b/tests/numeric_packing.rs new file mode 100644 index 0000000..4001514 --- /dev/null +++ b/tests/numeric_packing.rs @@ -0,0 +1,103 @@ +use klamath_rs_ext::*; +use std::{mem::size_of, slice}; + +// Read the packed prefix of each source slot, as the Python wrapper does. +fn packed_bytes(values: &[T], width: usize) -> Vec { + let bytes = unsafe { slice::from_raw_parts(values.as_ptr().cast::(), size_of_val(values)) }; + bytes + .chunks_exact(size_of::()) + .flat_map(|slot| slot[..width].iter().copied()) + .collect() +} + +macro_rules! check_int2 { + ($ty:ty, $function:ident) => {{ + let mut values = [0 as $ty, 1 as $ty, 256 as $ty, 32767 as $ty]; + assert_eq!( + unsafe { $function(values.as_mut_ptr(), values.len()) }, + 0 as $ty + ); + assert_eq!(packed_bytes(&values, 2), [0, 0, 0, 1, 1, 0, 0x7f, 0xff]); + }}; +} + +macro_rules! check_int4 { + ($ty:ty, $function:ident) => {{ + let mut values = [0 as $ty, 1 as $ty, 65536 as $ty, 2147483520_i64 as $ty]; + assert_eq!( + unsafe { $function(values.as_mut_ptr(), values.len()) }, + 0 as $ty + ); + assert_eq!( + packed_bytes(&values, 4), + [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0x7f, 0xff, 0xff, 0x80] + ); + }}; +} + +#[test] +fn all_source_types_pack_to_big_endian_integer_bytes() { + check_int2!(u16, u16_to_i16); + check_int2!(u32, u32_to_i16); + check_int2!(u64, u64_to_i16); + check_int2!(i16, i16_to_i16); + check_int2!(i32, i32_to_i16); + check_int2!(i64, i64_to_i16); + check_int2!(f32, f32_to_i16); + check_int2!(f64, f64_to_i16); + check_int4!(u32, u32_to_i32); + check_int4!(u64, u64_to_i32); + check_int4!(i32, i32_to_i32); + check_int4!(i64, i64_to_i32); + check_int4!(f32, f32_to_i32); + check_int4!(f64, f64_to_i32); +} + +#[test] +fn signed_limits_and_unsigned_overflows_are_checked() { + let mut signed = [i64::from(i16::MIN), -1]; + assert_eq!(unsafe { i64_to_i16(signed.as_mut_ptr(), signed.len()) }, 0); + assert_eq!(packed_bytes(&signed, 2), [0x80, 0, 0xff, 0xff]); + let mut signed = [i64::from(i32::MIN), i64::from(i32::MAX)]; + assert_eq!(unsafe { i64_to_i32(signed.as_mut_ptr(), signed.len()) }, 0); + assert_eq!( + packed_bytes(&signed, 4), + [0x80, 0, 0, 0, 0x7f, 0xff, 0xff, 0xff] + ); + + for value in [32768_u64, u64::MAX] { + let mut input = [value]; + assert_eq!(unsafe { u64_to_i16(input.as_mut_ptr(), 1) }, value); + assert_eq!(input, [value]); + } + for value in [2147483648_u64, u64::MAX] { + let mut input = [value]; + assert_eq!(unsafe { u64_to_i32(input.as_mut_ptr(), 1) }, value); + assert_eq!(input, [value]); + } +} + +#[test] +fn nonfinite_floats_and_rounded_up_f32_limit_are_rejected() { + for convert in [f32_to_i16, f32_to_i32] { + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mut input = [value]; + let result = unsafe { convert(input.as_mut_ptr(), 1) }; + assert_ne!(result, 0.0); + assert_eq!(input[0].to_bits(), value.to_bits()); + } + } + for convert in [f64_to_i16, f64_to_i32] { + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut input = [value]; + assert_ne!(unsafe { convert(input.as_mut_ptr(), 1) }, 0.0); + assert_eq!(input[0].to_bits(), value.to_bits()); + } + } + let mut input = [2147483648_f32]; + assert_eq!(unsafe { f32_to_i32(input.as_mut_ptr(), 1) }, 2147483648_f32); + assert_eq!(input, [2147483648_f32]); + let mut input = [-2147483648_f32]; + assert_eq!(unsafe { f32_to_i32(input.as_mut_ptr(), 1) }, 0.0); + assert_eq!(packed_bytes(&input, 4), [0x80, 0, 0, 0]); +} diff --git a/tests/review.rs b/tests/review.rs new file mode 100644 index 0000000..829eeb5 --- /dev/null +++ b/tests/review.rs @@ -0,0 +1,1246 @@ +mod common; + +use common::{library_header, record}; +use klamath_rs_ext::{ + records::*, + review::{Comparison, Document, LAYER_SENTINEL, hierarchy}, +}; +use std::{fs, path::PathBuf, process::Command}; + +fn ascii(bytes: &mut Vec, tag: u16, value: &str) { + let mut value = value.as_bytes().to_vec(); + if value.len() % 2 == 1 { + value.push(0); + } + record(bytes, tag, &value); +} + +fn xy(bytes: &mut Vec, points: &[[i32; 2]]) { + record( + bytes, + RTAG_XY, + &points + .iter() + .flatten() + .flat_map(|v| v.to_be_bytes()) + .collect::>(), + ); +} + +fn layout(cells: &[(&str, Vec>)]) -> Vec { + let mut bytes = library_header(); + for (name, objects) in cells { + record(&mut bytes, RTAG_BGNSTR, &[0; 24]); + ascii(&mut bytes, RTAG_STRNAME, name); + for object in objects { + bytes.extend_from_slice(object); + } + record(&mut bytes, RTAG_ENDSTR, &[]); + } + record(&mut bytes, RTAG_ENDLIB, &[]); + bytes +} + +fn polygon(points: &[[i32; 2]]) -> Vec { + let mut bytes = Vec::new(); + record(&mut bytes, RTAG_BOUNDARY, &[]); + record(&mut bytes, RTAG_LAYER, &1_u16.to_be_bytes()); + record(&mut bytes, RTAG_DATATYPE, &0_u16.to_be_bytes()); + xy(&mut bytes, points); + record(&mut bytes, RTAG_ENDEL, &[]); + bytes +} + +fn square() -> Vec { + polygon(&[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]) +} + +fn triangle() -> Vec { + polygon(&[[0, 0], [10, 0], [0, 10], [0, 0]]) +} + +fn reference(target: &str, x: i32, count: i16) -> Vec { + let mut bytes = Vec::new(); + record( + &mut bytes, + if count == 1 { RTAG_SREF } else { RTAG_AREF }, + &[], + ); + ascii(&mut bytes, RTAG_SNAME, target); + if count == 1 { + xy(&mut bytes, &[[x, 0]]); + } else { + let counts: Vec<_> = [count, 1].into_iter().flat_map(i16::to_be_bytes).collect(); + record(&mut bytes, RTAG_COLROW, &counts); + xy(&mut bytes, &[[x, 0], [x + 100, 0], [x, 0]]); + } + record(&mut bytes, RTAG_ENDEL, &[]); + bytes +} + +fn label(carrier: (u16, u16), text: &str) -> Vec { + let mut bytes = Vec::new(); + record(&mut bytes, RTAG_TEXT, &[]); + record(&mut bytes, RTAG_LAYER, &carrier.0.to_be_bytes()); + record(&mut bytes, RTAG_TEXTTYPE, &carrier.1.to_be_bytes()); + xy(&mut bytes, &[[0, 0]]); + ascii(&mut bytes, RTAG_STRING, text); + record(&mut bytes, RTAG_ENDEL, &[]); + bytes +} + +fn with_property(mut object: Vec, value: &str) -> Vec { + object.truncate(object.len() - 4); + record(&mut object, RTAG_PROPATTR, &17_u16.to_be_bytes()); + ascii(&mut object, RTAG_PROPVALUE, value); + record(&mut object, RTAG_ENDEL, &[]); + object +} + +fn shared(geometry: Vec) -> Vec { + layout(&[ + ( + "CHIP", + vec![reference("left", 0, 1), reference("right", 20, 1)], + ), + ("left", vec![reference("leaf", 0, 2)]), + ("right", vec![reference("leaf", 0, 3)]), + ("leaf", vec![geometry]), + ]) +} + +struct Pair { + name: &'static str, + old: Vec, + new: Vec, + changed_cells: usize, + removed: usize, + added: usize, + metadata: usize, +} + +// Ten deliberately small fixture pairs specify the first object profile. +fn corpus() -> Vec { + let base = layout(&[("CHIP", vec![square(), label((2, 0), "port")])]); + let mut timestamps = base.clone(); + timestamps[10] = 1; // BGNLIB payload, ignored by the object profile. + let meta = |name| { + layout(&[( + "CHIP", + vec![ + square(), + label((900, 7), LAYER_SENTINEL), + label((900, 7), name), + ], + )]) + }; + vec![ + Pair { + name: "record reordering", + old: base.clone(), + new: layout(&[("CHIP", vec![label((2, 0), "port"), square()])]), + changed_cells: 0, + removed: 0, + added: 0, + metadata: 0, + }, + Pair { + name: "timestamp edit", + old: base, + new: timestamps, + changed_cells: 0, + removed: 0, + added: 0, + metadata: 0, + }, + Pair { + name: "polygon start and winding", + old: layout(&[("CHIP", vec![square()])]), + new: layout(&[( + "CHIP", + vec![polygon(&[[10, 10], [10, 0], [0, 0], [0, 10], [10, 10]])], + )]), + changed_cells: 0, + removed: 0, + added: 0, + metadata: 0, + }, + Pair { + name: "duplicate shape", + old: layout(&[("CHIP", vec![square()])]), + new: layout(&[("CHIP", vec![square(), square()])]), + changed_cells: 1, + removed: 0, + added: 1, + metadata: 0, + }, + Pair { + name: "same bounds different geometry", + old: layout(&[("CHIP", vec![square()])]), + new: layout(&[("CHIP", vec![triangle()])]), + changed_cells: 1, + removed: 1, + added: 1, + metadata: 0, + }, + Pair { + name: "moved reference", + old: layout(&[ + ("CHIP", vec![reference("leaf", 0, 1)]), + ("leaf", vec![square()]), + ]), + new: layout(&[ + ("CHIP", vec![reference("leaf", 5, 1)]), + ("leaf", vec![square()]), + ]), + changed_cells: 1, + removed: 1, + added: 1, + metadata: 0, + }, + Pair { + name: "array count", + old: layout(&[ + ("CHIP", vec![reference("leaf", 0, 2)]), + ("leaf", vec![square()]), + ]), + new: layout(&[ + ("CHIP", vec![reference("leaf", 0, 3)]), + ("leaf", vec![square()]), + ]), + changed_cells: 1, + removed: 1, + added: 1, + metadata: 0, + }, + Pair { + name: "element property", + old: layout(&[("CHIP", vec![with_property(square(), "old")])]), + new: layout(&[("CHIP", vec![with_property(square(), "new")])]), + changed_cells: 1, + removed: 1, + added: 1, + metadata: 0, + }, + Pair { + name: "layer name only", + old: meta("1:0:WG"), + new: meta("1:0:CORE:WG"), + changed_cells: 0, + removed: 0, + added: 0, + metadata: 1, + }, + Pair { + name: "shared changed descendant", + old: shared(square()), + new: shared(triangle()), + changed_cells: 1, + removed: 1, + added: 1, + metadata: 0, + }, + ] +} + +#[test] +fn ten_fixture_pairs_have_explicit_expected_changes() { + for pair in corpus() { + let old = Document::parse(&pair.old).unwrap(); + let new = Document::parse(&pair.new).unwrap(); + let diff = Comparison::between(&old, &new); + assert!(diff.issues.is_empty(), "{}: {:?}", pair.name, diff.issues); + assert_eq!(diff.cells.len(), pair.changed_cells, "{}", pair.name); + assert_eq!( + diff.cells.iter().map(|c| c.removed.len()).sum::(), + pair.removed, + "{}", + pair.name + ); + assert_eq!( + diff.cells.iter().map(|c| c.added.len()).sum::(), + pair.added, + "{}", + pair.name + ); + assert_eq!(diff.layer_names.len(), pair.metadata, "{}", pair.name); + let equal = pair.changed_cells + pair.metadata == 0; + assert_eq!(diff.is_equal(), equal, "{}", pair.name); + assert_eq!( + old.canonical_dump() == new.canonical_dump(), + equal, + "{}", + pair.name + ); + assert_eq!(diff.exit_code(), if equal { 0 } else { 1 }); + } +} + +#[test] +fn canonical_polygon_dump_is_readable_and_offsets_are_separate() { + let bytes = layout(&[("CHIP", vec![square()])]); + let doc = Document::parse(&bytes).unwrap(); + let dump = doc.canonical_dump(); + assert!( + dump.ends_with( + "cell \"CHIP\"\n BOUNDARY layer=1 datatype=0 xy=[0, 0, 0, 10, 10, 10, 10, 0, 0, 0]\n" + ), + "{dump}" + ); + assert!(!dump.contains("BGNSTR")); + assert!( + doc.record_dump() + .contains("0000000000 0002 HEADER size=6 [600]") + ); + assert!(doc.record_dump().contains("BGNSTR")); +} + +#[test] +fn canonical_dump_and_hierarchy_match_versioned_goldens() { + let bytes = layout(&[( + "CHIP", + vec![ + square(), + label((900, 7), LAYER_SENTINEL), + label((900, 7), "1:0:WG"), + ], + )]); + assert_eq!( + Document::parse(&bytes).unwrap().canonical_dump(), + include_str!("golden/review-canonical.txt") + ); + let a = shared(square()); + let b = shared(triangle()); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + let diff = Comparison::between(&a, &b); + assert_eq!( + hierarchy(&a, &b, Some(&diff), false, 8), + include_str!("golden/review-hierarchy.txt") + ); + assert_eq!( + hierarchy(&a, &b, Some(&diff), true, 8), + include_str!("golden/review-hierarchy.mmd") + ); +} + +#[test] +fn misplaced_library_fields_and_nul_names_are_rejected() { + let mut late = layout(&[("CHIP", vec![])]); + late.truncate(late.len() - 4); + ascii(&mut late, RTAG_LIBNAME, "late"); + record(&mut late, RTAG_ENDLIB, &[]); + assert!( + Document::parse(&late) + .unwrap_err() + .contains("library field outside") + ); + assert!( + Document::parse(&layout(&[("CH\0IP", vec![])])) + .unwrap_err() + .contains("NUL") + ); +} + +#[test] +fn cell_and_property_order_do_not_affect_comparison() { + let a = with_property(with_property(square(), "a"), "b"); + let b = with_property(with_property(square(), "b"), "a"); + let a = layout(&[("z", vec![a]), ("a", vec![])]); + let b = layout(&[("a", vec![]), ("z", vec![b])]); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + assert!(Comparison::between(&a, &b).is_equal()); + assert_eq!(a.canonical_dump(), b.canonical_dump()); +} + +#[test] +fn metadata_requires_a_sentinel_in_the_same_cell_and_carrier_pair() { + let bytes = layout(&[ + ( + "CHIP", + vec![ + label((900, 7), LAYER_SENTINEL), + label((900, 7), "1:0:WG"), + label((900, 8), "2:0:ordinary text"), + ], + ), + ("OTHER", vec![label((900, 7), "3:0:ordinary text")]), + ]); + let doc = Document::parse(&bytes).unwrap(); + assert_eq!(doc.layer_names.len(), 1); + assert_eq!(doc.layer_names.get(&(1, 0)).unwrap(), "WG"); + assert!(doc.canonical_dump().contains("2:0:ordinary text")); + assert!(doc.canonical_dump().contains("3:0:ordinary text")); + assert!(!doc.canonical_dump().contains(LAYER_SENTINEL)); + let conflicts = layout(&[( + "CHIP", + vec![ + label((9, 0), LAYER_SENTINEL), + label((9, 0), "1:0:A"), + label((9, 0), "1:0:B"), + ], + )]); + assert!( + Document::parse(&conflicts) + .unwrap_err() + .contains("conflicting names") + ); + assert!( + klamath_rs_ext::review::dump_records(&conflicts) + .unwrap() + .contains("1:0:B") + ); + let future = layout(&[("CHIP", vec![label((9, 0), "KLAMATH_LAYER_NAMES_V2")])]); + let future = Document::parse(&future).unwrap(); + assert_eq!(Comparison::between(&future, &future).exit_code(), 2); +} + +#[test] +fn unknown_records_never_produce_a_successful_equality_claim() { + let mut unknown = square(); + unknown.truncate(unknown.len() - 4); + record(&mut unknown, 0x7f00, &[]); + record(&mut unknown, RTAG_ENDEL, &[]); + let bytes = layout(&[("CHIP", vec![unknown])]); + let doc = Document::parse(&bytes).unwrap(); + let diff = Comparison::between(&doc, &doc); + assert!(!diff.is_equal()); + assert_eq!(diff.exit_code(), 2); + assert!(doc.record_dump().contains("7f00")); + assert!(diff.text(0).contains("INCOMPLETE")); +} + +#[test] +fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() { + let a = shared(square()); + let b = shared(triangle()); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + let diff = Comparison::between(&a, &b); + assert_eq!( + hierarchy(&a, &b, Some(&diff), false, 8), + concat!( + "scope top=all cell=all layer=all\n", + "\"CHIP\" x1 [affected]\n", + " \"left\" x1 [affected]\n", + " \"leaf\" x2 [cell changed]\n", + " \"right\" x1 [affected]\n", + " \"leaf\" x3 [cell changed] [shown above]\n", + ) + ); + let graph = hierarchy(&a, &b, Some(&diff), true, 8); + assert_eq!(graph.matches("leaf [cell changed]").count(), 1); + assert!(graph.contains("x2")); + assert!(graph.contains("x3")); + let limited = hierarchy(&a, &b, Some(&diff), false, 1); + assert!(!limited.contains("\"leaf\"")); + assert!(limited.contains("children omitted")); +} + +#[test] +fn reference_changes_keep_unchanged_targets_and_old_edges_visible() { + for pair in corpus() + .into_iter() + .filter(|p| p.name == "moved reference" || p.name == "array count") + { + let old = Document::parse(&pair.old).unwrap(); + let new = Document::parse(&pair.new).unwrap(); + let diff = Comparison::between(&old, &new); + let tree = hierarchy(&old, &new, Some(&diff), false, 8); + assert!(tree.contains("[cell unchanged]"), "{tree}"); + assert!(tree.contains("[reference changed]"), "{tree}"); + if pair.name == "array count" { + assert!(tree.contains("x2 -> x3"), "{tree}"); + } + } + let a = layout(&[ + ("CHIP", vec![reference("leaf", 0, 1)]), + ("leaf", vec![square()]), + ]); + let b = layout(&[("CHIP", vec![])]); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + let tree = hierarchy(&a, &b, Some(&Comparison::between(&a, &b)), false, 8); + assert!(tree.contains("\"leaf\" x1 -> x0"), "{tree}"); +} + +#[test] +fn same_bounds_changes_and_truncated_reports_remain_differences() { + let a = layout(&[("CHIP", vec![square()])]); + let b = layout(&[("CHIP", vec![triangle()])]); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + let diff = Comparison::between(&a, &b); + assert_eq!( + diff.cells[0].removed[0].bounds, + diff.cells[0].added[0].bounds + ); + assert!(diff.text(0).contains("0 of 2 object changes shown")); + assert_eq!(diff.exit_code(), 1); + assert!(diff.cells[0].removed[0].offset > 0); +} + +#[test] +fn unit_changes_report_values_without_claiming_geometry_equivalence() { + let a = layout(&[("CHIP", vec![square()])]); + let units = Document::parse(&a) + .unwrap() + .records + .iter() + .find(|r| r.tag == RTAG_UNITS) + .unwrap() + .offset; + let mut b = a.clone(); + b[units + 12..units + 20].copy_from_slice( + &klamath_rs_ext::basic::encode_real8(2e-9) + .unwrap() + .to_be_bytes(), + ); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + let diff = Comparison::between(&a, &b); + assert_eq!(diff.exit_code(), 1); + assert_eq!(diff.library_fields.len(), 1); + assert_eq!(diff.library_fields[0].field, "UNITS"); + assert!(diff.text(0).contains("UNITS changed")); + assert!(diff.cells.is_empty()); +} + +#[test] +fn dangling_references_cycles_and_duplicate_cell_names_are_reported() { + let missing = layout(&[("CHIP", vec![reference("missing", 0, 1)])]); + let missing = Document::parse(&missing).unwrap(); + assert!( + missing + .issues + .iter() + .any(|s| s.contains("unresolved reference")) + ); + let cycle = layout(&[ + ("a", vec![reference("b", 0, 1)]), + ("b", vec![reference("a", 0, 1)]), + ]); + let cycle = Document::parse(&cycle).unwrap(); + assert!(cycle.issues.iter().any(|s| s.contains("cyclic"))); + assert!(hierarchy(&cycle, &cycle, None, false, 8).len() < 200); + let duplicate = layout(&[("a", vec![]), ("a", vec![])]); + assert!( + Document::parse(&duplicate) + .unwrap_err() + .contains("duplicate cell") + ); +} + +#[test] +fn absolute_transform_flags_are_not_discarded() { + let a = reference("leaf", 0, 1); + let mut b = Vec::new(); + record(&mut b, RTAG_SREF, &[]); + ascii(&mut b, RTAG_SNAME, "leaf"); + record(&mut b, RTAG_STRANS, &[0, 2]); + xy(&mut b, &[[0, 0]]); + record(&mut b, RTAG_ENDEL, &[]); + let a = layout(&[("CHIP", vec![a]), ("leaf", vec![])]); + let b = layout(&[("CHIP", vec![b]), ("leaf", vec![])]); + assert_eq!( + Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()) + .exit_code(), + 1 + ); +} + +#[test] +fn polygon_normalization_handles_repeated_minimum_vertices() { + let ring = [[0, 0], [4, 0], [4, 4], [0, 0], [-2, 2], [-2, 4], [0, 0]]; + let baseline = layout(&[("CHIP", vec![polygon(&ring)])]); + let baseline = Document::parse(&baseline).unwrap(); + let mut open = ring[..ring.len() - 1].to_vec(); + for _ in 0..2 { + for start in 0..open.len() { + let mut rotated = open[start..] + .iter() + .chain(&open[..start]) + .copied() + .collect::>(); + rotated.push(rotated[0]); + let candidate = layout(&[("CHIP", vec![polygon(&rotated)])]); + let candidate = Document::parse(&candidate).unwrap(); + assert!(Comparison::between(&baseline, &candidate).is_equal()); + } + open.reverse(); + } +} + +#[test] +fn malformed_lengths_fields_and_units_return_errors_without_panicking() { + let good = layout(&[("CHIP", vec![square()])]); + for length in 0..good.len() { + assert!( + Document::parse(&good[..length]).is_err(), + "accepted truncated length {length}" + ); + } + let mut bad = good.clone(); + bad[0..2].copy_from_slice(&3_u16.to_be_bytes()); + assert!(Document::parse(&bad).is_err()); + let mut bad = good.clone(); + let units = Document::parse(&good) + .unwrap() + .records + .iter() + .find(|r| r.tag == RTAG_UNITS) + .unwrap() + .offset; + bad[units + 4..units + 20].fill(0); + assert!(Document::parse(&bad).unwrap_err().contains("UNITS")); + let mut polygon = square(); + polygon.truncate(polygon.len() - 4); + record(&mut polygon, RTAG_LAYER, &[0, 1]); + record(&mut polygon, RTAG_ENDEL, &[]); + assert!( + Document::parse(&layout(&[("CHIP", vec![polygon])])) + .unwrap_err() + .contains("duplicate element field") + ); +} + +#[test] +fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() { + let directory = std::env::temp_dir().join(format!("klamath review {}", std::process::id())); + fs::create_dir_all(&directory).unwrap(); + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + let _cleanup = Cleanup(directory.clone()); + let old = directory.join("old file.gds"); + let new = directory.join("new file.gds"); + fs::write(&old, shared(square())).unwrap(); + fs::write(&new, shared(triangle())).unwrap(); + let command = || Command::new(env!("CARGO_BIN_EXE_klamath")); + let equal = command().arg("diff").arg(&old).arg(&old).output().unwrap(); + assert_eq!(equal.status.code(), Some(0)); + let diff = command() + .arg("diff") + .arg(&old) + .arg(&new) + .args(["--hierarchy", "mermaid", "--max-changes", "0"]) + .output() + .unwrap(); + assert_eq!(diff.status.code(), Some(1)); + let text = String::from_utf8(diff.stdout).unwrap(); + assert!(text.contains("0 of 2 object changes shown")); + assert!(text.contains("```mermaid\nflowchart TD")); + let dump = command() + .arg("dump") + .arg(&old) + .args(["--records"]) + .output() + .unwrap(); + assert_eq!(dump.status.code(), Some(0)); + assert!(String::from_utf8(dump.stdout).unwrap().contains("BGNSTR")); + let graph = command() + .arg("hierarchy") + .arg(&old) + .args(["--format", "mermaid"]) + .output() + .unwrap(); + assert_eq!(graph.status.code(), Some(0)); + assert!( + String::from_utf8(graph.stdout) + .unwrap() + .starts_with("flowchart TD") + ); + fs::write(&new, b"invalid").unwrap(); + assert_eq!( + command() + .arg("diff") + .arg(&old) + .arg(&new) + .output() + .unwrap() + .status + .code(), + Some(2) + ); +} + +#[test] +fn metadata_writer_preserves_unrelated_bytes_and_consolidates_updates() { + use klamath_rs_ext::review::write_layer_names; + use std::collections::BTreeMap; + let mut bytes = shared(with_property(square(), "keep this")); + bytes.extend_from_slice(&[0; 32]); + let updates = BTreeMap::from([ + ((1, 0), "WG".to_string()), + ((2, 3), "HEATER:draw".to_string()), + ]); + let output = write_layer_names(&bytes, "CHIP", (900, 7), &updates).unwrap(); + let doc = Document::parse(&output).unwrap(); + assert_eq!(doc.layer_names, updates); + let meta: Vec<_> = doc.cells["CHIP"] + .objects + .iter() + .filter(|o| o.layer == Some((900, 7))) + .collect(); + let start = meta.iter().map(|o| o.offset).min().unwrap(); + let end = meta.iter().map(|o| o.end_offset).max().unwrap(); + assert_eq!([&output[..start], &output[end..]].concat(), bytes); + let updated = write_layer_names( + &output, + "CHIP", + (900, 7), + &BTreeMap::from([((1, 0), "CORE".to_string())]), + ) + .unwrap(); + let parsed = Document::parse(&updated).unwrap(); + assert_eq!(parsed.layer_names[&(1, 0)], "CORE"); + assert_eq!(parsed.layer_names[&(2, 3)], "HEATER:draw"); + assert_eq!( + parsed.cells["CHIP"] + .objects + .iter() + .filter(|o| o.layer == Some((900, 7))) + .count(), + 3 + ); + let diff = Comparison::between(&Document::parse(&output).unwrap(), &parsed); + assert!(diff.cells.is_empty()); + assert_eq!(diff.layer_names.len(), 1); + assert_eq!( + write_layer_names(&updated, "CHIP", (900, 7), &BTreeMap::new()).unwrap(), + updated + ); +} + +#[test] +fn metadata_writer_rejects_ambiguous_carriers_versions_and_bad_names() { + use klamath_rs_ext::review::{parse_layer_name, write_layer_names}; + use std::collections::BTreeMap; + let bytes = layout(&[("CHIP", vec![label((900, 7), "ordinary label")])]); + assert!( + write_layer_names(&bytes, "CHIP", (900, 7), &BTreeMap::new()) + .unwrap_err() + .contains("ordinary design") + ); + assert!( + write_layer_names(&bytes, "missing", (901, 7), &BTreeMap::new()) + .unwrap_err() + .contains("does not exist") + ); + let bytes = layout(&[("CHIP", vec![label((900, 7), "KLAMATH_LAYER_NAMES_V2")])]); + assert!( + write_layer_names(&bytes, "CHIP", (901, 7), &BTreeMap::new()) + .unwrap_err() + .contains("unsupported") + ); + let bytes = layout(&[("CHIP", vec![square()])]); + for value in ["".to_string(), "bad\0name".to_string(), "x".repeat(65536)] { + assert!( + write_layer_names(&bytes, "CHIP", (901, 7), &BTreeMap::from([((1, 0), value)])) + .is_err() + ); + } + for text in ["+1:0:name", "1:-1:name", "1:0:", "65536:0:name"] { + assert!(parse_layer_name(text).is_err()); + } +} + +#[test] +fn metadata_cli_creates_a_separate_file_and_refuses_existing_output() { + let directory = std::env::temp_dir().join(format!("klamath-metadata-{}", std::process::id())); + fs::create_dir_all(&directory).unwrap(); + let source = directory.join("source.gds"); + let output = directory.join("output.gds"); + let bytes = shared(square()); + fs::write(&source, &bytes).unwrap(); + let _ = fs::remove_file(&output); + let mut command = Command::new(env!("CARGO_BIN_EXE_klamath")); + command.arg("name-layers").arg(&source).arg(&output).args([ + "--cell", + "CHIP", + "--carrier", + "900/7", + "--name", + "1:0:WG", + ]); + let result = command.output().unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + assert_eq!(fs::read(&source).unwrap(), bytes); + let generated = fs::read(&output).unwrap(); + assert_eq!( + Document::parse(&generated).unwrap().layer_names[&(1, 0)], + "WG" + ); + assert_eq!(command.output().unwrap().status.code(), Some(2)); + assert_eq!(fs::read(&output).unwrap(), generated); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn scope_selection_distinguishes_reachable_subtrees_from_exact_cells() { + use klamath_rs_ext::review::Scope; + let a = layout(&[ + ("CHIP", vec![reference("leaf", 0, 1)]), + ("leaf", vec![square()]), + ("unused", vec![square()]), + ]); + let b = layout(&[ + ("CHIP", vec![reference("leaf", 0, 1)]), + ("leaf", vec![triangle()]), + ("unused", vec![triangle()]), + ]); + let top = Scope { + top: Some("CHIP".to_string()), + ..Scope::default() + }; + let old = Document::parse(&a).unwrap().selected(&top, false).unwrap(); + let new = Document::parse(&b).unwrap().selected(&top, false).unwrap(); + assert_eq!( + old.cells.keys().map(String::as_str).collect::>(), + ["CHIP", "leaf"] + ); + assert_eq!(Comparison::between(&old, &new).cells.len(), 1); + assert!(old.canonical_dump().contains("scope top=\"CHIP\"")); + let cell = Scope { + cell: Some("CHIP".to_string()), + ..Scope::default() + }; + let old = Document::parse(&a).unwrap().selected(&cell, false).unwrap(); + let new = Document::parse(&b).unwrap().selected(&cell, false).unwrap(); + assert!(old.issues.is_empty()); + assert!(Comparison::between(&old, &new).is_equal()); + let missing = Scope { + top: Some("missing".to_string()), + ..Scope::default() + }; + assert!( + Document::parse(&a) + .unwrap() + .selected(&missing, false) + .is_err() + ); + let wrong = Scope { + top: Some("CHIP".to_string()), + cell: Some("unused".to_string()), + layer: None, + }; + assert!( + wrong + .validate_pair(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()) + .is_err() + ); +} + +#[test] +fn layer_scope_filters_geometry_and_references_by_descendant_coverage() { + use klamath_rs_ext::review::Scope; + let mut other_layer = square(); + other_layer[8..10].copy_from_slice(&2_u16.to_be_bytes()); + let a = layout(&[ + ( + "CHIP", + vec![reference("wg", 0, 1), reference("heater", 0, 1)], + ), + ("wg", vec![square()]), + ("heater", vec![other_layer.clone()]), + ]); + let b = layout(&[ + ( + "CHIP", + vec![reference("wg", 0, 1), reference("heater", 5, 1)], + ), + ("wg", vec![square()]), + ("heater", vec![other_layer]), + ]); + for (layer, expected) in [((1, 0), 0), ((2, 0), 1)] { + let scope = Scope { + layer: Some(layer), + ..Scope::default() + }; + let old = Document::parse(&a) + .unwrap() + .selected(&scope, false) + .unwrap(); + let new = Document::parse(&b) + .unwrap() + .selected(&scope, false) + .unwrap(); + assert_eq!(Comparison::between(&old, &new).exit_code(), expected); + assert!(old.issues.is_empty()); + } +} + +#[test] +fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() { + use klamath_rs_ext::review::Scope; + let mut unknown = square(); + unknown.truncate(unknown.len() - 4); + record(&mut unknown, 0x7f00, &[]); + record(&mut unknown, RTAG_ENDEL, &[]); + let bytes = layout(&[("CHIP", vec![square()]), ("unused", vec![unknown])]); + let scope = Scope { + cell: Some("CHIP".to_string()), + ..Scope::default() + }; + assert!( + Document::parse(&bytes) + .unwrap() + .selected(&scope, false) + .unwrap() + .issues + .is_empty() + ); + let scope = Scope { + cell: Some("unused".to_string()), + ..Scope::default() + }; + assert!( + !Document::parse(&bytes) + .unwrap() + .selected(&scope, false) + .unwrap() + .issues + .is_empty() + ); + let bytes = layout(&[ + ("a", vec![reference("b", 0, 1)]), + ("b", vec![reference("a", 0, 1)]), + ]); + let scope = Scope { + layer: Some((999, 0)), + ..Scope::default() + }; + assert!( + Document::parse(&bytes) + .unwrap() + .selected(&scope, false) + .unwrap() + .issues + .iter() + .any(|s| s.contains("cyclic")) + ); +} + +#[test] +fn display_filters_never_change_equality_or_totals() { + use klamath_rs_ext::review::DisplayFilter; + let a = layout(&[("CHIP", vec![square()])]); + let b = layout(&[("CHIP", vec![triangle()])]); + let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); + let text = diff.text_filtered( + 100, + &DisplayFilter { + cell: None, + layer: Some((42, 0)), + }, + ); + assert!(text.contains("display-only")); + assert!(text.contains("0 of 2 object changes shown")); + assert_eq!(diff.exit_code(), 1); +} + +#[test] +fn git_external_driver_handles_changes_additions_deletions_and_errors() { + let directory = std::env::temp_dir().join(format!( + "klamath-git-review-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&directory).unwrap(); + let inherited_path = std::env::var_os("PATH").unwrap_or_default(); + let git_path = std::env::join_paths( + std::iter::once( + PathBuf::from(env!("CARGO_BIN_EXE_klamath")) + .parent() + .unwrap() + .to_path_buf(), + ) + .chain(std::env::split_paths(&inherited_path)), + ) + .unwrap(); + let git = |args: &[&str]| { + let result = Command::new("git") + .env("PATH", &git_path) + .arg("-C") + .arg(&directory) + .args(args) + .output() + .unwrap(); + assert!( + result.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&result.stderr) + ); + result + }; + git(&["init", "-q"]); + git(&["config", "user.name", "Review Fixture"]); + git(&["config", "user.email", "fixture@example.invalid"]); + git(&["config", "commit.gpgsign", "false"]); + git(&["config", "core.hooksPath", "/dev/null"]); + git(&[ + "config", + "include.path", + concat!(env!("CARGO_MANIFEST_DIR"), "/contrib/git/config"), + ]); + assert_eq!( + String::from_utf8(git(&["config", "--get", "diff.klamath.trustExitCode"]).stdout) + .unwrap() + .trim(), + "false" + ); + fs::write( + directory.join(".gitattributes"), + include_str!("../contrib/git/attributes"), + ) + .unwrap(); + let path = directory.join("chip layout.gds"); + fs::write(&path, layout(&[("CHIP", vec![square()])])).unwrap(); + git(&["add", "."]); + git(&["commit", "-qm", "baseline"]); + fs::write(&path, layout(&[("CHIP", vec![triangle()])])).unwrap(); + let changed = git(&["diff", "--", "chip layout.gds"]); + assert!( + String::from_utf8(changed.stdout) + .unwrap() + .contains("2 of 2 object changes shown") + ); + fs::write(&path, b"invalid").unwrap(); + let invalid = Command::new("git") + .env("PATH", &git_path) + .arg("-C") + .arg(&directory) + .args(["diff", "--", "chip layout.gds"]) + .output() + .unwrap(); + assert!(!invalid.status.success()); + assert!(String::from_utf8_lossy(&invalid.stderr).contains("klamath:")); + fs::write(&path, layout(&[("CHIP", vec![square()])])).unwrap(); + let added = directory.join("added layout.gds"); + fs::write(&added, shared(square())).unwrap(); + git(&["add", "added layout.gds"]); + let result = git(&["diff", "--cached", "--", "added layout.gds"]); + assert!( + String::from_utf8(result.stdout) + .unwrap() + .contains("layout added") + ); + fs::remove_file(&path).unwrap(); + git(&["add", "-u"]); + let result = git(&["diff", "--cached", "--", "chip layout.gds"]); + assert!( + String::from_utf8(result.stdout) + .unwrap() + .contains("layout deleted") + ); + // Textconv is an alternative to the external driver, with a separate cache. + git(&["commit", "-qm", "replace fixture"]); + git(&["mv", "added layout.gds", "renamed layout.gds"]); + let renamed = directory.join("renamed layout.gds"); + fs::write(&renamed, shared(triangle())).unwrap(); + git(&["add", "renamed layout.gds"]); + let result = git(&["diff", "--cached", "--find-renames"]); + let text = String::from_utf8(result.stdout).unwrap(); + assert!(text.contains("renamed layout.gds"), "{text}"); + assert!(text.contains("2 of 2 object changes shown"), "{text}"); + git(&["commit", "-qm", "rename fixture"]); + fs::write( + directory.join(".gitattributes"), + "*.gds diff=klamath-text\n", + ) + .unwrap(); + fs::write(&renamed, shared(square())).unwrap(); + let result = git(&["diff", "--", "renamed layout.gds"]); + assert!( + String::from_utf8(result.stdout) + .unwrap() + .contains("- BOUNDARY") + ); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn replacement_explanations_are_unique_and_keep_full_evidence() { + for pair in corpus().into_iter().filter(|p| { + [ + "same bounds different geometry", + "moved reference", + "array count", + ] + .contains(&p.name) + }) { + let old = Document::parse(&pair.old).unwrap(); + let new = Document::parse(&pair.new).unwrap(); + let diff = Comparison::between(&old, &new); + assert_eq!(diff.cells[0].replacements.len(), 1); + let text = diff.text(100); + assert!(text.contains(" ~ ")); + assert!(text.contains(" - @")); + assert!(text.contains(" + @")); + match pair.name { + "moved reference" => assert!(text.contains("delta=(5, 0) dbu")), + "array count" => assert!(text.contains("columns/rows 2 x 1 -> 3 x 1")), + _ => assert_eq!(text, include_str!("golden/review-diff.txt")), + } + assert!(!diff.text(0).contains(" ~ ")); + assert!(diff.text(1).contains("1 of 2 object changes shown")); + } + let a = layout(&[("CHIP", vec![square(), square()])]); + let b = layout(&[("CHIP", vec![triangle(), triangle()])]); + let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); + assert!(diff.cells[0].replacements.is_empty()); +} + +#[test] +fn path_width_explanation_preserves_absent_and_zero() { + let path = |width: Option| { + let mut bytes = Vec::new(); + record(&mut bytes, RTAG_PATH, &[]); + record(&mut bytes, RTAG_LAYER, &[0, 1]); + record(&mut bytes, RTAG_DATATYPE, &[0, 0]); + if let Some(n) = width { + record(&mut bytes, RTAG_WIDTH, &n.to_be_bytes()); + } + xy(&mut bytes, &[[0, 0], [10, 10]]); + record(&mut bytes, RTAG_ENDEL, &[]); + layout(&[("CHIP", vec![bytes])]) + }; + let a = path(None); + let b = path(Some(0)); + let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); + assert!(diff.text(100).contains("width absent -> 0 dbu")); +} + +#[test] +fn unchanged_layer_names_explain_geometry_changes_once() { + let named = |geometry| { + layout(&[( + "CHIP", + vec![ + geometry, + label((900, 7), LAYER_SENTINEL), + label((900, 7), "1:0:WG"), + ], + )]) + }; + let a = named(square()); + let b = named(triangle()); + let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); + let text = diff.text(100); + assert_eq!(text.matches("name=\"WG\"").count(), 1); + assert!(diff.layer_names.is_empty()); +} + +#[test] +fn an_added_empty_document_is_still_a_presence_change() { + let bytes = layout(&[]); + let doc = Document::parse(&bytes).unwrap(); + let diff = Comparison::between(&doc.empty_like(), &doc); + assert_eq!(diff.exit_code(), 1); + assert!(diff.text(0).contains("library presence:")); + assert!(!diff.text(0).contains("equal under")); +} + +#[test] +fn cli_scope_and_display_filters_have_distinct_exit_behavior() { + let directory = std::env::temp_dir().join(format!("klamath-scope-{}", std::process::id())); + fs::create_dir_all(&directory).unwrap(); + let old = directory.join("old.gds"); + let new = directory.join("new.gds"); + fs::write(&old, shared(square())).unwrap(); + fs::write(&new, shared(triangle())).unwrap(); + for (options, expected) in [ + (vec!["--cell", "CHIP"], 0), + (vec!["--top", "CHIP"], 1), + (vec!["--layer", "99/0"], 0), + (vec!["--show-cell", "missing"], 1), + (vec!["--show-layer", "99/0"], 1), + (vec!["--top", "missing"], 2), + ] { + let output = Command::new(env!("CARGO_BIN_EXE_klamath")) + .arg("diff") + .args(&options) + .arg(&old) + .arg(&new) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(expected), + "{options:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + fs::write(&old, layout(&[])).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_klamath")) + .args(["diff", "--top", "CHIP"]) + .arg(&old) + .arg(&new) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn large_polygons_and_billion_instance_arrays_stay_compact() { + let mut points = vec![[0, 0], [0, 1]]; + points.extend((1..8187).map(|x| [x, 1])); + points.extend([[8186, 0], [0, 0]]); + let mut array = Vec::new(); + record(&mut array, RTAG_AREF, &[]); + ascii(&mut array, RTAG_SNAME, "leaf"); + record(&mut array, RTAG_COLROW, &[0x7f, 0xff, 0x7f, 0xff]); + xy(&mut array, &[[0, 0], [32767, 0], [0, 32767]]); + record(&mut array, RTAG_ENDEL, &[]); + let bytes = layout(&[("CHIP", vec![array]), ("leaf", vec![polygon(&points)])]); + let doc = Document::parse(&bytes).unwrap(); + assert_eq!( + doc.edges()[&("CHIP".to_string(), "leaf".to_string())], + 32767 * 32767 + ); + assert_eq!(doc.cells["CHIP"].objects.len(), 1); + assert!(hierarchy(&doc, &doc, None, false, 8).len() < 200); + assert!(Comparison::between(&doc, &doc).is_equal()); +} + +#[test] +fn deep_hierarchy_comparison_and_rendering_are_iterative() { + let names: Vec<_> = (0..2048).map(|i| format!("cell_{i}")).collect(); + let cells = |leaf: Vec| { + names + .iter() + .enumerate() + .map(|(i, name)| { + ( + name.as_str(), + if i + 1 == names.len() { + vec![leaf.clone()] + } else { + vec![reference(&names[i + 1], 0, 1)] + }, + ) + }) + .collect::>() + }; + let a = layout(&cells(square())); + let b = layout(&cells(triangle())); + let a = Document::parse(&a).unwrap(); + let b = Document::parse(&b).unwrap(); + let diff = Comparison::between(&a, &b); + let tree = hierarchy(&a, &b, Some(&diff), false, 5); + assert_eq!(diff.cells.len(), 1); + assert!(tree.contains("children omitted")); + assert!(tree.len() < 500); +} diff --git a/tests/selective_reads.rs b/tests/selective_reads.rs new file mode 100644 index 0000000..a6ebeaa --- /dev/null +++ b/tests/selective_reads.rs @@ -0,0 +1,438 @@ +mod common; + +use arrow::array::{ + Array, BooleanArray, Float64Array, Int32Array, ListArray, StringArray, StructArray, + UInt32Array, UInt64Array, +}; +use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema, from_ffi}; +use common::{library_header, record}; +use klamath_rs_ext::{ + basic::encode_real8, + last_error_message, + library::{read_library, read_selected_library, scan_library}, + read_cells_bytes, records, scan_bytes, +}; +use std::{ffi::CStr, ptr}; + +fn xy(values: &[i32]) -> Vec { + values.iter().flat_map(|v| v.to_be_bytes()).collect() +} + +fn fixture() -> Vec { + let mut bytes = library_header(); + record(&mut bytes, records::RTAG_BGNSTR, &[0; 24]); + record(&mut bytes, records::RTAG_STRNAME, b"top\0"); + record(&mut bytes, records::RTAG_SREF, &[]); + record(&mut bytes, records::RTAG_SNAME, b"leaf"); + record(&mut bytes, records::RTAG_XY, &xy(&[3, -4])); + record(&mut bytes, records::RTAG_PROPATTR, &1_i16.to_be_bytes()); + record(&mut bytes, records::RTAG_PROPVALUE, b"value\0"); + record(&mut bytes, records::RTAG_ENDEL, &[]); + record(&mut bytes, records::RTAG_AREF, &[]); + record(&mut bytes, records::RTAG_SNAME, b"leaf"); + record(&mut bytes, records::RTAG_STRANS, &[0x80, 0]); + record( + &mut bytes, + records::RTAG_MAG, + &encode_real8(2.0).unwrap().to_be_bytes(), + ); + record( + &mut bytes, + records::RTAG_ANGLE, + &encode_real8(90.0).unwrap().to_be_bytes(), + ); + record(&mut bytes, records::RTAG_COLROW, &[0, 2, 0, 3]); + record(&mut bytes, records::RTAG_XY, &xy(&[-5, -7, 15, -7, -5, 23])); + record(&mut bytes, records::RTAG_ENDEL, &[]); + record(&mut bytes, records::RTAG_ENDSTR, &[]); + record(&mut bytes, records::RTAG_BGNSTR, &[0; 24]); + record(&mut bytes, records::RTAG_STRNAME, b"leaf"); + record(&mut bytes, records::RTAG_BOUNDARY, &[]); + record(&mut bytes, records::RTAG_LAYER, &1_i16.to_be_bytes()); + record(&mut bytes, records::RTAG_DATATYPE, &0_i16.to_be_bytes()); + record( + &mut bytes, + records::RTAG_XY, + &xy(&[0, 0, 10, 0, 10, 10, 0, 10, 0, 0]), + ); + record(&mut bytes, records::RTAG_ENDEL, &[]); + record(&mut bytes, records::RTAG_ENDSTR, &[]); + record(&mut bytes, records::RTAG_ENDLIB, &[]); + bytes +} + +fn list_struct(array: &StructArray, name: &str, row: usize) -> StructArray { + let list = array + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + list.value(row) + .as_any() + .downcast_ref::() + .unwrap() + .clone() +} + +fn aref_fixture(origin: [i32; 2], column: [i32; 2], row: [i32; 2], counts: [i16; 2]) -> Vec { + let mut bytes = library_header(); + record(&mut bytes, records::RTAG_BGNSTR, &[0; 24]); + record(&mut bytes, records::RTAG_STRNAME, b"top\0"); + record(&mut bytes, records::RTAG_AREF, &[]); + record(&mut bytes, records::RTAG_SNAME, b"leaf"); + let counts: Vec = counts.into_iter().flat_map(i16::to_be_bytes).collect(); + record(&mut bytes, records::RTAG_COLROW, &counts); + record( + &mut bytes, + records::RTAG_XY, + &xy(&[origin[0], origin[1], column[0], column[1], row[0], row[1]]), + ); + record(&mut bytes, records::RTAG_ENDEL, &[]); + record(&mut bytes, records::RTAG_ENDSTR, &[]); + record(&mut bytes, records::RTAG_ENDLIB, &[]); + bytes +} + +#[test] +fn aref_pitches_use_wide_coordinate_differences_in_full_reads_and_scans() { + let bytes = aref_fixture( + [i32::MIN, i32::MAX], + [i32::MAX - 1, i32::MIN + 1], + [i32::MIN, i32::MIN + 1], + [2, 2], + ); + let full_cells = list_struct(&read_library(&bytes).unwrap().1, "cells", 0); + let scan_cells = list_struct(&scan_library(&bytes).unwrap().1, "cells", 0); + for refs in [ + list_struct(&full_cells, "arefs", 0), + list_struct(&scan_cells, "refs", 0), + ] { + let column = u64_value(&refs, "xy0", 0); + let row = u64_value(&refs, "xy1", 0); + assert_eq!((column >> 32) as i32, i32::MAX); + assert_eq!(column as i32, -i32::MAX); + assert_eq!((row >> 32) as i32, 0); + assert_eq!(row as i32, -i32::MAX); + } +} + +#[test] +fn aref_invalid_counts_and_unrepresentable_pitches_return_errors() { + for counts in [[0, 1], [-1, 1], [1, 0], [1, -1]] { + let bytes = aref_fixture([0, 0], [10, 0], [0, 10], counts); + assert!(read_library(&bytes).is_err()); + assert!(scan_library(&bytes).is_err()); + } + let bytes = aref_fixture([i32::MIN, 0], [i32::MAX, 0], [i32::MIN, 10], [1, 2]); + assert!(read_library(&bytes).is_err()); + assert!(scan_library(&bytes).is_err()); +} + +#[test] +fn paths_preserve_missing_explicit_zero_and_negative_widths() { + let mut bytes = library_header(); + record(&mut bytes, records::RTAG_BGNSTR, &[0; 24]); + record(&mut bytes, records::RTAG_STRNAME, b"top\0"); + for width in [None, Some(0_i32), Some(-100)] { + record(&mut bytes, records::RTAG_PATH, &[]); + record(&mut bytes, records::RTAG_LAYER, &[0, 1]); + record(&mut bytes, records::RTAG_DATATYPE, &[0, 0]); + if let Some(width) = width { + record(&mut bytes, records::RTAG_WIDTH, &width.to_be_bytes()); + } + record(&mut bytes, records::RTAG_XY, &xy(&[0, 0, 10, 10])); + record(&mut bytes, records::RTAG_ENDEL, &[]); + } + record(&mut bytes, records::RTAG_ENDSTR, &[]); + record(&mut bytes, records::RTAG_ENDLIB, &[]); + let (_, full) = read_library(&bytes).unwrap(); + let (_, scan) = scan_library(&bytes).unwrap(); + let (_, selected) = read_selected_library(&bytes, &ranges(&scan)).unwrap(); + assert_eq!(full, selected); + let cells = list_struct(&full, "cells", 0); + let paths = list_struct(&cells, "paths", 0); + let widths = paths + .column_by_name("width") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + widths.iter().collect::>(), + [None, Some(0), Some(-100)] + ); +} + +fn u64_value(array: &StructArray, name: &str, row: usize) -> u64 { + array + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(row) +} + +fn ranges(scan: &StructArray) -> Vec<(u64, u64)> { + let cells = list_struct(scan, "cells", 0); + (0..cells.len()) + .map(|i| { + ( + u64_value(&cells, "struct_start_offset", i), + u64_value(&cells, "struct_end_offset", i), + ) + }) + .collect() +} + +#[test] +fn scanned_ranges_reproduce_the_full_library_including_offsets() { + let bytes = fixture(); + let (_, full) = read_library(&bytes).unwrap(); + let (scan_remaining, scan) = scan_library(&bytes).unwrap(); + assert!(scan_remaining.is_empty()); + let ranges = ranges(&scan); + assert_eq!(ranges.len(), 2); + for &(start, end) in &ranges { + assert_eq!(&bytes[start as usize..start as usize + 4], &[0, 28, 5, 2]); + assert_eq!(&bytes[end as usize - 4..end as usize], &[0, 4, 7, 0]); + } + let (remaining, selected) = read_selected_library(&bytes, &ranges).unwrap(); + assert_eq!(remaining, bytes); // Random access leaves the caller's cursor unchanged. + assert_eq!(full, selected); + let cells = list_struct(&full, "cells", 0); + assert_eq!(u64_value(&cells, "file_offset", 0), ranges[0].0 + 28 + 8); +} + +#[test] +fn scan_preserves_reference_transforms_and_skips_geometry() { + let bytes = fixture(); + let (_, scan) = scan_library(&bytes).unwrap(); + let cells = list_struct(&scan, "cells", 0); + let refs = list_struct(&cells, "refs", 0); + assert_eq!(refs.len(), 2); + assert_eq!(list_struct(&cells, "refs", 1).len(), 0); + let target = refs + .column_by_name("target") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(target.values().as_ref(), &[1, 1]); + assert_eq!( + u64_value(&refs, "xy", 0), + (3_u64 << 32) | (-4_i32 as u32 as u64) + ); + assert_eq!(u64_value(&refs, "xy0", 0), 0); + assert_eq!(u64_value(&refs, "xy1", 0), 0); + let counts = refs + .column_by_name("counts") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(counts.values().as_ref(), &[(1 << 16) | 1, (2 << 16) | 3]); + assert!( + refs.column_by_name("invert_y") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(1) + ); + assert_eq!( + refs.column_by_name("scale") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(1), + 2.0 + ); + assert_eq!( + refs.column_by_name("angle_rad") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(1), + std::f64::consts::FRAC_PI_2 + ); + assert_eq!(u64_value(&refs, "xy0", 1), 10_u64 << 32); + assert_eq!(u64_value(&refs, "xy1", 1), 10); +} + +#[test] +fn selections_support_subsets_reordering_and_empty_results() { + let bytes = fixture(); + let (_, scan) = scan_library(&bytes).unwrap(); + let ranges = ranges(&scan); + let (_, leaf) = read_selected_library(&bytes, &ranges[1..]).unwrap(); + let leaf_cells = list_struct(&leaf, "cells", 0); + assert_eq!(leaf_cells.len(), 1); + let leaf_names = leaf + .column_by_name("cell_names") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!( + leaf_names + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "leaf" + ); + let (_, reordered) = read_selected_library(&bytes, &[ranges[1], ranges[0]]).unwrap(); + let reordered_cells = list_struct(&reordered, "cells", 0); + assert_eq!( + u64_value(&reordered_cells, "file_offset", 0), + u64_value(&leaf_cells, "file_offset", 0) + ); + let refs = list_struct(&reordered_cells, "sref_props", 1); + assert_eq!( + refs.column_by_name("target") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 0 + ); + let (_, empty) = read_selected_library(&bytes, &[]).unwrap(); + assert_eq!(list_struct(&empty, "cells", 0).len(), 0); +} + +#[test] +fn selected_ranges_must_cover_exactly_one_complete_cell() { + let bytes = fixture(); + let (_, scan) = scan_library(&bytes).unwrap(); + let ranges = ranges(&scan); + let (start, end) = ranges[0]; + for range in [ + (end, start), + (start, u64::MAX), + (start, end - 1), + (start + 4, end), + (start, end + 4), + (start, ranges[1].1), + ] { + assert!( + read_selected_library(&bytes, &[range]).is_err(), + "accepted {range:?}" + ); + } +} + +#[test] +fn ffi_accepts_null_empty_ranges_and_exports_both_schemas() { + let bytes = fixture(); + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!( + unsafe { + read_cells_bytes( + bytes.as_ptr(), + bytes.len(), + ptr::null(), + 0, + &mut array, + &mut schema, + ) + }, + 0 + ); + let empty = StructArray::from(unsafe { from_ffi(array, &schema) }.unwrap()); + assert_eq!(list_struct(&empty, "cells", 0).len(), 0); + + let mut array = FFI_ArrowArray::empty(); + assert_eq!( + unsafe { scan_bytes(bytes.as_ptr(), bytes.len(), &mut array, &mut schema) }, + 0 + ); + let scan = StructArray::from(unsafe { from_ffi(array, &schema) }.unwrap()); + let ranges: Vec = ranges(&scan) + .into_iter() + .flat_map(|(a, b)| [a, b]) + .collect(); + let mut array = FFI_ArrowArray::empty(); + assert_eq!( + unsafe { + read_cells_bytes( + bytes.as_ptr(), + bytes.len(), + ranges.as_ptr(), + ranges.len() / 2, + &mut array, + &mut schema, + ) + }, + 0 + ); + let selected = StructArray::from(unsafe { from_ffi(array, &schema) }.unwrap()); + assert_eq!(selected, read_library(&bytes).unwrap().1); + assert!(last_error_message().is_null()); +} + +#[test] +fn ffi_rejects_null_nonempty_inputs_and_overflowing_range_counts() { + let bytes = fixture(); + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!( + unsafe { scan_bytes(ptr::null(), 0, &mut array, &mut schema) }, + -1 + ); + assert!( + unsafe { CStr::from_ptr(last_error_message()) } + .to_str() + .unwrap() + .contains("scan failed") + ); + assert_eq!( + unsafe { scan_bytes(ptr::null(), 1, &mut array, &mut schema) }, + -1 + ); + assert_eq!( + unsafe { + read_cells_bytes( + bytes.as_ptr(), + bytes.len(), + ptr::null(), + 1, + &mut array, + &mut schema, + ) + }, + -1 + ); + assert!( + unsafe { CStr::from_ptr(last_error_message()) } + .to_str() + .unwrap() + .contains("ranges pointer was null") + ); + assert_eq!( + unsafe { + read_cells_bytes( + bytes.as_ptr(), + bytes.len(), + ptr::null(), + usize::MAX, + &mut array, + &mut schema, + ) + }, + -1 + ); + assert!( + unsafe { CStr::from_ptr(last_error_message()) } + .to_str() + .unwrap() + .contains("range count is too large") + ); + assert!(array.is_released()); +} diff --git a/tests/writing.rs b/tests/writing.rs new file mode 100644 index 0000000..0af060f --- /dev/null +++ b/tests/writing.rs @@ -0,0 +1,91 @@ +use arrow::array::Array; +use klamath_rs_ext::{ + library::{FileHeader, read_library}, + record::{Record, RecordHeader}, + records, +}; +use std::io::{self, Write}; + +#[test] +fn record_headers_include_their_own_size() { + let mut bytes = Vec::new(); + assert_eq!(records::HEADER::write(&mut bytes, &600).unwrap(), 6); + assert_eq!(bytes, [0, 6, 0, 2, 2, 88]); + let (remaining, value) = records::HEADER::read(&bytes).unwrap(); + assert!(remaining.is_empty()); + assert_eq!(value, 600); + let maximum = RecordHeader { + data_size: u16::MAX - 4, + tag: 0x1003, + }; + assert_eq!(maximum.pack_into(), [0xff, 0xff, 0x10, 0x03]); +} + +#[test] +fn integer_array_records_round_trip() { + let mut bytes = Vec::new(); + records::COLROW::write(&mut bytes, &[2, 3]).unwrap(); + let (remaining, values) = records::COLROW::read(&bytes).unwrap(); + assert!(remaining.is_empty()); + assert_eq!(values.collect::>(), [2, 3]); + + let mut bytes = Vec::new(); + let values = [i32::MIN, -1, 0, i32::MAX]; + records::XY::write(&mut bytes, &values).unwrap(); + let (remaining, parsed) = records::XY::read(&bytes).unwrap(); + assert!(remaining.is_empty()); + assert_eq!(parsed.collect::>(), values); +} + +#[test] +fn string_records_pad_only_when_needed_and_support_empty_strings() { + for value in [b"".as_slice(), b"odd", b"even"] { + let mut bytes = Vec::new(); + let expected_size = 4 + value.len() + value.len() % 2; + assert_eq!( + records::LIBNAME::write(&mut bytes, value).unwrap(), + expected_size + ); + assert_eq!(bytes.len(), expected_size); + let (remaining, parsed) = records::LIBNAME::read(&bytes).unwrap(); + assert!(remaining.is_empty()); + assert_eq!(parsed, value); + if value.len() % 2 == 1 { + assert_eq!(bytes.last(), Some(&0)); + } + } +} + +struct ShortWriter(Vec); + +impl Write for ShortWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let size = bytes.len().min(1); + self.0.extend_from_slice(&bytes[..size]); + Ok(size) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn library_header_round_trips_through_a_short_writer() { + let header = FileHeader::new(b"odd", 1e-9, 0.001); + let mut writer = ShortWriter(Vec::new()); + let mut written = header.write(&mut writer).unwrap(); + written += records::ENDLIB::write(&mut writer, &()).unwrap(); + assert_eq!(written, writer.0.len()); + let (remaining, library) = read_library(&writer.0).unwrap(); + assert!(remaining.is_empty()); + assert_eq!(library.len(), 1); +} + +#[test] +fn oversized_records_fail_before_writing() { + let mut bytes = Vec::new(); + let error = records::XY::write(&mut bytes, &vec![0; 16383]).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + assert!(bytes.is_empty()); +}