use super::binary::{coord, legal_string};
use super::{MAGIC, MAX_BLOCK, MAX_POINTS, MAX_STRING};
use crate::{
Array, Element, Error, Interval, Layer, Layout, PathEnds, Point, Property, PropertyValue,
Repetition, Result,
};
use crate::{TableEntry, TableProperties};
use flate2::Compression;
use flate2::write::DeflateEncoder;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{BufWriter, Write};
trait Put: Write {
fn octet(&mut self, b: u8) -> Result<()> {
self.write_all(&[b])?;
Ok(())
}
fn uint(&mut self, mut n: u128) -> Result<()> {
let mut bytes = [0; 19];
let mut i = 0;
while n >= 128 {
bytes[i] = (n as u8) | 0x80;
n >>= 7;
i += 1;
}
bytes[i] = n as u8;
self.write_all(&bytes[..=i])?;
Ok(())
}
fn sint(&mut self, n: i64) -> Result<()> {
self.uint(signed(n))
}
fn real(&mut self, n: f64) -> Result<()> {
if !n.is_finite() {
return Err(Error::invalid("non-finite OASIS real"));
}
self.octet(7)?;
self.write_all(&n.to_le_bytes())?;
Ok(())
}
fn string(&mut self, s: &str, name: bool) -> Result<()> {
if !legal_string(s.as_bytes(), name) || s.len() > MAX_STRING {
return Err(Error::unsupported(
"string outside supported OASIS name/text alphabet or length",
));
}
self.uint(s.len() as u128)?;
self.write_all(s.as_bytes())?;
Ok(())
}
fn pos(&mut self, p: Point) -> Result<()> {
self.sint(p.x)?;
self.sint(p.y)
}
fn layer(&mut self, l: Layer) -> Result<()> {
self.uint(l.number.into())?;
self.uint(l.datatype.into())
}
fn delta(&mut self, p: Point) -> Result<()> {
let dir = if p.y == 0 {
Some(if p.x >= 0 { 0 } else { 2 })
} else if p.x == 0 {
Some(if p.y > 0 { 1 } else { 3 })
} else if p.x.unsigned_abs() == p.y.unsigned_abs() {
Some(match (p.x > 0, p.y > 0) {
(true, true) => 4,
(false, true) => 5,
(false, false) => 6,
(true, false) => 7,
})
} else {
None
};
if let Some(d) = dir {
let length = u128::from(p.x.unsigned_abs().max(p.y.unsigned_abs()));
self.uint((length << 4) | (d << 1))
} else {
self.uint((signed(p.x) << 1) | 1)?;
self.sint(p.y)
}
}
}
impl<W: Write> Put for W {}
fn signed(n: i64) -> u128 {
(u128::from(n.unsigned_abs()) << 1) | u128::from(n < 0)
}
fn points(out: &mut Vec<u8>, points: &[Point], is_polygon: bool) -> Result<()> {
let min = if is_polygon { 3 } else { 2 };
if points.len() < min || points.len() > MAX_POINTS {
return Err(Error::unsupported(
"OASIS point list outside supported size",
));
}
out.octet(4)?;
out.uint((points.len() - 1) as u128)?;
for edge in points.windows(2) {
let d = Point {
x: coord(i128::from(edge[1].x) - i128::from(edge[0].x))?,
y: coord(i128::from(edge[1].y) - i128::from(edge[0].y))?,
};
out.delta(d)?;
}
out.pos(points[0])
}
fn regular(out: &mut Vec<u8>, a: &Array) -> Result<()> {
if a.columns == 0 || a.rows == 0 {
return Err(Error::invalid("zero OASIS array dimension"));
}
if a.columns > 1 && a.rows > 1 {
out.octet(8)?;
out.uint((a.columns - 2).into())?;
out.uint((a.rows - 2).into())?;
out.delta(a.column_step)?;
out.delta(a.row_step)
} else {
let (n, step) = if a.columns > 1 {
(a.columns, a.column_step)
} else {
(a.rows, a.row_step)
};
if n < 2 {
return Err(Error::invalid(
"OASIS repetition requires more than one instance",
));
}
if a.rows > 1 && step.x == 0 && step.y >= 0 {
out.octet(3)?;
out.uint((n - 2).into())?;
out.uint(step.y as u128)
} else {
out.octet(9)?;
out.uint((n - 2).into())?;
out.delta(step)
}
}
}
fn repetition(out: &mut Vec<u8>, r: &Repetition) -> Result<()> {
match r {
Repetition::Regular(a) => regular(out, a),
Repetition::Offsets(offsets) => {
if offsets.is_empty() || offsets.len() > MAX_POINTS {
return Err(Error::unsupported(
"OASIS explicit repetition outside supported length",
));
}
let step_count = offsets.len() - 1;
let horizontal = offsets.iter().all(|p| p.y == 0)
&& offsets.first().is_some_and(|p| p.x >= 0)
&& offsets.windows(2).all(|w| w[1].x >= w[0].x);
let vertical = offsets.iter().all(|p| p.x == 0)
&& offsets.first().is_some_and(|p| p.y >= 0)
&& offsets.windows(2).all(|w| w[1].y >= w[0].y);
let kind = if horizontal {
4
} else if vertical {
6
} else {
10
};
out.octet(kind)?;
out.uint(step_count as u128)?;
let mut prev = Point { x: 0, y: 0 };
for p in offsets {
match kind {
4 => out.uint((p.x - prev.x) as u128)?,
6 => out.uint((p.y - prev.y) as u128)?,
_ => out.delta(Point {
x: coord(i128::from(p.x) - i128::from(prev.x))?,
y: coord(i128::from(p.y) - i128::from(prev.y))?,
})?,
}
prev = *p;
}
Ok(())
}
}
}
pub(crate) struct Preflight<'a> {
defaults: BTreeMap<(u8, &'a [u8]), u64>,
numbered: BTreeMap<(u8, u64), (&'a [u8], bool)>,
ids: Vec<u64>,
explicit_classes: [bool; 11],
}
fn entry_key(entry: &TableEntry) -> (u8, &[u8]) {
match entry {
TableEntry::CellName(s) => (4, s.as_bytes()),
TableEntry::Text(s) => (6, s.as_bytes()),
TableEntry::PropertyName(s) => (8, s.as_bytes()),
TableEntry::PropertyString(b) => (10, b),
}
}
impl<'a> Preflight<'a> {
pub(crate) fn new(entries: &'a [TableProperties]) -> Result<Self> {
let mut defaults = BTreeMap::new();
let mut numbered = BTreeMap::new();
let mut explicit_values = BTreeSet::new();
let mut explicit_classes = [false; 11];
for t in entries {
let (kind, bytes) = entry_key(&t.entry);
if let Some(id) = t.reference {
explicit_classes[usize::from(kind)] = true;
if numbered.insert((kind, id), (bytes, true)).is_some() {
return Err(Error::invalid("duplicate OASIS table reference number"));
}
if !explicit_values.insert((kind, bytes)) && matches!(kind, 4 | 8) {
return Err(Error::invalid("nonunique OASIS CELLNAME or PROPNAME"));
}
}
}
let mut ids = Vec::with_capacity(entries.len());
let mut next = [0u64; 11];
for t in entries {
let (kind, bytes) = entry_key(&t.entry);
let id = if let Some(id) = t.reference {
id
} else {
if t.properties.is_empty() {
return Err(Error::invalid(
"unbound OASIS table entry with no properties",
));
}
let id = &mut next[kind as usize];
while numbered.contains_key(&(kind, *id)) {
*id += 1;
}
if defaults.insert((kind, bytes), *id).is_some()
|| explicit_values.contains(&(kind, bytes))
{
return Err(Error::invalid("ambiguous OASIS by-value table definition"));
}
numbered.insert((kind, *id), (bytes, false));
*id
};
ids.push(id);
}
Ok(Self {
defaults,
numbered,
ids,
explicit_classes,
})
}
fn get(&self, kind: u8, bytes: &[u8], reference: Option<u64>) -> Result<Option<u64>> {
if let Some(id) = reference {
match self.numbered.get(&(kind, id)) {
Some((_, false)) => Err(Error::invalid(format!(
"OASIS table {kind} reference {id} points to an automatically assigned slot without an explicit definition"
))),
Some(&(payload, true)) if payload == bytes => Ok(Some(id)),
Some(_) => Err(Error::invalid(format!(
"OASIS table {kind} reference {id} has different bytes from its definition"
))),
None => Err(Error::invalid(format!(
"undefined OASIS table {kind} reference {id}"
))),
}
} else {
Ok(self.defaults.get(&(kind, bytes)).copied())
}
}
pub(crate) fn check_element(&self, e: &Element) -> Result<()> {
element(&mut Vec::new(), e, self)
}
pub(crate) fn check_property(&self, p: &Property) -> Result<()> {
properties(&mut std::io::sink(), std::slice::from_ref(p), self)
}
}
fn properties<W: Write>(out: &mut W, items: &[Property], tables: &Preflight) -> Result<()> {
for prop in items {
if prop.standard && prop.name == "S_CELL_OFFSET" {
return Err(Error::unsupported(
"S_CELL_OFFSET is a physical byte offset and cannot be supplied for a new OASIS stream",
));
}
let n = prop.values.len();
if n > MAX_POINTS {
return Err(Error::unsupported("too many values in OASIS PROPERTY"));
}
let id = tables.get(8, prop.name.as_bytes(), prop.name_reference)?;
let flags =
(n.min(15) as u8) << 4 | 4 | u8::from(prop.standard) | (u8::from(id.is_some()) << 1);
out.write_all(&[28, flags])?;
if let Some(id) = id {
out.uint(id.into())?;
} else {
out.string(&prop.name, true)?;
}
if n >= 15 {
out.uint(n as u128)?;
}
for item in &prop.values {
let (v, reference) = match item {
PropertyValue::ReferencedString { reference, value } => {
(value.as_ref(), Some(*reference))
}
plain => (plain, None),
};
let string_ref = match v {
PropertyValue::Ascii(s) => {
Some((13, s.as_bytes(), legal_string(s.as_bytes(), false)))
}
PropertyValue::Binary(b) => Some((14, b.as_slice(), true)),
PropertyValue::Name(s) => {
Some((15, s.as_bytes(), legal_string(s.as_bytes(), true)))
}
_ => None,
};
if let Some((kind, bytes, valid)) = string_ref {
if !valid {
return Err(Error::invalid("invalid OASIS property string characters"));
}
if let Some(id) = tables.get(10, bytes, reference)? {
out.octet(kind)?;
out.uint(id.into())?;
continue;
}
} else if reference.is_some() {
return Err(Error::invalid(
"referenced OASIS property value must be Ascii, Binary or Name",
));
}
match v {
PropertyValue::ReferencedString { .. } => {
return Err(Error::invalid("nested OASIS property string reference"));
}
PropertyValue::Real(v) => out.real(*v)?,
PropertyValue::Ratio {
negative,
numerator,
denominator,
} => {
if *denominator == 0 {
return Err(Error::invalid("zero OASIS property denominator"));
}
out.octet(4 + u8::from(*negative))?;
out.uint((*numerator).into())?;
out.uint((*denominator).into())?;
}
PropertyValue::Unsigned(n) => {
out.octet(8)?;
out.uint((*n).into())?;
}
PropertyValue::Signed(n) => {
out.octet(9)?;
out.sint(*n)?;
}
PropertyValue::Ascii(s) => {
out.octet(10)?;
out.string(s, false)?;
}
PropertyValue::Binary(b) => {
if b.len() > MAX_STRING {
return Err(Error::unsupported("OASIS property string too long"));
}
out.octet(11)?;
out.uint(b.len() as u128)?;
out.write_all(b)?;
}
PropertyValue::Name(s) => {
out.octet(12)?;
out.string(s, true)?;
}
}
}
}
Ok(())
}
fn interval<W: Write>(w: &mut W, range: &Interval) -> Result<()> {
match range {
Interval::All => w.octet(0),
Interval::AtMost(a) => {
w.octet(1)?;
w.uint((*a).into())
}
Interval::AtLeast(a) => {
w.octet(2)?;
w.uint((*a).into())
}
Interval::Exactly(a) => {
w.octet(3)?;
w.uint((*a).into())
}
Interval::Range(a, b) => {
if a > b {
return Err(Error::invalid("reversed OASIS layer interval"));
}
w.octet(4)?;
w.uint((*a).into())?;
w.uint((*b).into())
}
}
}
fn element(out: &mut Vec<u8>, e: &Element, tables: &Preflight) -> Result<()> {
match e {
Element::Polygon {
layer,
points: vertices,
} => {
if let [a, b, c, d] = vertices.as_slice()
&& a.y == b.y
&& b.x == c.x
&& c.y == d.y
&& d.x == a.x
&& a.x < b.x
&& a.y < d.y
{
out.write_all(&[20, 0x7b])?;
out.layer(*layer)?;
out.uint(a.x.abs_diff(b.x).into())?;
out.uint(a.y.abs_diff(d.y).into())?;
return out.pos(*a);
}
out.write_all(&[21, 0x3b])?;
out.layer(*layer)?;
points(out, vertices, true)
}
Element::Circle {
layer,
center,
radius,
} => {
out.write_all(&[27, 0x3b])?;
out.layer(*layer)?;
out.uint((*radius).into())?;
out.pos(*center)
}
Element::Path {
layer,
points: vertices,
width,
}
| Element::ExtendedPath {
layer,
points: vertices,
width,
..
} => {
let mut ends = &PathEnds::Flush;
if let Element::ExtendedPath {
absolute_width,
ends: path_ends,
..
} = e
{
if *absolute_width {
return Err(Error::unsupported(
"OASIS PATH cannot preserve absolute GDSII width",
));
}
ends = path_ends;
}
if *width < 0 || width % 2 != 0 {
return Err(Error::unsupported(
"OASIS PATH requires nonnegative even width in database units",
));
}
out.write_all(&[22, 0xfb])?;
out.layer(*layer)?;
out.uint((*width / 2) as u128)?;
match ends {
PathEnds::Flush => out.octet(5)?,
PathEnds::HalfWidth => out.octet(10)?,
PathEnds::Explicit { begin, end } => {
out.octet(15)?;
out.sint(*begin)?;
out.sint(*end)?;
}
PathEnds::Round => {
return Err(Error::unsupported(
"OASIS PATH cannot preserve round GDSII ends",
));
}
}
points(out, vertices, false)
}
Element::Attributed {
element: child,
properties: props,
} => {
element(out, child, tables)?;
properties(out, props, tables)
}
Element::Text {
layer,
origin,
text,
text_reference,
style,
} => {
if style.is_some() {
return Err(Error::unsupported(
"OASIS TEXT cannot preserve GDSII text presentation or transform",
));
}
if let Some(id) = tables.get(6, text.as_bytes(), *text_reference)? {
out.write_all(&[19, 0x7b])?;
out.uint(id.into())?;
} else {
out.write_all(&[19, 0x5b])?;
out.string(text, false)?;
}
out.layer(*layer)?;
out.pos(*origin)
}
Element::Repeated {
element: shape,
array: grid,
} => {
if matches!(
shape.as_ref(),
Element::Reference { .. } | Element::Repeated { .. }
) {
return Err(Error::invalid(
"OASIS geometry repetition must wrap a single shape",
));
}
let start = out.len();
element(out, shape, tables)?;
out[start + 1] |= 4;
repetition(out, grid)?;
Ok(())
}
Element::Reference {
cell,
origin,
transform,
array: rep,
} => {
let a = rep
.as_ref()
.filter(|r| !matches!(r,Repetition::Regular(a) if a.columns==1 && a.rows==1));
let mut flags = 0xb0 | u8::from(transform.reflect_x);
if a.is_some() {
flags |= 8;
}
if transform.magnification <= 0.0 {
return Err(Error::invalid("nonpositive OASIS magnification"));
}
if transform.magnification != 1.0 {
flags |= 4;
}
if transform.angle_deg != 0.0 {
flags |= 2;
}
out.write_all(&[18, flags])?;
out.string(cell, true)?;
if flags & 4 != 0 {
out.real(transform.magnification)?;
}
if flags & 2 != 0 {
out.real(transform.angle_deg)?;
}
out.pos(*origin)?;
if let Some(a) = a {
repetition(out, a)?;
}
Ok(())
}
}
}
fn flush_records<W: Write>(w: &mut W, records: &mut Vec<u8>) -> Result<()> {
if records.len() >= 256 && records.len() <= MAX_BLOCK {
let mut enc = DeflateEncoder::new(Vec::new(), Compression::fast());
enc.write_all(records)?;
let compressed = enc.finish()?;
if compressed.len() + 24 < records.len() {
w.write_all(&[34, 0])?;
w.uint(records.len() as u128)?;
w.uint(compressed.len() as u128)?;
w.write_all(&compressed)?;
records.clear();
return Ok(());
}
}
w.write_all(records)?;
records.clear();
Ok(())
}
pub(crate) fn write<W: Write>(layout: &Layout, w: W) -> Result<()> {
let unit = 1e-6 / layout.dbu_meters;
if !unit.is_finite() || unit <= 0.0 {
return Err(Error::invalid("invalid OASIS database unit"));
}
let mut out = BufWriter::new(w);
out.write_all(MAGIC)?;
out.write_all(&[1, 3, b'1', b'.', b'0'])?;
out.real(unit)?;
out.write_all(&[0; 13])?;
let tables = Preflight::new(&layout.table_properties)?;
properties(&mut out, &layout.properties, &tables)?;
for (t, id) in layout.table_properties.iter().zip(&tables.ids) {
let (kind, _) = entry_key(&t.entry);
let numbered = tables.explicit_classes[usize::from(kind)];
out.octet(if numbered { kind } else { kind - 1 })?;
match &t.entry {
TableEntry::Text(s) => out.string(s, false)?,
TableEntry::CellName(s) | TableEntry::PropertyName(s) => out.string(s, true)?,
TableEntry::PropertyString(b) => {
if b.len() > MAX_STRING {
return Err(Error::unsupported("OASIS table string too long"));
}
out.uint(b.len() as u128)?;
out.write_all(b)?;
}
}
if numbered {
out.uint((*id).into())?;
}
properties(&mut out, &t.properties, &tables)?;
}
for l in &layout.layer_names {
out.octet(if l.text { 12 } else { 11 })?;
out.string(&l.name, true)?;
interval(&mut out, &l.layers)?;
interval(&mut out, &l.datatypes)?;
properties(&mut out, &l.properties, &tables)?;
}
let indexed = layout.cells.iter().any(|c| !c.name_properties.is_empty());
let orphan_names: BTreeSet<_> = layout
.table_properties
.iter()
.filter_map(|t| match &t.entry {
TableEntry::CellName(s) => Some(s.as_str()),
_ => None,
})
.collect();
let mut cell_ids = Vec::new();
let mut next = 0;
for cell in &layout.cells {
if orphan_names.contains(cell.name.as_str()) {
return Err(Error::invalid(
"orphan CELLNAME entry also has a cell; put its properties on Cell.name_properties",
));
}
if indexed {
while tables.numbered.contains_key(&(4, next)) {
next += 1;
}
let numbered = tables.explicit_classes[4];
out.octet(if numbered { 4 } else { 3 })?;
out.string(&cell.name, true)?;
if numbered {
out.uint(next.into())?;
}
cell_ids.push(next);
next += 1;
properties(&mut out, &cell.name_properties, &tables)?;
}
}
let mut records = Vec::new();
for (cell_index, cell) in layout.cells.iter().enumerate() {
if indexed {
out.octet(13)?;
out.uint(cell_ids[cell_index].into())?;
} else {
out.octet(14)?;
out.string(&cell.name, true)?;
}
properties(&mut out, &cell.properties, &tables)?;
for (idx, e) in cell.elements.iter().enumerate() {
element(&mut records, e, &tables).map_err(|err| err.at_element(&cell.name, idx, e))?;
if records.len() >= 1024 * 1024 {
flush_records(&mut out, &mut records)?;
}
}
flush_records(&mut out, &mut records)?;
}
out.octet(2)?;
out.uint(252)?;
out.write_all(&[0; 252])?;
out.octet(0)?;
out.flush()?;
Ok(())
}
pub(crate) fn check_element(e: &Element) -> Result<()> {
element(&mut Vec::new(), e, &Preflight::new(&[])?)
}
pub(crate) fn check_property(p: &Property) -> Result<()> {
properties(
&mut std::io::sink(),
std::slice::from_ref(p),
&Preflight::new(&[])?,
)
}