layouttk 0.5.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
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<()> {
        // Directional form is shorter for Manhattan and 45-degree edges.
        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(())
        }
    }
}
/// Resolve once per stream. Explicit IDs and value-based defaults are disjoint:
/// an inline label never captures an equal, explicitly bound table definition.
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)?;
            // All supported geometry and TEXT records share the repetition bit.
            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(())
        }
    }
}

// Keep compression independent of the size of a cell. Every block ends on a
// record boundary, allowing record-sequence decoding with bounded buffers.
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)?;
    // Unindexed non-strict stream, table offsets in START.
    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);
        // Implicit numbering carries value-based defaults in the canonical
        // stream. Sparse/explicit IDs retain identity after later edits.
        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(&[])?,
    )
}