feat(metadata): write embedded layer names without rewriting design records

Consolidate sentinel declarations in an explicit existing cell and carrier pair. Preserve unrelated bytes and padding, reject ambiguous carriers and future versions, and create a separate output file without overwriting existing files.
This commit is contained in:
Jan Petykiewicz 2026-11-14 17:27:02 -08:00
commit 360e0f98f7
3 changed files with 305 additions and 14 deletions

View file

@ -1,5 +1,8 @@
use klamath_rs_ext::review::{Comparison, Document, dump_records, hierarchy};
use klamath_rs_ext::review::{
Comparison, Document, dump_records, hierarchy, parse_layer, parse_layer_name, write_layer_names,
};
use std::{
collections::BTreeMap,
ffi::OsString,
fs,
io::{self, Write},
@ -10,6 +13,7 @@ const HELP: &str = "Usage:
klamath dump FILE [--records]
klamath diff OLD NEW [--hierarchy ascii|mermaid|none] [--max-changes N] [--depth N]
klamath hierarchy FILE [--format ascii|mermaid] [--depth N]
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.
@ -24,6 +28,55 @@ fn value(args: &[OsString], index: &mut usize) -> Result<String, String> {
.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 run() -> Result<u8, String> {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
@ -31,6 +84,9 @@ fn run() -> Result<u8, String> {
return Ok(0);
}
let command = args[0].to_str().ok_or("invalid command")?;
if command == "name-layers" {
return name_layers(&args[1..]);
}
let paths = match command {
"dump" | "hierarchy" => 1,
"diff" => 2,

View file

@ -8,6 +8,9 @@ use std::{
fmt::Write,
};
mod names;
pub use names::{parse_layer, parse_layer_name, write_layer_names};
pub const PROFILE: &str = "klamath-object-v1";
pub const LAYER_SENTINEL: &str = "KLAMATH_LAYER_NAMES_V1";
pub type Layer = (u16, u16);
@ -30,6 +33,7 @@ struct Key<'a> {
#[derive(Debug)]
pub struct Object<'a> {
pub offset: usize,
pub end_offset: usize,
pub kind: u16,
pub layer: Option<Layer>,
pub bounds: Option<Bounds>,
@ -63,6 +67,8 @@ impl Object<'_> {
#[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<Object<'a>>,
attributes: Vec<(u16, &'a [u8])>,
}
@ -281,6 +287,7 @@ fn object<'a>(records: &[Record<'a>], issues: &mut Vec<String>) -> Result<Object
properties.sort();
let mut object = Object {
offset: first.offset,
end_offset: records.last().unwrap().offset + 4,
kind: first.tag,
layer: None,
bounds: None,
@ -473,6 +480,7 @@ impl<'a> Document<'a> {
i += 1;
let mut cell = Cell {
offset,
end_offset: 0,
objects: Vec::new(),
attributes: Vec::new(),
};
@ -482,6 +490,7 @@ impl<'a> Document<'a> {
.get(i)
.ok_or_else(|| error(offset, "missing ENDSTR"))?;
if record.tag == RTAG_ENDSTR {
cell.end_offset = record.offset;
i += 1;
break;
}
@ -564,22 +573,12 @@ impl<'a> Document<'a> {
}
let text = decoded_string(object.field(RTAG_STRING).unwrap(), object.offset)?;
if text != LAYER_SENTINEL {
let mut parts = text.splitn(3, ':');
let parsed = parts
.next()
.and_then(|a| a.parse::<u16>().ok())
.zip(parts.next().and_then(|b| b.parse::<u16>().ok()))
.zip(parts.next().filter(|name| !name.is_empty()));
let ((layer, dtype), name) = parsed.ok_or_else(|| {
error(
object.offset,
"invalid layer-name declaration; expected layer:datatype:name",
)
})?;
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)
.is_some_and(|old| old != &name)
{
return Err(error(
object.offset,

120
src/review/names.rs Normal file
View file

@ -0,0 +1,120 @@
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)
}