Compare commits

..
27 changed files with 530 additions and 5199 deletions

View file

@ -1,142 +0,0 @@
# 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`

218
README.md
View file

@ -1,218 +0,0 @@
# 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.

View file

@ -1,5 +0,0 @@
# 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

View file

@ -1,10 +0,0 @@
# 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

View file

@ -98,7 +98,8 @@ pub fn parse_bitarray(input: &[u8]) -> IResult<'_, [bool; 16]> {
pub fn parse_ascii(input: &[u8], length: u16) -> IResult<'_, Vec<u8>> {
let length = length as usize;
let (input, data) = take_bytes(input, length)?;
let true_length = length - usize::from(data.last() == Some(&0));
let last = data[length - 1];
let true_length = if last == 0 { length - 1 } else { length };
let vec = data[..true_length].to_vec();
Ok((input, vec))
}

View file

@ -1,259 +0,0 @@
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<String, String> {
*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<u8, String> {
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<u8, String> {
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)
}
}
}

View file

@ -71,18 +71,6 @@ struct ARefRecord {
properties: Vec<PropertyRecord>,
}
#[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),
@ -90,7 +78,6 @@ enum RefRecord {
const UNIT_COUNTS: u32 = (1_u32 << 16) | 1_u32;
const ZERO_XY: u64 = 0;
fn layer_id_for(
@ -293,38 +280,6 @@ pub fn read_elements<'a>(
}
pub fn scan_elements<'a>(
input: &'a [u8],
names: &mut HashMap<String, u32>,
) -> IResult<'a, Vec<ScanRefRecord>> {
let mut input = input;
let mut refs = Vec::<ScanRefRecord>::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,
@ -346,45 +301,6 @@ 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,
@ -886,9 +802,6 @@ 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()));
@ -902,10 +815,6 @@ 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();
@ -917,20 +826,11 @@ 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 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 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 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);

425
src/iface.rs Normal file
View file

@ -0,0 +1,425 @@
/*
* 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<Int32Builder>,
text_parent: UInt64Builder,
text_string: LargeStringDictionaryBuilder,
text_x: Int32Builder,
text_y: Int32Builder,
boundaries: Vec<elements::Boundary>,
paths: Vec<elements::Path>,
nodes: Vec<elements::Node>,
boxes: Vec<elements::GDSBox>,
texts: Vec<elements::Text>,
refs: Vec<elements::Reference>,
}
impl Cell {
/// Build an empty cell
pub fn new(name: Vec<u8>) -> 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<Option<Cell>> {
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<W: 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<W: Write>(&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<HashMap::<Vec<u8>, 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<bool>,
mag_and_angle_deg: Vec<f64>,
xy: Vec<i32>,
names: Vec<u8>,
name_inds: Vec<usize>,
has_prop: Vec<bool>,
has_rep: Vec<bool>,
}
pub struct Repetitions {
colrow_vecs: Vec<i32>, // 4 per
colrow_counts: Vec<i16>, // 2 per
}
pub struct Shapes {
layers_and_dtypes: Vec<i16>, // 2 per
xy: Vec<i32>, // variable per
has_prop: Vec<bool>,
}
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<u8>,
properties: HashMap::<i16, Vec<u8>>,
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<i32>,
/// Properties for the element.
properties: HashMap::<i16, Vec<u8>>,
}
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<i32>,
/// Properties for the element.
properties: HashMap::<i16, Vec<u8>>,
}
pub struct GDSBox {
/// (layer, box_type) tuple
layer: (i16, i16),
/// Box coordinates (5 pairs)
xy: Vec<i32>,
/// Properties for the element.
properties: HashMap::<i16, Vec<u8>>,
}
pub struct Node {
/// (layer, box_type) tuple
layer: (i16, i16),
/// 1-50 pairs of coordinates.
xy: Vec<i32>,
/// Properties for the element.
properties: HashMap::<i16, Vec<u8>>,
}
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<i32>,
/// Text content
string: Vec<u8>,
/// Properties for the element.
properties: HashMap::<i16, Vec<u8>>
}

View file

@ -5,215 +5,42 @@ pub mod record;
pub mod records;
pub mod elements;
pub mod library;
pub mod review;
use crate::library::{read_library, read_selected_library, scan_library};
use crate::library::read_library;
use byteorder::{ByteOrder, BigEndian};
use std::any::Any;
use std::cell::RefCell;
use std::mem::size_of;
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::ffi::{CStr, OsStr, c_char};
use std::os::unix::ffi::OsStrExt;
use std::str;
use std::fs;
use std::slice;
use std::path::Path;
use arrow::ffi::{to_ffi, FFI_ArrowArray, FFI_ArrowSchema};
use arrow::array::{Array, StructArray};
use arrow::array::Array;
thread_local! {
static LAST_ERROR: RefCell<Option<CString>> = 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<dyn Any + Send>) -> String {
if let Some(message) = payload.downcast_ref::<&str>() {
(*message).to_string()
} else if let Some(message) = payload.downcast_ref::<String>() {
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<StructArray, String>,
) -> 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<PathBuf, String> {
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,
) -> 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 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");
}
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::<T>()).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)
})
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(); }
}
@ -222,15 +49,12 @@ macro_rules! impl_i16be {
{
let sl = unsafe { std::slice::from_raw_parts_mut($arr, $size) };
for xx in sl.iter_mut() {
// 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;
}
if *xx < i16::MIN as $tt { return *xx }
if *xx > i16::MAX as $tt { return *xx }
let mut buf = [0; size_of::<$tt>()];
BigEndian::write_i16(&mut buf, *xx as i16);
*xx = <$tt>::from_ne_bytes(buf);
*xx = <$tt>::from_le_bytes(buf);
}
0 as $tt
}
@ -243,14 +67,12 @@ macro_rules! impl_i32be {
{
let sl = unsafe { std::slice::from_raw_parts_mut($arr, $size) };
for xx in sl.iter_mut() {
let value = *xx as f64;
if !value.is_finite() || value < i32::MIN as f64 || value > i32::MAX as f64 {
return *xx;
}
if *xx < i32::MIN as $tt { return *xx }
if *xx > i32::MAX as $tt { return *xx }
let mut buf = [0; size_of::<$tt>()];
BigEndian::write_i32(&mut buf, *xx as i32);
*xx = <$tt>::from_ne_bytes(buf);
*xx = <$tt>::from_le_bytes(buf);
}
0 as $tt
}
@ -294,3 +116,4 @@ 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) }

View file

@ -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, scan_elements, DListBuilder, FListBuilder, ScanRefRecord};
pub use crate::elements::{read_elements, DListBuilder, FListBuilder};
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::{
BooleanBuilder, StructBuilder, StringBuilder, UInt64Builder, UInt32Builder, Int16Builder, Float64Builder,
StructBuilder, StringBuilder, UInt64Builder, UInt32Builder, Int16Builder, Float64Builder,
StructArray,
};
@ -98,38 +98,9 @@ impl FileHeader {
}
fn make_name_list_type() -> DataType {
DataType::List(Arc::new(
Field::new_list_field(DataType::Utf8, false)
))
}
pub fn read_library(input: &[u8]) -> IResult<'_, StructArray> {
let input_size = input.len();
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<Field>) -> 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),
@ -226,7 +197,7 @@ fn make_library_builder() -> StructBuilder {
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, true),
Field::new("width", DataType::Int32, false),
Field::new("xy", coords_t.clone(), false),
Field::new("properties", property_list_t.clone(), true),
]));
@ -277,10 +248,20 @@ fn make_library_builder() -> StructBuilder {
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),
@ -301,59 +282,26 @@ fn make_library_builder() -> StructBuilder {
Field::new_list_field(cell_struct_t, false)
));
make_top_level_builder(
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),
vec![
Field::new("cell_names", name_list_t, false),
Field::new("layers", layer_list_t, false),
],
)
}
0,
);
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 (input, header) = FileHeader::read(input)?;
let dbu_builder = lib_builder.field_builder::<Float64Builder>(0).unwrap();
dbu_builder.append_value(header.meters_per_db_unit);
let uu_builder = lib_builder.field_builder::<Float64Builder>(1).unwrap();
uu_builder.append_value(header.user_units_per_db_unit);
let libname_builder = lib_builder.field_builder::<StringBuilder>(2).unwrap();
libname_builder.append_value(String::from_utf8(header.name.clone()).unwrap());
libname_builder.append_value(String::from_utf8(header.name).unwrap());
let mtl_builder = lib_builder.field_builder::<FListBuilder>(3).unwrap();
let mt_builder = mtl_builder.values().as_any_mut().downcast_mut::<Int16Builder>().unwrap();
mt_builder.append_values(&header.mod_time, &[true; 6]);
@ -362,28 +310,47 @@ fn append_file_header(
let at_builder = atl_builder.values().as_any_mut().downcast_mut::<Int16Builder>().unwrap();
at_builder.append_values(&header.acc_time, &[true; 6]);
atl_builder.append(true);
let mut names = HashMap::<String, u32>::new();
let mut layers = HashMap::<u32, u32>::new();
let cells_builder = lib_builder.field_builder::<DListBuilder>(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::<StructBuilder>().unwrap();
let id_builder = cell_builder.field_builder::<UInt32Builder>(0).unwrap();
id_builder.append_value(*id);
let offset_builder = cell_builder.field_builder::<UInt64Builder>(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<String, u32>,
) {
let mut ids: HashMap<u32, String> = names.into_iter().map(|(kk, vv)| (vv, kk)).collect();
let names_builder = lib_builder.field_builder::<DListBuilder>(field_index).unwrap();
let names_builder = lib_builder.field_builder::<DListBuilder>(6).unwrap();
let name_builder = names_builder.values().as_any_mut().downcast_mut::<StringBuilder>().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<u32, u32>,
) {
let mut layer_ids: HashMap<u32, u32> = layers.into_iter().map(|(kk, vv)| (vv, kk)).collect();
let layers_builder = lib_builder.field_builder::<DListBuilder>(7).unwrap();
let layer_builder = layers_builder.values().as_any_mut().downcast_mut::<UInt32Builder>().unwrap();
@ -391,211 +358,6 @@ fn append_layers(
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::<StructBuilder>().unwrap();
let target_builder = ref_builder.field_builder::<UInt32Builder>(0).unwrap();
target_builder.append_value(scan_ref.target_id);
let invert_builder = ref_builder.field_builder::<BooleanBuilder>(1).unwrap();
invert_builder.append_value(scan_ref.invert_y);
let scale_builder = ref_builder.field_builder::<Float64Builder>(2).unwrap();
scale_builder.append_value(scan_ref.scale);
let angle_builder = ref_builder.field_builder::<Float64Builder>(3).unwrap();
angle_builder.append_value(scan_ref.angle_rad);
let xy_builder = ref_builder.field_builder::<UInt64Builder>(4).unwrap();
xy_builder.append_value(scan_ref.xy);
let xy0_builder = ref_builder.field_builder::<UInt64Builder>(5).unwrap();
xy0_builder.append_value(scan_ref.xy0);
let xy1_builder = ref_builder.field_builder::<UInt64Builder>(6).unwrap();
xy1_builder.append_value(scan_ref.xy1);
let counts_builder = ref_builder.field_builder::<UInt32Builder>(7).unwrap();
counts_builder.append_value(scan_ref.counts);
ref_builder.append(true);
}
fn intern_name(names: &mut HashMap<String, u32>, 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<String, u32>,
layers: &mut HashMap<u32, u32>,
struct_input: &'a [u8],
id: u32,
file_offset: u64,
) -> IResult<'a, ()> {
let cell_builder = cells_builder.values().as_any_mut().downcast_mut::<StructBuilder>().unwrap();
let id_builder = cell_builder.field_builder::<UInt32Builder>(0).unwrap();
id_builder.append_value(id);
let offset_builder = cell_builder.field_builder::<UInt64Builder>(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<String, u32>,
mut on_struct: F,
) -> IResult<'a, ()>
where
F: FnMut(&'a [u8], usize, u32, &mut HashMap<String, u32>) -> 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::<String, u32>::new();
let mut layers = HashMap::<u32, u32>::new();
let cells_builder = lib_builder.field_builder::<DListBuilder>(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::<String, u32>::new();
let cells_builder = lib_builder.field_builder::<DListBuilder>(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::<StructBuilder>().unwrap();
let id_builder = cell_builder.field_builder::<UInt32Builder>(0).unwrap();
id_builder.append_value(id);
let start_builder = cell_builder.field_builder::<UInt64Builder>(1).unwrap();
start_builder.append_value(record_start.try_into().unwrap());
let end_builder = cell_builder.field_builder::<UInt64Builder>(2).unwrap();
end_builder.append_value(struct_end.try_into().unwrap());
let refs_builder = cell_builder.field_builder::<DListBuilder>(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::<String, u32>::new();
let mut layers = HashMap::<u32, u32>::new();
let cells_builder = lib_builder.field_builder::<DListBuilder>(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();

View file

@ -1,7 +1,8 @@
///
/// Generic record-level read/write functionality.
///
use std::io::{self, Write};
use std::io::Write;
use std::convert::TryInto;
use byteorder::{ByteOrder, BigEndian};
@ -26,15 +27,12 @@ impl RecordHeader {
pub fn read(input: &[u8]) -> IResult<'_, RecordHeader> {
let (input, size) = parse_u16(input)?;
let (input, tag) = parse_u16(input)?;
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}))
Ok((input, RecordHeader{tag, data_size:size - 4}))
}
pub fn pack_into(&self) -> [u8; 4] {
let size = self.data_size.checked_add(4).expect("Record too big!");
let vals = [size, self.tag];
assert!(self.data_size < 0xffff - 4, "Record too big!");
let vals = [self.data_size, self.tag];
let mut buf = [0x77; 4];
BigEndian::write_u16_into(&vals, &mut buf);
buf
@ -42,8 +40,7 @@ impl RecordHeader {
pub fn write<W: Write>(&self, ww: &mut W) -> OResult {
let bytes = self.pack_into();
ww.write_all(&bytes)?;
Ok(bytes.len())
ww.write(&bytes)
}
}
@ -141,12 +138,11 @@ pub trait Record<RData: RecordData> {
fn write<W: Write>(ww: &mut W, data: &RData::InData) -> OResult {
let packed_data = RData::pack(data);
let data_bytes = packed_data.as_ref();
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)
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)
}
}
@ -236,7 +232,7 @@ impl RecordData for Int2Array {
}
fn pack(data: &Self::InData) -> Self::ByteData {
let mut buf = vec![0; data.len() * 2];
let mut buf = Vec::with_capacity(data.len() * 2);
Self::pack_into(&mut buf, data);
buf
}
@ -277,7 +273,7 @@ impl RecordData for Int4Array {
}
fn pack(data: &Self::InData) -> Self::ByteData {
let mut buf = vec![0; data.len() * 4];
let mut buf = Vec::with_capacity(data.len() * 4);
Self::pack_into(&mut buf, data);
buf
}
@ -336,7 +332,7 @@ impl RecordData for Real8Pair {
}
fn pack_into(buf: &mut [u8], data: &Self::InData) {
pack_real8(buf, data.0).unwrap_or_else(|_| panic!("Float.0 {0} too big for Real8", data.0));
pack_real8(&mut buf[8 * 0..], 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));
}
@ -367,7 +363,7 @@ impl RecordData for ASCII {
}
fn pack(data: &Self::InData) -> Self::ByteData {
let mut buf = vec![0; data.len() + data.len() % 2];
let mut buf = Vec::with_capacity(data.len() * 4);
Self::pack_into(&mut buf, data);
buf
}
@ -388,7 +384,7 @@ impl RecordData for DateTimePair {
}
fn pack_into(buf: &mut [u8], data: &Self::InData) {
pack_datetime(buf, &data[0]);
pack_datetime(&mut buf[6 * 2 * 0..], &data[0]);
pack_datetime(&mut buf[6 * 2 * 1..], &data[1]);
}

View file

@ -137,7 +137,7 @@ impl Record<Empty> for ENDLIB {
pub struct BGNSTR;
impl Record<DateTimePair> for BGNSTR {
fn tag() -> u16 { RTAG_BGNSTR }
fn expected_size() -> Option<u16> { Some(2 * 6 * 2) }
fn expected_size() -> Option<u16> { Some(2 * 6) }
}
pub struct STRNAME;
@ -545,23 +545,3 @@ impl Record<Empty> for CONTACT {
fn tag() -> u16 { RTAG_CONTACT }
fn expected_size() -> Option<u16> { 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]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,117 +0,0 @@
use super::*;
#[derive(Debug)]
pub struct Replacement {
pub removed: usize,
pub added: usize,
pub explanation: String,
}
type Group = (u16, Option<Layer>, Option<String>, Option<Bounds>);
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<Replacement> {
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::<Group, Vec<usize>>::new(),
BTreeMap::<Group, Vec<usize>>::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<i32>| {
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("; ")
}

View file

@ -1,120 +0,0 @@
use super::*;
pub fn parse_layer(value: &str) -> Result<Layer, String> {
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<u16, String> {
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<u8>, 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<u8>, 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<Layer, String>,
) -> Result<Vec<u8>, 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)
}

View file

@ -1,221 +0,0 @@
use super::*;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Scope {
pub top: Option<String>,
pub cell: Option<String>,
pub layer: Option<Layer>,
}
/// Presentation filters never modify comparison status, totals, or hierarchy.
#[derive(Clone, Debug, Default)]
pub struct DisplayFilter {
pub cell: Option<String>,
pub layer: Option<Layer>,
}
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<String> {
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<Self, String> {
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::<String, Vec<String>>::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)
}
}

10
test.py
View file

@ -16,16 +16,10 @@ 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('''
int read_path(const char* path, struct ArrowArray* array, struct ArrowSchema* schema);
const char* last_error_message(void);
''')
ffi.cdef('void read_path(char* path, struct ArrowArray* array, struct ArrowSchema* schema);')
print(f'{ret_ptr_array[0]=}, {ret_ptr_schema[0]=}')
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)
clib.read_path(path.encode(), ret_ptr_array, ret_ptr_schema)
ptr_schema = int(ffi.cast('uintptr_t', ret_ptr_schema))
ptr_array = int(ffi.cast('uintptr_t', ret_ptr_array))

View file

@ -1,20 +0,0 @@
use klamath_rs_ext::{basic::encode_real8, records};
pub fn record(out: &mut Vec<u8>, 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<u8> {
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<u8> = [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
}

View file

@ -1,157 +0,0 @@
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"
)));
}

View file

@ -1,9 +0,0 @@
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]

Some files were not shown because too many files have changed in this diff Show more