layouttk 0.1.1

Integer-grid GDSII and OASIS layout processing with hierarchy-aware extraction
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! Streaming codec for the GDSII records represented by the layout model.
//!
//! Output uses the Gdspy multi-XY extension for long polygons, a micrometre display unit and fixed
//! library/structure timestamps. All geometry is stored in integer DBU.

use crate::{
    Array, Cell, Element, Error, Layer, Layout, PathEnds, Point, Property, PropertyValue,
    Repetition, Result, TextStyle, Transform,
};
use std::collections::BTreeSet;
use std::io::{self, Read, Write};

const HEADER: u8 = 0x00;
const BGNLIB: u8 = 0x01;
const LIBNAME: u8 = 0x02;
const UNITS: u8 = 0x03;
const ENDLIB: u8 = 0x04;
const BGNSTR: u8 = 0x05;
const STRNAME: u8 = 0x06;
const ENDSTR: u8 = 0x07;
const BOUNDARY: u8 = 0x08;
const PATH: u8 = 0x09;
const SREF: u8 = 0x0a;
const AREF: u8 = 0x0b;
const TEXT: u8 = 0x0c;
const LAYER: u8 = 0x0d;
const DATATYPE: u8 = 0x0e;
const WIDTH: u8 = 0x0f;
const XY: u8 = 0x10;
const ENDEL: u8 = 0x11;
const SNAME: u8 = 0x12;
const COLROW: u8 = 0x13;
const TEXTTYPE: u8 = 0x16;
const PRESENTATION: u8 = 0x17;
const STRING: u8 = 0x19;
const STRANS: u8 = 0x1a;
const MAG: u8 = 0x1b;
const ANGLE: u8 = 0x1c;
const PATHTYPE: u8 = 0x21;
const BOX: u8 = 0x2d;
const BOXTYPE: u8 = 0x2e;
const PROPATTR: u8 = 0x2b;
const PROPVALUE: u8 = 0x2c;
const BGNEXTN: u8 = 0x30;
const ENDEXTN: u8 = 0x31;
const MAX_XY_POINTS: usize = (u16::MAX as usize - 4) / 8;
pub(crate) const DEFAULT_TIMESTAMP: [u16; 6] = [100, 1, 1, 0, 0, 0];

fn record_spec(kind: u8) -> Option<(u8, Option<usize>)> {
    Some(match kind {
        ENDLIB | ENDSTR | BOUNDARY | PATH | SREF | AREF | TEXT | BOX | ENDEL => (0, Some(0)),
        STRANS | PRESENTATION => (1, Some(2)),
        HEADER | LAYER | DATATYPE | TEXTTYPE | PATHTYPE | BOXTYPE | PROPATTR => (2, Some(2)),
        BGNLIB | BGNSTR => (2, Some(24)),
        COLROW => (2, Some(4)),
        WIDTH | BGNEXTN | ENDEXTN => (3, Some(4)),
        XY => (3, None),
        UNITS => (5, Some(16)),
        MAG | ANGLE => (5, Some(8)),
        LIBNAME | STRNAME | SNAME | STRING | PROPVALUE => (6, None),
        _ => return None,
    })
}

// GDS reals have a 7-bit excess-64 base-16 exponent and a 56-bit fraction.
// Decoding can require three more bits than f64 supplies. Reject that case for
// physical quantities instead of silently moving or resizing geometry.
pub(crate) fn decode_real(bytes: &[u8], exact: bool) -> Result<f64> {
    let word = u64::from_be_bytes(bytes.try_into().unwrap());
    if word == 0 {
        return Ok(0.0);
    }
    let mantissa = word & 0x00ff_ffff_ffff_ffff;
    if mantissa < (1 << 52) {
        return Err(Error::invalid("unnormalized GDSII REAL8"));
    }
    if exact && mantissa as f64 as u64 != mantissa {
        return Err(Error::unsupported(
            "GDSII REAL8 needs more than 53 significant bits",
        ));
    }
    let exponent = i32::from(bytes[0] & 0x7f) - 64;
    let value = (mantissa as f64) * 2f64.powi(4 * exponent - 56);
    Ok(if bytes[0] & 0x80 != 0 { -value } else { value })
}

pub(crate) fn encode_real(value: f64) -> Result<[u8; 8]> {
    if value == 0.0 {
        return Ok([0; 8]);
    }
    let absolute = value.abs();
    let binary_exponent = ((absolute.to_bits() >> 52) & 0x7ff) as i32 - 1023;
    let exponent = binary_exponent.div_euclid(4) + 1;
    if !value.is_finite() || !(-64..=63).contains(&exponent) {
        return Err(Error::unsupported(format!(
            "{value} exceeds GDSII REAL8 range"
        )));
    }
    let mantissa = (absolute * 2f64.powi(56 - 4 * exponent)) as u64;
    let mut bytes = mantissa.to_be_bytes();
    bytes[0] = (exponent + 64) as u8 | if value.is_sign_negative() { 0x80 } else { 0 };
    Ok(bytes)
}

struct Decoder<R> {
    stream: R,
    next_offset: u64,
    offset: u64,
    kind: u8,
    payload: Vec<u8>,
}

impl<R: Read> Decoder<R> {
    fn invalid(&self, message: &str) -> Error {
        Error::invalid(format!(
            "GDSII byte {} (record 0x{:02x}): {message}",
            self.offset, self.kind
        ))
    }

    fn unsupported(&self, message: &str) -> Error {
        Error::unsupported(format!(
            "GDSII byte {} (record 0x{:02x}): {message}",
            self.offset, self.kind
        ))
    }

    fn exact(&mut self, header: &mut [u8]) -> Result<()> {
        self.stream.read_exact(header).map_err(|err| {
            if err.kind() == io::ErrorKind::UnexpectedEof {
                Error::invalid(format!("truncated GDSII record at byte {}", self.offset))
            } else {
                err.into()
            }
        })
    }

    fn advance(&mut self) -> Result<()> {
        self.offset = self.next_offset;
        let mut header = [0u8; 4];
        self.exact(&mut header)?;
        let size = usize::from(u16::from_be_bytes([header[0], header[1]]));
        self.kind = header[2];
        if size < 4 || !size.is_multiple_of(2) {
            return Err(self.invalid("record length must be even and at least 4"));
        }
        let (data_type, length) = record_spec(self.kind)
            .ok_or_else(|| self.unsupported("record is outside the supported profile"))?;
        if header[3] != data_type || length.is_some_and(|expected| expected != size - 4) {
            return Err(self.invalid("incorrect payload type or length"));
        }
        self.payload.resize(size - 4, 0);
        if let Err(err) = self.stream.read_exact(&mut self.payload) {
            return Err(if err.kind() == io::ErrorKind::UnexpectedEof {
                self.invalid("truncated payload")
            } else {
                err.into()
            });
        }
        self.next_offset += size as u64;
        Ok(())
    }

    fn expect(&self, kind: u8) -> Result<()> {
        if self.kind != kind {
            return Err(self.invalid(&format!("expected record 0x{kind:02x}")));
        }
        Ok(())
    }

    fn take(&mut self, kind: u8) -> Result<()> {
        self.expect(kind)?;
        self.advance()
    }

    fn word(&mut self, kind: u8) -> Result<u16> {
        self.expect(kind)?;
        let n = u16::from_be_bytes(self.payload[..].try_into().unwrap());
        self.advance()?;
        Ok(n)
    }

    fn string(&mut self, kind: u8) -> Result<String> {
        self.expect(kind)?;
        let bytes = self.payload.strip_suffix(&[0]).unwrap_or(&self.payload);
        if !bytes.is_ascii() || bytes.contains(&0) {
            return Err(self.unsupported("string must be ASCII without embedded NUL"));
        }
        if kind != STRING && bytes.is_empty() {
            return Err(self.invalid("empty library or structure name"));
        }
        let s = String::from_utf8(bytes.to_vec()).unwrap();
        self.advance()?;
        Ok(s)
    }

    fn layer(&mut self, type_record: u8) -> Result<Layer> {
        Ok(Layer {
            number: u32::from(self.word(LAYER)?),
            datatype: u32::from(self.word(type_record)?),
        })
    }

    fn points(&mut self, exact_count: Option<usize>, minimum: usize) -> Result<Vec<Point>> {
        self.expect(XY)?;
        let (coordinates, tail) = self.payload.as_chunks::<8>();
        let count = coordinates.len();
        if !tail.is_empty() || count < minimum || exact_count.is_some_and(|n| n != count) {
            return Err(self.invalid("wrong number of XY coordinates"));
        }
        let points = coordinates
            .iter()
            .map(|bytes| Point {
                x: i64::from(i32::from_be_bytes(bytes[0..4].try_into().unwrap())),
                y: i64::from(i32::from_be_bytes(bytes[4..8].try_into().unwrap())),
            })
            .collect();
        self.advance()?;
        Ok(points)
    }

    fn transform(&mut self) -> Result<Transform> {
        let mut transform = Transform::default();
        if self.kind == STRANS {
            let flags = u16::from_be_bytes(self.payload[..].try_into().unwrap());
            if flags & !0x8000 != 0 {
                return Err(self.unsupported("absolute or reserved STRANS flags"));
            }
            transform.reflect_x = flags & 0x8000 != 0;
            self.advance()?;
            if self.kind == MAG {
                transform.magnification = decode_real(&self.payload, true)?;
                if transform.magnification <= 0.0 {
                    return Err(self.invalid("non-positive magnification"));
                }
                self.advance()?;
            }
            if self.kind == ANGLE {
                transform.angle_deg = decode_real(&self.payload, true)?;
                self.advance()?;
            }
        }
        Ok(transform)
    }

    fn reference(&mut self, is_array: bool) -> Result<Element> {
        let cell = self.string(SNAME)?;
        let transform = self.transform()?;
        let (origin, array) = if is_array {
            self.expect(COLROW)?;
            let columns = u16::from_be_bytes(self.payload[0..2].try_into().unwrap());
            let rows = u16::from_be_bytes(self.payload[2..4].try_into().unwrap());
            if !(1..=32767).contains(&columns) || !(1..=32767).contains(&rows) {
                return Err(self.invalid("COLROW counts must be in 1..=32767"));
            }
            self.advance()?;
            let points = self.points(Some(3), 3)?;
            let origin = points[0];
            let step = |end: Point, count: u16| -> Result<Point> {
                let dx = end.x - origin.x;
                let dy = end.y - origin.y;
                let n = i64::from(count);
                if dx % n != 0 || dy % n != 0 {
                    return Err(Error::unsupported(
                        "GDSII array pitch is fractional in database units",
                    ));
                }
                Ok(Point {
                    x: dx / n,
                    y: dy / n,
                })
            };
            let array = Array {
                columns: u32::from(columns),
                rows: u32::from(rows),
                column_step: step(points[1], columns)?,
                row_step: step(points[2], rows)?,
            };
            (origin, Some(Repetition::Regular(array)))
        } else {
            (self.points(Some(1), 1)?[0], None)
        };
        Ok(Element::Reference {
            cell,
            origin,
            transform,
            array,
        })
    }

    fn int4(&mut self, kind: u8) -> Result<i64> {
        self.expect(kind)?;
        let value = i32::from_be_bytes(self.payload[..].try_into().unwrap());
        self.advance()?;
        Ok(i64::from(value))
    }

    fn path(&mut self) -> Result<Element> {
        let layer = self.layer(DATATYPE)?;
        let pathtype = if self.kind == PATHTYPE {
            self.word(PATHTYPE)?
        } else {
            0
        };
        let signed_width = if self.kind == WIDTH {
            self.int4(WIDTH)?
        } else {
            0
        };
        let ends = match pathtype {
            0 => PathEnds::Flush,
            1 => PathEnds::Round,
            2 => PathEnds::HalfWidth,
            4 => PathEnds::Explicit {
                begin: self.int4(BGNEXTN)?,
                end: self.int4(ENDEXTN)?,
            },
            _ => return Err(self.unsupported("unsupported GDSII PATHTYPE")),
        };
        let points = self.points(None, 2)?;
        if signed_width >= 0 && ends == PathEnds::Flush {
            Ok(Element::Path {
                layer,
                points,
                width: signed_width,
            })
        } else {
            Ok(Element::ExtendedPath {
                layer,
                points,
                width: signed_width.abs(),
                absolute_width: signed_width < 0,
                ends,
            })
        }
    }

    fn property(&mut self) -> Result<Property> {
        let key = self.word(PROPATTR)?;
        self.expect(PROPVALUE)?;
        let value = self
            .payload
            .strip_suffix(&[0])
            .unwrap_or(&self.payload)
            .to_vec();
        self.advance()?;
        Ok(Property::gds(key, value))
    }

    fn element(&mut self) -> Result<Element> {
        let kind = self.kind;
        self.advance()?;
        let element = match kind {
            BOX => {
                let layer = self.layer(BOXTYPE)?;
                let mut points = self.points(Some(5), 5)?;
                let [a, b, c, d, end] = points.as_slice() else {
                    unreachable!()
                };
                let edge = |a: &Point, b: &Point| {
                    (
                        i128::from(b.x) - i128::from(a.x),
                        i128::from(b.y) - i128::from(a.y),
                    )
                };
                let u = edge(a, b);
                let v = edge(b, c);
                if a != end
                    || u == (0, 0)
                    || v == (0, 0)
                    || u.0 * v.0 + u.1 * v.1 != 0
                    || edge(d, c) != u
                    || edge(a, d) != v
                {
                    return Err(self.invalid("BOX must contain a closed nondegenerate rectangle"));
                }
                // Follow gdspy's editable-geometry convention. Raw cell tools retain BOX verbatim.
                points.pop();
                Element::Polygon { layer, points }
            }
            BOUNDARY => {
                let layer = self.layer(DATATYPE)?;
                let mut points = self.points(None, 1)?;
                while self.kind == XY {
                    points.extend(self.points(None, 1)?);
                }
                if points.len() < 4 {
                    return Err(self.invalid("BOUNDARY needs at least 4 coordinates"));
                }
                if points.first() != points.last() {
                    return Err(self.invalid("BOUNDARY has no repeated closing point"));
                }
                points.pop();
                Element::Polygon { layer, points }
            }
            PATH => self.path()?,
            TEXT => {
                let layer = self.layer(TEXTTYPE)?;
                let presentation = if self.kind == PRESENTATION {
                    self.word(PRESENTATION)?
                } else {
                    0
                };
                let path_type = if self.kind == PATHTYPE {
                    Some(self.word(PATHTYPE)?)
                } else {
                    None
                };
                let width = if self.kind == WIDTH {
                    Some(self.int4(WIDTH)?)
                } else {
                    None
                };
                let transform = self.transform()?;
                let style = (presentation != 0
                    || transform != Transform::default()
                    || path_type.is_some()
                    || width.is_some())
                .then_some(TextStyle {
                    presentation,
                    transform,
                    path_type,
                    width,
                });
                let origin = self.points(Some(1), 1)?[0];
                let text = self.string(STRING)?;
                Element::Text {
                    layer,
                    origin,
                    text,
                    text_reference: None,
                    style,
                }
            }
            SREF | AREF => self.reference(kind == AREF)?,
            _ => return Err(self.invalid("expected an element")),
        };
        let mut properties = Vec::new();
        while self.kind == PROPATTR {
            properties.push(self.property()?);
        }
        self.take(ENDEL)?;
        Ok(if properties.is_empty() {
            element
        } else {
            Element::Attributed {
                element: Box::new(element),
                properties,
            }
        })
    }

    fn finish(&mut self) -> Result<()> {
        let mut padding = [0u8; 8192];
        loop {
            match self.stream.read(&mut padding) {
                Ok(0) => return Ok(()),
                Ok(n) if padding[..n].iter().all(|b| *b == 0) => {}
                Ok(_) => return Err(self.invalid("unexpected nonzero data after ENDLIB")),
                Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
                Err(err) => return Err(err.into()),
            }
        }
    }
}

pub(crate) fn read<R: Read>(r: R, layers: Option<&BTreeSet<Layer>>) -> Result<Layout> {
    let mut d = Decoder {
        stream: r,
        offset: 0,
        next_offset: 0,
        kind: HEADER,
        payload: Vec::new(),
    };
    d.advance()?;
    if !matches!(d.word(HEADER)?, 0 | 3 | 4 | 5 | 6 | 600) {
        return Err(Error::unsupported("unsupported GDSII HEADER version"));
    }
    d.take(BGNLIB)?;
    let name = d.string(LIBNAME)?;
    d.expect(UNITS)?;
    let user_ratio = decode_real(&d.payload[..8], false)?;
    let dbu_meters = decode_real(&d.payload[8..], true)?;
    if user_ratio <= 0.0 || dbu_meters <= 0.0 {
        return Err(d.invalid("UNITS must be positive"));
    }
    d.advance()?;
    let mut cells = Vec::new();
    while d.kind == BGNSTR {
        d.advance()?;
        let name = d.string(STRNAME)?;
        let mut elements = Vec::new();
        while matches!(d.kind, BOUNDARY | BOX | PATH | SREF | AREF | TEXT) {
            let element = d.element()?;
            if layers
                .zip(element.layer())
                .is_none_or(|(set, layer)| set.contains(&layer))
            {
                elements.push(element);
            } else {
                element.validate()?;
            }
        }
        d.take(ENDSTR)?;
        cells.push(Cell {
            name,
            elements,
            properties: Vec::new(),
            name_properties: Vec::new(),
        });
    }
    d.expect(ENDLIB)?;
    d.finish()?;
    Ok(Layout {
        name,
        dbu_meters,
        cells,
        properties: Vec::new(),
        layer_names: Vec::new(),
        table_properties: Vec::new(),
    })
}

struct Encoder<W> {
    stream: W,
}

impl<W: Write> Encoder<W> {
    fn record(&mut self, kind: u8, payload: &[u8]) -> Result<()> {
        let size = u16::try_from(payload.len() + 4)
            .map_err(|_| Error::unsupported("GDSII record exceeds 65535 bytes"))?;
        let (dtype, _) = record_spec(kind).unwrap();
        self.stream.write_all(&size.to_be_bytes())?;
        self.stream.write_all(&[kind, dtype])?;
        self.stream.write_all(payload)?;
        Ok(())
    }

    fn string(&mut self, kind: u8, value: &str) -> Result<()> {
        if !value.is_ascii()
            || value.as_bytes().contains(&0)
            || (value.is_empty() && kind != STRING)
        {
            return Err(Error::unsupported(
                "GDSII strings require ASCII without NUL and names must be nonempty",
            ));
        }
        if value.len() > u16::MAX as usize - 5 {
            return Err(Error::unsupported("string exceeds GDSII record capacity"));
        }
        if value.len().is_multiple_of(2) {
            return self.record(kind, value.as_bytes());
        }
        let mut bytes = Vec::with_capacity(value.len() + 1);
        bytes.extend_from_slice(value.as_bytes());
        bytes.push(0);
        self.record(kind, &bytes)
    }

    fn layer(&mut self, layer: &Layer, type_record: u8) -> Result<()> {
        let number = u16::try_from(layer.number)
            .map_err(|_| Error::unsupported("layer exceeds GDSII 16-bit range"))?;
        let datatype = u16::try_from(layer.datatype)
            .map_err(|_| Error::unsupported("datatype exceeds GDSII 16-bit range"))?;
        self.record(LAYER, &number.to_be_bytes())?;
        self.record(type_record, &datatype.to_be_bytes())
    }

    fn xy(&mut self, points: &[Point], close: bool) -> Result<()> {
        if points.is_empty() {
            return Err(Error::invalid("empty GDSII XY record"));
        }
        if !close && points.len() > MAX_XY_POINTS {
            return Err(Error::unsupported(
                "too many points for a single GDSII XY record",
            ));
        }
        let mut data = Vec::with_capacity(
            (points.len().min(MAX_XY_POINTS) + usize::from(close)).min(MAX_XY_POINTS) * 8,
        );
        for p in points.iter().chain(points.first().filter(|_| close)) {
            for v in [p.x, p.y] {
                let n = i32::try_from(v).map_err(|_| {
                    Error::unsupported("coordinate exceeds GDSII signed 32-bit range")
                })?;
                data.extend_from_slice(&n.to_be_bytes());
            }
            if data.len() == MAX_XY_POINTS * 8 {
                self.record(XY, &data)?;
                data.clear();
            }
        }
        if !data.is_empty() {
            self.record(XY, &data)?;
        }
        Ok(())
    }

    fn transform(&mut self, t: &Transform) -> Result<()> {
        if !t.reflect_x && t.angle_deg == 0.0 && t.magnification == 1.0 {
            return Ok(());
        }
        if t.magnification <= 0.0 {
            return Err(Error::invalid("magnification must be positive"));
        }
        self.record(
            STRANS,
            &(if t.reflect_x { 0x8000u16 } else { 0 }).to_be_bytes(),
        )?;
        if t.magnification != 1.0 {
            self.record(MAG, &encode_real(t.magnification)?)?;
        }
        if t.angle_deg != 0.0 {
            self.record(ANGLE, &encode_real(t.angle_deg)?)?;
        }
        Ok(())
    }

    fn array(&mut self, origin: Point, a: &Array) -> Result<()> {
        if !(1..=32767).contains(&a.columns) || !(1..=32767).contains(&a.rows) {
            return Err(Error::unsupported("GDSII AREF counts must be in 1..=32767"));
        }
        let mut counts = [0u8; 4];
        counts[..2].copy_from_slice(&(a.columns as u16).to_be_bytes());
        counts[2..].copy_from_slice(&(a.rows as u16).to_be_bytes());
        self.record(COLROW, &counts)?;
        // AREF's second/third points lie one pitch beyond the last instance.
        let endpoint = |step: Point, count: u32| -> Result<Point> {
            let add = |base, delta| {
                i64::try_from(i128::from(base) + i128::from(delta) * i128::from(count))
                    .map_err(|_| Error::unsupported("GDSII AREF endpoint overflow"))
            };
            Ok(Point {
                x: add(origin.x, step.x)?,
                y: add(origin.y, step.y)?,
            })
        };
        self.xy(
            &[
                origin,
                endpoint(a.column_step, a.columns)?,
                endpoint(a.row_step, a.rows)?,
            ],
            false,
        )
    }

    fn property(&mut self, p: &Property) -> Result<()> {
        if p.name_reference.is_some() {
            return Err(Error::unsupported(
                "GDSII cannot preserve an explicit OASIS PROPNAME table binding",
            ));
        }
        let [PropertyValue::Unsigned(key), PropertyValue::Binary(value)] = p.values.as_slice()
        else {
            return Err(Error::unsupported(
                "GDSII requires properties with an unsigned attribute and a binary value",
            ));
        };
        if !p.standard || p.name != "S_GDS_PROPERTY" {
            return Err(Error::unsupported(format!(
                "property {:?} has no GDSII representation",
                p.name
            )));
        }
        let attr = u16::try_from(*key)
            .map_err(|_| Error::unsupported("GDSII property attribute exceeds 16 bits"))?;
        if value.len() > u16::MAX as usize - 5 {
            return Err(Error::unsupported(
                "GDSII property exceeds the record capacity",
            ));
        }
        if value.len().is_multiple_of(2) && value.last() == Some(&0) {
            return Err(Error::unsupported(
                "an even-length GDSII property ending in NUL is ambiguous with padding",
            ));
        }
        self.record(PROPATTR, &attr.to_be_bytes())?;
        if value.len().is_multiple_of(2) {
            self.record(PROPVALUE, value)
        } else {
            let mut padded = value.clone();
            padded.push(0);
            self.record(PROPVALUE, &padded)
        }
    }

    fn path(
        &mut self,
        layer: &Layer,
        points: &[Point],
        width: i64,
        absolute: bool,
        ends: &PathEnds,
    ) -> Result<()> {
        self.record(PATH, &[])?;
        self.layer(layer, DATATYPE)?;
        let code: u16 = match ends {
            PathEnds::Flush => 0,
            PathEnds::Round => 1,
            PathEnds::HalfWidth => 2,
            PathEnds::Explicit { .. } => 4,
        };
        if code != 0 {
            self.record(PATHTYPE, &code.to_be_bytes())?;
        }
        if width < 0 || absolute && width == 0 {
            return Err(Error::invalid(
                "GDSII path width or its absolute flag is invalid",
            ));
        }
        let signed = if absolute { -width } else { width };
        let width = i32::try_from(signed)
            .map_err(|_| Error::unsupported("path width exceeds GDSII signed 32-bit range"))?;
        self.record(WIDTH, &width.to_be_bytes())?;
        if let PathEnds::Explicit { begin, end } = ends {
            for (record, value) in [(BGNEXTN, begin), (ENDEXTN, end)] {
                let n = i32::try_from(*value).map_err(|_| {
                    Error::unsupported("path extension exceeds GDSII signed 32-bit range")
                })?;
                self.record(record, &n.to_be_bytes())?;
            }
        }
        self.xy(points, false)
    }

    fn element(&mut self, e: &Element) -> Result<()> {
        match e.unadorned() {
            Element::Polygon { layer, points } => {
                self.record(BOUNDARY, &[])?;
                self.layer(layer, DATATYPE)?;
                self.xy(points, true)?;
            }
            Element::Path {
                layer,
                points,
                width,
            } => self.path(layer, points, *width, false, &PathEnds::Flush)?,
            Element::ExtendedPath {
                layer,
                points,
                width,
                absolute_width,
                ends,
            } => self.path(layer, points, *width, *absolute_width, ends)?,
            Element::Attributed { .. } => {
                return Err(Error::invalid("nested element property wrappers"));
            }
            Element::Text {
                layer,
                origin,
                text,
                text_reference,
                style,
            } => {
                if text_reference.is_some() {
                    return Err(Error::unsupported(
                        "GDSII cannot preserve an explicit OASIS TEXTSTRING table binding",
                    ));
                }
                self.record(TEXT, &[])?;
                self.layer(layer, TEXTTYPE)?;
                if let Some(style) = style {
                    if style.presentation != 0 {
                        self.record(PRESENTATION, &style.presentation.to_be_bytes())?;
                    }
                    if let Some(kind) = style.path_type {
                        self.record(PATHTYPE, &kind.to_be_bytes())?;
                    }
                    if let Some(w) = style.width {
                        let signed = i32::try_from(w).map_err(|_| {
                            Error::unsupported(
                                "text stroke width exceeds GDSII signed 32-bit range",
                            )
                        })?;
                        self.record(WIDTH, &signed.to_be_bytes())?;
                    }
                    self.transform(&style.transform)?;
                }
                self.xy(std::slice::from_ref(origin), false)?;
                self.string(STRING, text)?;
            }
            Element::Circle { .. } => {
                return Err(Error::unsupported("GDSII has no native CIRCLE record"));
            }
            Element::Repeated { .. } => {
                return Err(Error::unsupported(
                    "GDSII cannot encode a shape repetition without expanding the instances",
                ));
            }
            Element::Reference {
                cell,
                origin,
                transform,
                array,
            } => {
                self.record(if array.is_some() { AREF } else { SREF }, &[])?;
                self.string(SNAME, cell)?;
                self.transform(transform)?;
                match array {
                    Some(Repetition::Regular(a)) => self.array(*origin, a)?,
                    Some(Repetition::Offsets(_)) => {
                        return Err(Error::unsupported(
                            "GDSII references cannot store arbitrary offsets in one record",
                        ));
                    }
                    None => self.xy(std::slice::from_ref(origin), false)?,
                }
            }
        }
        for p in e.properties() {
            self.property(p)?;
        }
        self.record(ENDEL, &[])
    }
}

pub(crate) fn check_property(p: &Property) -> Result<()> {
    Encoder { stream: io::sink() }.property(p)
}
pub(crate) fn check_element(e: &Element) -> Result<()> {
    write_element(io::sink(), e)
}
pub(crate) fn write_element(w: impl Write, e: &Element) -> Result<()> {
    Encoder { stream: w }.element(e)
}
pub(crate) fn check_text(s: &str) -> Result<()> {
    Encoder { stream: io::sink() }.string(STRING, s)
}
pub(crate) fn check_array(origin: Point, array: &Array) -> Result<()> {
    Encoder { stream: io::sink() }.array(origin, array)
}
pub(crate) fn check_name(s: &str) -> Result<()> {
    Encoder { stream: io::sink() }.string(STRNAME, s)
}

pub(crate) fn encode_dates(timestamp: [u16; 6]) -> [u8; 24] {
    let mut dates = [0u8; 24];
    for (out, n) in dates
        .as_chunks_mut::<2>()
        .0
        .iter_mut()
        .zip(timestamp.into_iter().cycle())
    {
        *out = n.to_be_bytes();
    }
    dates
}

pub(crate) fn write_header(
    w: impl Write,
    name: &str,
    unit: f64,
    dbu_meters: f64,
    timestamp: [u16; 6],
) -> Result<()> {
    if !(unit.is_finite() && unit > 0. && dbu_meters.is_finite() && dbu_meters > 0.) {
        return Err(Error::invalid(
            "both GDSII units must be positive and finite",
        ));
    }
    let mut e = Encoder { stream: w };
    e.record(HEADER, &600u16.to_be_bytes())?;
    e.record(BGNLIB, &encode_dates(timestamp))?;
    e.string(LIBNAME, name)?;
    let ratio = dbu_meters / unit;
    if ratio == 0. {
        return Err(Error::unsupported("GDSII unit ratio underflows"));
    }
    let mut units = [0u8; 16];
    units[..8].copy_from_slice(&encode_real(ratio)?);
    units[8..].copy_from_slice(&encode_real(dbu_meters)?);
    e.record(UNITS, &units)
}

pub(crate) fn write_cell(w: impl Write, cell: &Cell, timestamp: [u16; 6]) -> Result<()> {
    if !cell.properties.is_empty() || !cell.name_properties.is_empty() {
        return Err(Error::unsupported(format!(
            "GDSII cannot store properties on cell {:?} or its name",
            cell.name
        )));
    }
    let mut e = Encoder { stream: w };
    e.record(BGNSTR, &encode_dates(timestamp))?;
    e.string(STRNAME, &cell.name)?;
    for (index, element) in cell.elements.iter().enumerate() {
        e.element(element)
            .map_err(|err| err.at_element(&cell.name, index, element))?;
    }
    e.record(ENDSTR, &[])
}

pub(crate) fn write<W: Write>(layout: &Layout, mut w: W) -> Result<()> {
    if !layout.table_properties.is_empty() {
        return Err(Error::unsupported(
            "GDSII cannot store OASIS name-table properties",
        ));
    }
    if !layout.layer_names.is_empty() {
        return Err(Error::unsupported("GDSII cannot store OASIS layer names"));
    }
    if !layout.properties.is_empty() {
        return Err(Error::unsupported("GDSII cannot store library properties"));
    }
    write_header(
        &mut w,
        &layout.name,
        1e-6,
        layout.dbu_meters,
        DEFAULT_TIMESTAMP,
    )?;
    for cell in &layout.cells {
        write_cell(&mut w, cell, DEFAULT_TIMESTAMP)?;
    }
    w.write_all(&[0, 4, ENDLIB, 0])?;
    w.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn point(x: i64, y: i64) -> Point {
        Point { x, y }
    }
    fn layer(n: u32) -> Layer {
        Layer {
            number: n,
            datatype: 2,
        }
    }

    fn example() -> Layout {
        Layout {
            layer_names: Vec::new(),
            table_properties: Vec::new(),
            properties: Vec::new(),
            name: "Mask".into(),
            dbu_meters: 1e-9,
            cells: vec![
                Cell {
                    properties: Vec::new(),
                    name_properties: Vec::new(),
                    name: "TOP".into(),
                    elements: vec![Element::Reference {
                        cell: "LEAF".into(),
                        origin: point(-5, 20),
                        transform: Transform {
                            angle_deg: 90.0,
                            magnification: 1.5,
                            reflect_x: true,
                        },
                        array: Some(Repetition::Regular(Array {
                            columns: 2,
                            rows: 3,
                            column_step: point(0, 11),
                            row_step: point(-7, 0),
                        })),
                    }],
                },
                Cell {
                    properties: Vec::new(),
                    name_properties: Vec::new(),
                    name: "LEAF".into(),
                    elements: vec![
                        Element::Polygon {
                            layer: layer(4),
                            points: vec![point(-2, 0), point(6, 2), point(4, 7)],
                        },
                        Element::Path {
                            layer: layer(8),
                            points: vec![point(0, 0), point(10, 20)],
                            width: 3,
                        },
                        Element::Text {
                            layer: layer(4),
                            origin: point(-3, 8),
                            text: "PIN".into(),
                            text_reference: None,
                            style: Some(TextStyle {
                                presentation: 0x15,
                                path_type: Some(1),
                                width: Some(-3),
                                transform: Transform {
                                    angle_deg: 90.0,
                                    magnification: 0.1,
                                    reflect_x: true,
                                },
                            }),
                        },
                    ],
                },
            ],
        }
    }

    fn encode(layout: &Layout) -> Vec<u8> {
        let mut bytes = Vec::new();
        write(layout, &mut bytes).unwrap();
        bytes
    }

    fn locate(bytes: &[u8], kind: u8) -> usize {
        let mut pos = 0;
        while pos < bytes.len() {
            if bytes[pos + 2] == kind {
                return pos;
            }
            pos += usize::from(u16::from_be_bytes(bytes[pos..pos + 2].try_into().unwrap()));
        }
        panic!("missing record {kind}");
    }

    #[test]
    fn real8_uses_base_sixteen_and_preserves_dbu() {
        for (v, word) in [
            (0., 0u64),
            (1., 0x4110000000000000),
            (-0.5, 0xc080000000000000),
            (1e-9, 0x3944b82fa09b5a54),
        ] {
            assert_eq!(encode_real(v).unwrap(), word.to_be_bytes());
            assert_eq!(decode_real(&word.to_be_bytes(), true).unwrap(), v);
        }
        for v in [f64::INFINITY, f64::NAN, 2f64.powi(252), 2f64.powi(-261)] {
            assert!(encode_real(v).is_err());
        }
        assert!(decode_real(&[0x41, 0x80, 0, 0, 0, 0, 0, 1], true).is_err());
        for v in [2f64.powi(-260), 2f64.powi(251)] {
            assert_eq!(decode_real(&encode_real(v).unwrap(), true).unwrap(), v);
        }
    }

    #[test]
    fn reads_forward_array_references_and_filters_local_shapes() {
        let bytes = encode(&example());
        let xy = locate(&bytes, XY) + 4;
        let expected = [-5i32, 20, -5, 42, -26, 20];
        for (chunk, coordinate) in bytes[xy..xy + 24].as_chunks::<4>().0.iter().zip(expected) {
            assert_eq!(*chunk, coordinate.to_be_bytes());
        }
        let roundtrip = read(bytes.as_slice(), None).unwrap();
        assert_eq!(encode(&roundtrip), bytes);
        assert_eq!(roundtrip.dbu_meters, 1e-9);
        let Element::Text { style, .. } = &roundtrip.cells[1].elements[2] else {
            panic!("missing text");
        };
        let style = style.as_ref().unwrap();
        assert_eq!(style.presentation, 0x15);
        assert_eq!(style.path_type, Some(1));
        assert_eq!(style.width, Some(-3));
        assert_eq!(
            style.transform,
            Transform {
                angle_deg: 90.0,
                magnification: 0.1,
                reflect_x: true
            }
        );
        let filtered = read(bytes.as_slice(), Some(&[layer(4)].into())).unwrap();
        assert_eq!(filtered.cells[0].elements.len(), 1);
        assert_eq!(filtered.cells[1].elements.len(), 2);
        assert!(matches!(
            filtered.cells[0].elements[0],
            Element::Reference { .. }
        ));
        assert!(matches!(
            filtered.cells[1].elements[1],
            Element::Text { .. }
        ));
    }

    #[test]
    fn rejects_unrepresentable_records_and_payloads() {
        let bytes = encode(&example());
        let mut properties = bytes.clone();
        let pos = locate(&properties, ENDEL);
        properties.splice(pos..pos, [0, 6, 0x2b, 2, 0, 1]);
        assert!(read(properties.as_slice(), None).is_err());

        let mut fractional = bytes.clone();
        let y = locate(&fractional, XY) + 4 + 12;
        fractional[y + 3] = 43;
        assert!(read(fractional.as_slice(), None).is_err());

        let mut absolute = bytes.clone();
        let flags = locate(&absolute, STRANS) + 5;
        absolute[flags] |= 2;
        assert!(read(absolute.as_slice(), None).is_err());

        let mut malformed = bytes.clone();
        let layer = locate(&malformed, LAYER) + 3;
        malformed[layer] = 3;
        assert!(read(malformed.as_slice(), None).is_err());
        assert!(read(&bytes[..bytes.len() - 1], None).is_err());
        let mut padded = bytes;
        padded.extend([0; 64]);
        assert!(read(padded.as_slice(), None).is_ok());
        padded.push(1);
        assert!(read(padded.as_slice(), None).is_err());
    }

    #[test]
    fn preserves_repeated_binary_properties_on_all_gds_elements() {
        let mut layout = example();
        let properties =
            [vec![0x80, 0, 1, 0xff], vec![0, 2, 0], vec![]].map(|bytes| Property::gds(77, bytes));
        for cell in &mut layout.cells {
            for element in &mut cell.elements {
                *element = element.clone().with_properties(properties.to_vec());
            }
        }
        assert_eq!(read(encode(&layout).as_slice(), None).unwrap(), layout);
        let props = &mut layout.cells[0].elements[0];
        *props = props
            .clone()
            .with_properties(vec![Property::gds(77, vec![1, 0])]);
        assert!(matches!(
            write(&layout, Vec::new()),
            Err(Error::Unsupported(_))
        ));
        layout.cells[0].elements.clear();
        layout.cells[0].name_properties = properties.to_vec();
        assert!(matches!(
            write(&layout, Vec::new()),
            Err(Error::Unsupported(_))
        ));
        layout.cells[0].name_properties.clear();
        layout.properties = properties.to_vec();
        assert!(matches!(
            write(&layout, Vec::new()),
            Err(Error::Unsupported(_))
        ));
    }

    #[test]
    fn box_requires_four_perpendicular_edges_and_a_closing_vertex() {
        let mut layout = Layout::new("LIB", 1e-9).unwrap();
        layout.add_cell("C").unwrap();
        // Rotated rectangle with integer vertices.
        layout
            .add_element(
                "C",
                Element::Polygon {
                    layer: layer(2),
                    points: vec![point(0, 0), point(3, 3), point(1, 5), point(-2, 2)],
                },
            )
            .unwrap();
        let mut bytes = encode(&layout);
        let start = locate(&bytes, BOUNDARY) + 2;
        let datatype = locate(&bytes, DATATYPE) + 2;
        bytes[start] = BOX;
        bytes[datatype] = BOXTYPE;
        assert_eq!(read(bytes.as_slice(), None).unwrap(), layout);
        let xy = locate(&bytes, XY) + 4;
        for (index, value) in [(0, 7i32), (2, 4), (4, -7), (8, 1)] {
            let mut broken = bytes.clone();
            broken[xy + 4 * index..xy + 4 * (index + 1)].copy_from_slice(&value.to_be_bytes());
            assert!(read(broken.as_slice(), None).is_err());
        }
    }

    #[test]
    fn supports_gdspy_multi_xy_boundaries_without_fracturing() {
        let mut layout = example();
        let mut points: Vec<_> = (0..10_000).map(|x| point(x, x % 2)).collect();
        points.push(point(5000, 1000));
        layout.cells[1].elements.push(Element::Polygon {
            layer: layer(8),
            points,
        });
        assert_eq!(read(encode(&layout).as_slice(), None).unwrap(), layout);
    }

    #[test]
    fn extended_paths_preserve_caps_absolute_width_and_signed_extensions() {
        let mut layout = example();
        for ends in [
            PathEnds::Flush,
            PathEnds::Round,
            PathEnds::HalfWidth,
            PathEnds::Explicit { begin: -5, end: 27 },
        ] {
            layout.cells[1].elements.push(Element::ExtendedPath {
                layer: layer(8),
                points: vec![point(-4, 5), point(17, 19)],
                width: 2147483648,
                absolute_width: true,
                ends,
            });
        }
        assert_eq!(read(encode(&layout).as_slice(), None).unwrap(), layout);
    }

    #[test]
    fn rejects_shape_arrays_without_expanding_them() {
        let mut layout = example();
        let shapes = &mut layout.cells[1].elements;
        let polygon = shapes.remove(0);
        shapes.push(Element::Repeated {
            element: Box::new(polygon),
            array: Repetition::Regular(Array {
                columns: 100,
                rows: 1,
                column_step: point(10, 0),
                row_step: point(0, 0),
            }),
        });
        assert!(matches!(
            write(&layout, Vec::new()),
            Err(Error::Unsupported(_))
        ));
    }

    #[test]
    fn rejects_coordinate_and_array_endpoint_overflow() {
        let mut layout = example();
        if let Element::Reference {
            array: Some(Repetition::Regular(a)),
            ..
        } = &mut layout.cells[0].elements[0]
        {
            a.column_step.x = i64::MAX;
        }
        assert!(write(&layout, Vec::new()).is_err());
        let mut layout = example();
        if let Element::Polygon { points, .. } = &mut layout.cells[1].elements[0] {
            points[0].x = i64::from(i32::MAX) + 1;
        }
        assert!(write(&layout, Vec::new()).is_err());
    }
}