Skip to main content

laykit/
gdsii.rs

1// GDSII (Graphic Database System II) Reader/Writer
2// Industry standard format for IC layout interchange
3// Binary format with record-based structure
4
5use std::fs::File;
6use std::io::{BufReader, BufWriter, Read, Write};
7use std::path::Path;
8
9/// GDSII File structure
10#[derive(Debug, Clone)]
11pub struct GDSIIFile {
12    pub version: u16,
13    pub modification_time: GDSTime,
14    pub access_time: GDSTime,
15    pub library_name: String,
16    pub units: (f64, f64),         // (user_units, database_units in meters)
17    pub reflibs: Vec<String>,      // Referenced library names (record 0x1F)
18    pub fonts: Vec<String>,        // Font table (record 0x29)
19    pub generations: Option<i16>,  // Backup generations (record 0x3C)
20    pub attrtable: Option<String>, // Attribute table reference (record 0x3D)
21    pub structures: Vec<GDSStructure>,
22}
23
24#[derive(Debug, Clone)]
25pub struct GDSTime {
26    pub year: u16,
27    pub month: u16,
28    pub day: u16,
29    pub hour: u16,
30    pub minute: u16,
31    pub second: u16,
32}
33
34#[derive(Debug, Clone)]
35pub struct GDSStructure {
36    pub name: String,
37    pub creation_time: GDSTime,
38    pub modification_time: GDSTime,
39    pub strclass: Option<i16>, // Structure class (record 0x34)
40    pub elements: Vec<GDSElement>,
41}
42
43#[derive(Debug, Clone)]
44pub enum GDSElement {
45    Boundary(Boundary),
46    Path(GPath),
47    StructRef(StructRef),
48    ArrayRef(ArrayRef),
49    Text(GText),
50    Node(Node),
51    Box(GDSBox),
52}
53
54#[derive(Debug, Clone)]
55pub struct Boundary {
56    pub layer: i16,
57    pub datatype: i16,
58    pub xy: Vec<(i32, i32)>,
59    pub elflags: Option<i16>, // Element flags (record 0x26)
60    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
61    pub properties: Vec<GDSProperty>,
62}
63
64#[derive(Debug, Clone)]
65pub struct GPath {
66    pub layer: i16,
67    pub datatype: i16,
68    pub pathtype: i16,
69    pub width: Option<i32>,
70    pub bgnextn: Option<i32>, // Path extension at beginning (record 0x30)
71    pub endextn: Option<i32>, // Path extension at end (record 0x31)
72    pub xy: Vec<(i32, i32)>,
73    pub elflags: Option<i16>, // Element flags (record 0x26)
74    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
75    pub properties: Vec<GDSProperty>,
76}
77
78#[derive(Debug, Clone)]
79pub struct StructRef {
80    pub sname: String,
81    pub xy: (i32, i32),
82    pub strans: Option<STrans>,
83    pub elflags: Option<i16>, // Element flags (record 0x26)
84    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
85    pub properties: Vec<GDSProperty>,
86}
87
88#[derive(Debug, Clone)]
89pub struct ArrayRef {
90    pub sname: String,
91    pub columns: u16,
92    pub rows: u16,
93    pub xy: Vec<(i32, i32)>, // 3 points: origin, column_spacing, row_spacing
94    pub strans: Option<STrans>,
95    pub elflags: Option<i16>, // Element flags (record 0x26)
96    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
97    pub properties: Vec<GDSProperty>,
98}
99
100#[derive(Debug, Clone)]
101pub struct GText {
102    pub layer: i16,
103    pub texttype: i16,
104    pub string: String,
105    pub xy: (i32, i32),
106    pub presentation: Option<i16>,
107    pub strans: Option<STrans>,
108    pub width: Option<i32>,
109    pub elflags: Option<i16>, // Element flags (record 0x26)
110    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
111    pub properties: Vec<GDSProperty>,
112}
113
114#[derive(Debug, Clone)]
115pub struct Node {
116    pub layer: i16,
117    pub nodetype: i16,
118    pub xy: Vec<(i32, i32)>,
119    pub elflags: Option<i16>, // Element flags (record 0x26)
120    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
121    pub properties: Vec<GDSProperty>,
122}
123
124#[derive(Debug, Clone)]
125pub struct GDSBox {
126    pub layer: i16,
127    pub boxtype: i16,
128    pub xy: Vec<(i32, i32)>,
129    pub elflags: Option<i16>, // Element flags (record 0x26)
130    pub plex: Option<i32>,    // Plex identifier (record 0x2F)
131    pub properties: Vec<GDSProperty>,
132}
133
134#[derive(Debug, Clone)]
135pub struct STrans {
136    pub reflection: bool,
137    pub absolute_magnification: bool,
138    pub absolute_angle: bool,
139    pub magnification: Option<f64>,
140    pub angle: Option<f64>,
141}
142
143#[derive(Debug, Clone)]
144pub struct GDSProperty {
145    pub attribute: i16,
146    pub value: String,
147}
148
149// GDSII Record Types (for reference)
150// These constants are used internally via their numeric values
151#[allow(dead_code)]
152mod record_types {
153    pub const HEADER: u8 = 0x00;
154    pub const BGNLIB: u8 = 0x01;
155    pub const LIBNAME: u8 = 0x02;
156    pub const UNITS: u8 = 0x03;
157    pub const ENDLIB: u8 = 0x04;
158    pub const BGNSTR: u8 = 0x05;
159    pub const STRNAME: u8 = 0x06;
160    pub const ENDSTR: u8 = 0x07;
161    pub const BOUNDARY: u8 = 0x08;
162    pub const PATH: u8 = 0x09;
163    pub const SREF: u8 = 0x0A;
164    pub const AREF: u8 = 0x0B;
165    pub const TEXT: u8 = 0x0C;
166    pub const LAYER: u8 = 0x0D;
167    pub const DATATYPE: u8 = 0x0E;
168    pub const WIDTH: u8 = 0x0F;
169    pub const XY: u8 = 0x10;
170    pub const ENDEL: u8 = 0x11;
171    pub const SNAME: u8 = 0x12;
172    pub const COLROW: u8 = 0x13;
173}
174
175// Data Types
176#[derive(Debug, Clone, Copy, PartialEq)]
177#[repr(u8)]
178enum DataType {
179    NoData = 0,
180    BitArray = 1,
181    TwoByteSignedInt = 2,
182    FourByteSignedInt = 3,
183    FourByteReal = 4,
184    EightByteReal = 5,
185    AsciiString = 6,
186}
187
188impl GDSIIFile {
189    /// Create a new empty GDSII file
190    pub fn new(library_name: String) -> Self {
191        let now = GDSTime::now();
192        GDSIIFile {
193            version: 600, // GDSII version 6.0
194            modification_time: now.clone(),
195            access_time: now,
196            library_name,
197            units: (1e-6, 1e-9), // 1 micron user unit, 1nm database unit
198            reflibs: Vec::new(),
199            fonts: Vec::new(),
200            generations: None,
201            attrtable: None,
202            structures: Vec::new(),
203        }
204    }
205
206    /// Read GDSII from file
207    pub fn read_from_file<P: AsRef<Path>>(path: P) -> Result<Self, Box<dyn std::error::Error>> {
208        let file = File::open(path)?;
209        let mut reader = BufReader::new(file);
210        Self::read_from_reader(&mut reader)
211    }
212
213    /// Read GDSII from any reader
214    pub fn read_from_reader<R: Read>(reader: &mut R) -> Result<Self, Box<dyn std::error::Error>> {
215        let mut buffer = Vec::new();
216        reader.read_to_end(&mut buffer)?;
217
218        let mut cursor = 0;
219        let mut gds = GDSIIFile::new(String::new());
220        let mut current_structure: Option<GDSStructure> = None;
221
222        // Track which element type is currently being built
223        #[derive(Debug, Clone, Copy, PartialEq)]
224        enum Building {
225            None,
226            Boundary,
227            Path,
228            StructRef,
229            ArrayRef,
230            Text,
231            Node,
232            Box,
233        }
234        let mut building = Building::None;
235
236        // Temporary storage for element construction
237        let mut layer: Option<i16> = None;
238        let mut datatype: Option<i16> = None;
239        let mut xy: Vec<(i32, i32)> = Vec::new();
240        let mut properties: Vec<GDSProperty> = Vec::new();
241        let mut sname: Option<String> = None;
242        let mut strans: Option<STrans> = None;
243        let mut width: Option<i32> = None;
244        let mut pathtype: Option<i16> = None;
245        let mut bgnextn: Option<i32> = None;
246        let mut endextn: Option<i32> = None;
247        let mut elflags: Option<i16> = None;
248        let mut plex: Option<i32> = None;
249        let mut texttype: Option<i16> = None;
250        let mut text_string: Option<String> = None;
251        let mut presentation: Option<i16> = None;
252        let mut colrow: Option<(u16, u16)> = None;
253        let mut nodetype: Option<i16> = None;
254        let mut boxtype: Option<i16> = None;
255        let mut current_prop_attr: Option<i16> = None;
256
257        while cursor < buffer.len() {
258            let (record_type, _data_type, data) = Self::read_record(&buffer, &mut cursor)?;
259
260            match record_type {
261                0x00 => {
262                    // HEADER
263                    gds.version = Self::parse_i16(&data)? as u16;
264                }
265                0x01 => {
266                    // BGNLIB
267                    let times = Self::parse_time(&data)?;
268                    gds.modification_time = times.0;
269                    gds.access_time = times.1;
270                }
271                0x02 => {
272                    // LIBNAME
273                    gds.library_name = Self::parse_string(&data)?;
274                }
275                0x03 => {
276                    // UNITS
277                    gds.units = Self::parse_units(&data)?;
278                }
279                0x1F => {
280                    // REFLIBS - Referenced libraries
281                    let reflib = Self::parse_string(&data)?;
282                    gds.reflibs.push(reflib);
283                }
284                0x29 => {
285                    // FONTS - Font table
286                    for i in (0..data.len()).step_by(44) {
287                        if i + 44 <= data.len() {
288                            let font = Self::parse_string(&data[i..i + 44])?;
289                            if !font.is_empty() {
290                                gds.fonts.push(font);
291                            }
292                        }
293                    }
294                }
295                0x3C => {
296                    // GENERATIONS - Number of backup generations
297                    gds.generations = Some(Self::parse_i16(&data)?);
298                }
299                0x3D => {
300                    // ATTRTABLE - Attribute table reference
301                    gds.attrtable = Some(Self::parse_string(&data)?);
302                }
303                0x04 => {
304                    // ENDLIB
305                    break;
306                }
307                0x05 => {
308                    // BGNSTR
309                    let times = Self::parse_time(&data)?;
310                    current_structure = Some(GDSStructure {
311                        name: String::new(),
312                        creation_time: times.0,
313                        modification_time: times.1,
314                        strclass: None,
315                        elements: Vec::new(),
316                    });
317                }
318                0x06 => {
319                    // STRNAME
320                    if let Some(ref mut structure) = current_structure {
321                        structure.name = Self::parse_string(&data)?;
322                    }
323                }
324                0x34 => {
325                    // STRCLASS - Structure class
326                    if let Some(ref mut structure) = current_structure {
327                        structure.strclass = Some(Self::parse_i16(&data)?);
328                    }
329                }
330                0x07 => {
331                    // ENDSTR
332                    if let Some(structure) = current_structure.take() {
333                        gds.structures.push(structure);
334                    }
335                }
336                0x08 => {
337                    // BOUNDARY
338                    building = Building::Boundary;
339                    layer = None;
340                    datatype = None;
341                    xy.clear();
342                    properties.clear();
343                    elflags = None;
344                    plex = None;
345                }
346                0x09 => {
347                    // PATH
348                    building = Building::Path;
349                    layer = None;
350                    datatype = None;
351                    xy.clear();
352                    properties.clear();
353                    width = None;
354                    pathtype = None;
355                    bgnextn = None;
356                    endextn = None;
357                    elflags = None;
358                    plex = None;
359                }
360                0x0A => {
361                    // SREF
362                    building = Building::StructRef;
363                    sname = None;
364                    xy.clear();
365                    strans = None;
366                    properties.clear();
367                    elflags = None;
368                    plex = None;
369                }
370                0x0B => {
371                    // AREF
372                    building = Building::ArrayRef;
373                    sname = None;
374                    xy.clear();
375                    strans = None;
376                    colrow = None;
377                    properties.clear();
378                    elflags = None;
379                    plex = None;
380                }
381                0x0C => {
382                    // TEXT
383                    building = Building::Text;
384                    layer = None;
385                    texttype = None;
386                    xy.clear();
387                    text_string = None;
388                    presentation = None;
389                    strans = None;
390                    width = None;
391                    properties.clear();
392                    elflags = None;
393                    plex = None;
394                }
395                0x15 => {
396                    // NODE
397                    building = Building::Node;
398                    layer = None;
399                    nodetype = None;
400                    xy.clear();
401                    properties.clear();
402                    elflags = None;
403                    plex = None;
404                }
405                0x2D => {
406                    // BOX
407                    building = Building::Box;
408                    layer = None;
409                    boxtype = None;
410                    xy.clear();
411                    properties.clear();
412                    elflags = None;
413                    plex = None;
414                }
415                0x0D => {
416                    // LAYER
417                    layer = Some(Self::parse_i16(&data)?);
418                }
419                0x0E => {
420                    // DATATYPE
421                    datatype = Some(Self::parse_i16(&data)?);
422                }
423                0x0F => {
424                    // WIDTH
425                    width = Some(Self::parse_i32(&data)?);
426                }
427                0x10 => {
428                    // XY
429                    xy = Self::parse_xy(&data)?;
430                }
431                0x11 => {
432                    // ENDEL - create element based on tracked type
433                    let new_element = match building {
434                        Building::Boundary => {
435                            if let (Some(l), Some(d)) = (layer, datatype) {
436                                Some(GDSElement::Boundary(Boundary {
437                                    layer: l,
438                                    datatype: d,
439                                    xy: xy.clone(),
440                                    elflags,
441                                    plex,
442                                    properties: properties.clone(),
443                                }))
444                            } else {
445                                None
446                            }
447                        }
448                        Building::Path => {
449                            if let (Some(l), Some(d)) = (layer, datatype) {
450                                Some(GDSElement::Path(GPath {
451                                    layer: l,
452                                    datatype: d,
453                                    pathtype: pathtype.unwrap_or(0),
454                                    width,
455                                    bgnextn,
456                                    endextn,
457                                    xy: xy.clone(),
458                                    elflags,
459                                    plex,
460                                    properties: properties.clone(),
461                                }))
462                            } else {
463                                None
464                            }
465                        }
466                        Building::StructRef => sname.as_ref().map(|sn| {
467                            GDSElement::StructRef(StructRef {
468                                sname: sn.clone(),
469                                xy: if !xy.is_empty() { xy[0] } else { (0, 0) },
470                                strans: strans.clone(),
471                                elflags,
472                                plex,
473                                properties: properties.clone(),
474                            })
475                        }),
476                        Building::ArrayRef => {
477                            if let (Some(sn), Some(cr)) = (sname.as_ref(), colrow) {
478                                Some(GDSElement::ArrayRef(ArrayRef {
479                                    sname: sn.clone(),
480                                    columns: cr.0,
481                                    rows: cr.1,
482                                    xy: xy.clone(),
483                                    strans: strans.clone(),
484                                    elflags,
485                                    plex,
486                                    properties: properties.clone(),
487                                }))
488                            } else {
489                                None
490                            }
491                        }
492                        Building::Text => {
493                            if let (Some(l), Some(tt), Some(ts)) =
494                                (layer, texttype, text_string.as_ref())
495                            {
496                                Some(GDSElement::Text(GText {
497                                    layer: l,
498                                    texttype: tt,
499                                    string: ts.clone(),
500                                    xy: if !xy.is_empty() { xy[0] } else { (0, 0) },
501                                    presentation,
502                                    strans: strans.clone(),
503                                    width,
504                                    elflags,
505                                    plex,
506                                    properties: properties.clone(),
507                                }))
508                            } else {
509                                None
510                            }
511                        }
512                        Building::Node => {
513                            if let (Some(l), Some(nt)) = (layer, nodetype) {
514                                Some(GDSElement::Node(Node {
515                                    layer: l,
516                                    nodetype: nt,
517                                    xy: xy.clone(),
518                                    elflags,
519                                    plex,
520                                    properties: properties.clone(),
521                                }))
522                            } else {
523                                None
524                            }
525                        }
526                        Building::Box => {
527                            if let (Some(l), Some(bt)) = (layer, boxtype) {
528                                Some(GDSElement::Box(GDSBox {
529                                    layer: l,
530                                    boxtype: bt,
531                                    xy: xy.clone(),
532                                    elflags,
533                                    plex,
534                                    properties: properties.clone(),
535                                }))
536                            } else {
537                                None
538                            }
539                        }
540                        Building::None => None,
541                    };
542
543                    if let (Some(elem), Some(ref mut structure)) =
544                        (new_element, current_structure.as_mut())
545                    {
546                        structure.elements.push(elem);
547                    }
548
549                    // Reset state
550                    building = Building::None;
551                    layer = None;
552                    datatype = None;
553                    xy.clear();
554                    properties.clear();
555                    sname = None;
556                    strans = None;
557                    width = None;
558                    pathtype = None;
559                    texttype = None;
560                    text_string = None;
561                    presentation = None;
562                    colrow = None;
563                    nodetype = None;
564                    boxtype = None;
565                    elflags = None;
566                    plex = None;
567                }
568                0x12 => {
569                    // SNAME
570                    sname = Some(Self::parse_string(&data)?);
571                }
572                0x13 => {
573                    // COLROW
574                    let cols = i16::from_be_bytes([data[0], data[1]]) as u16;
575                    let rows = i16::from_be_bytes([data[2], data[3]]) as u16;
576                    colrow = Some((cols, rows));
577                }
578                0x16 => {
579                    // TEXTTYPE
580                    texttype = Some(Self::parse_i16(&data)?);
581                }
582                0x17 => {
583                    // PRESENTATION
584                    presentation = Some(Self::parse_i16(&data)?);
585                }
586                0x19 => {
587                    // STRING
588                    text_string = Some(Self::parse_string(&data)?);
589                }
590                0x1A => {
591                    // STRANS
592                    let flags = i16::from_be_bytes([data[0], data[1]]);
593                    strans = Some(STrans {
594                        reflection: (flags & -0x8000_i16) != 0,
595                        absolute_magnification: (flags & 0x0004) != 0,
596                        absolute_angle: (flags & 0x0002) != 0,
597                        magnification: None,
598                        angle: None,
599                    });
600                }
601                0x1B => {
602                    // MAG
603                    let mag = Self::parse_real8(&data)?;
604                    if let Some(ref mut st) = strans {
605                        st.magnification = Some(mag);
606                    }
607                }
608                0x1C => {
609                    // ANGLE
610                    let ang = Self::parse_real8(&data)?;
611                    if let Some(ref mut st) = strans {
612                        st.angle = Some(ang);
613                    }
614                }
615                0x21 => {
616                    // PATHTYPE
617                    pathtype = Some(Self::parse_i16(&data)?);
618                }
619                0x26 => {
620                    // ELFLAGS - Element flags
621                    elflags = Some(Self::parse_i16(&data)?);
622                }
623                0x2A => {
624                    // NODETYPE
625                    nodetype = Some(Self::parse_i16(&data)?);
626                }
627                0x2B => {
628                    // PROPATTR - Property attribute number
629                    current_prop_attr = Some(Self::parse_i16(&data)?);
630                }
631                0x2C => {
632                    // PROPVALUE - Property value string
633                    if let Some(attr) = current_prop_attr.take() {
634                        let value = Self::parse_string(&data)?;
635                        properties.push(GDSProperty {
636                            attribute: attr,
637                            value,
638                        });
639                    }
640                }
641                0x2E => {
642                    // BOXTYPE
643                    boxtype = Some(Self::parse_i16(&data)?);
644                }
645                0x2F => {
646                    // PLEX - Plex identifier
647                    plex = Some(Self::parse_i32(&data)?);
648                }
649                0x30 => {
650                    // BGNEXTN - Path extension at beginning
651                    bgnextn = Some(Self::parse_i32(&data)?);
652                }
653                0x31 => {
654                    // ENDEXTN - Path extension at end
655                    endextn = Some(Self::parse_i32(&data)?);
656                }
657                _ => {
658                    // Skip unknown record types
659                }
660            }
661        }
662
663        Ok(gds)
664    }
665
666    /// Parse GDSII element records from a structure body (records between STRNAME and ENDSTR).
667    pub fn parse_element_records(
668        body: &[u8],
669    ) -> Result<Vec<GDSElement>, Box<dyn std::error::Error>> {
670        let mut full = Self::streaming_wrap_prefix();
671        full.extend_from_slice(body);
672        full.extend_from_slice(&[0x00, 0x04, 0x07, 0x02]); // ENDSTR
673        full.extend_from_slice(&[0x00, 0x04, 0x04, 0x02]); // ENDLIB
674        let gds = Self::read_from_reader(&mut std::io::Cursor::new(full))?;
675        Ok(gds
676            .structures
677            .into_iter()
678            .next()
679            .map(|s| s.elements)
680            .unwrap_or_default())
681    }
682
683    fn streaming_wrap_prefix() -> Vec<u8> {
684        use std::sync::OnceLock;
685        static PREFIX: OnceLock<Vec<u8>> = OnceLock::new();
686        PREFIX
687            .get_or_init(|| {
688                let mut gds = GDSIIFile::new("STREAM".to_string());
689                gds.units = (1e-6, 1e-9);
690                gds.structures.push(GDSStructure {
691                    name: "CELL".to_string(),
692                    creation_time: GDSTime::now(),
693                    modification_time: GDSTime::now(),
694                    strclass: None,
695                    elements: Vec::new(),
696                });
697                let mut buf = Vec::new();
698                gds.write_to_writer(&mut buf).expect("streaming prefix");
699                let mut i = 0usize;
700                while i + 4 <= buf.len() {
701                    if buf[i + 2] == 0x07 {
702                        return buf[..i].to_vec();
703                    }
704                    let len = u16::from_be_bytes([buf[i], buf[i + 1]]) as usize;
705                    i += len.max(4);
706                }
707                buf
708            })
709            .clone()
710    }
711
712    /// Write GDSII to file
713    pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), Box<dyn std::error::Error>> {
714        let file = File::create(path)?;
715        let mut writer = BufWriter::new(file);
716        self.write_to_writer(&mut writer)
717    }
718
719    /// Write GDSII to any writer
720    pub fn write_to_writer<W: Write>(
721        &self,
722        writer: &mut W,
723    ) -> Result<(), Box<dyn std::error::Error>> {
724        // HEADER
725        Self::write_record(
726            writer,
727            0x00,
728            DataType::TwoByteSignedInt,
729            &self.version.to_be_bytes(),
730        )?;
731
732        // BGNLIB
733        let time_data = Self::format_times(&self.modification_time, &self.access_time);
734        Self::write_record(writer, 0x01, DataType::TwoByteSignedInt, &time_data)?;
735
736        // LIBNAME
737        Self::write_record(
738            writer,
739            0x02,
740            DataType::AsciiString,
741            self.library_name.as_bytes(),
742        )?;
743
744        // UNITS (gdstk encoding)
745        let units_data = Self::format_units(self.units.0, self.units.1);
746        Self::write_record(writer, 0x03, DataType::EightByteReal, &units_data)?;
747
748        // REFLIBS - Referenced libraries
749        for reflib in &self.reflibs {
750            Self::write_record(writer, 0x1F, DataType::AsciiString, reflib.as_bytes())?;
751        }
752
753        // FONTS - Font table
754        if !self.fonts.is_empty() {
755            let mut font_data = Vec::new();
756            for font in &self.fonts {
757                let mut font_bytes = font.as_bytes().to_vec();
758                font_bytes.resize(44, 0); // Each font name is 44 bytes
759                font_data.extend_from_slice(&font_bytes);
760            }
761            Self::write_record(writer, 0x29, DataType::AsciiString, &font_data)?;
762        }
763
764        // GENERATIONS - Backup generations
765        if let Some(generations) = self.generations {
766            Self::write_record(
767                writer,
768                0x3C,
769                DataType::TwoByteSignedInt,
770                &generations.to_be_bytes(),
771            )?;
772        }
773
774        // ATTRTABLE - Attribute table reference
775        if let Some(ref attrtable) = self.attrtable {
776            Self::write_record(writer, 0x3D, DataType::AsciiString, attrtable.as_bytes())?;
777        }
778
779        // Write structures
780        for structure in &self.structures {
781            structure.write(writer)?;
782        }
783
784        // ENDLIB
785        Self::write_record(writer, 0x04, DataType::NoData, &[])?;
786
787        Ok(())
788    }
789
790    // Helper functions for reading records
791    fn read_record(
792        buffer: &[u8],
793        cursor: &mut usize,
794    ) -> Result<(u8, DataType, Vec<u8>), Box<dyn std::error::Error>> {
795        if *cursor + 4 > buffer.len() {
796            return Err("Incomplete record header".into());
797        }
798
799        let length = u16::from_be_bytes([buffer[*cursor], buffer[*cursor + 1]]) as usize;
800        let record_type = buffer[*cursor + 2];
801        let data_type_byte = buffer[*cursor + 3];
802
803        let data_type = match data_type_byte {
804            0 => DataType::NoData,
805            1 => DataType::BitArray,
806            2 => DataType::TwoByteSignedInt,
807            3 => DataType::FourByteSignedInt,
808            4 => DataType::FourByteReal,
809            5 => DataType::EightByteReal,
810            6 => DataType::AsciiString,
811            _ => return Err(format!("Unknown data type: {}", data_type_byte).into()),
812        };
813
814        *cursor += 4;
815
816        let data_length = length.saturating_sub(4);
817        if *cursor + data_length > buffer.len() {
818            return Err("Incomplete record data".into());
819        }
820
821        let data = buffer[*cursor..*cursor + data_length].to_vec();
822        *cursor += data_length;
823
824        Ok((record_type, data_type, data))
825    }
826
827    fn write_record<W: Write>(
828        writer: &mut W,
829        record_type: u8,
830        data_type: DataType,
831        data: &[u8],
832    ) -> Result<(), Box<dyn std::error::Error>> {
833        let length = (4 + data.len()) as u16;
834        writer.write_all(&length.to_be_bytes())?;
835        writer.write_all(&[record_type, data_type as u8])?;
836        writer.write_all(data)?;
837        Ok(())
838    }
839
840    fn write_properties<W: Write>(
841        writer: &mut W,
842        properties: &[GDSProperty],
843    ) -> Result<(), Box<dyn std::error::Error>> {
844        for prop in properties {
845            // PROPATTR
846            Self::write_record(
847                writer,
848                0x2B,
849                DataType::TwoByteSignedInt,
850                &prop.attribute.to_be_bytes(),
851            )?;
852            // PROPVALUE
853            Self::write_record(writer, 0x2C, DataType::AsciiString, prop.value.as_bytes())?;
854        }
855        Ok(())
856    }
857
858    fn write_elflags_plex<W: Write>(
859        writer: &mut W,
860        elflags: Option<i16>,
861        plex: Option<i32>,
862    ) -> Result<(), Box<dyn std::error::Error>> {
863        // ELFLAGS (0x26) must come before PLEX (0x2F)
864        if let Some(flags) = elflags {
865            Self::write_record(
866                writer,
867                0x26,
868                DataType::TwoByteSignedInt,
869                &flags.to_be_bytes(),
870            )?;
871        }
872        if let Some(p) = plex {
873            Self::write_record(writer, 0x2F, DataType::FourByteSignedInt, &p.to_be_bytes())?;
874        }
875        Ok(())
876    }
877
878    // Parsing helpers
879    fn parse_i16(data: &[u8]) -> Result<i16, Box<dyn std::error::Error>> {
880        if data.len() < 2 {
881            return Err("Insufficient data for i16".into());
882        }
883        Ok(i16::from_be_bytes([data[0], data[1]]))
884    }
885
886    fn parse_i32(data: &[u8]) -> Result<i32, Box<dyn std::error::Error>> {
887        if data.len() < 4 {
888            return Err("Insufficient data for i32".into());
889        }
890        Ok(i32::from_be_bytes([data[0], data[1], data[2], data[3]]))
891    }
892
893    fn parse_string(data: &[u8]) -> Result<String, Box<dyn std::error::Error>> {
894        // GDSII strings are null-terminated or padded
895        let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
896        // Use from_utf8_lossy to handle non-UTF8 strings gracefully
897        // GDSII spec uses ASCII, but some tools may write non-UTF8 data
898        Ok(String::from_utf8_lossy(&data[..end]).into_owned())
899    }
900
901    /// Decode GDSII 8-byte real (gdstk `gdsii_real_to_double`).
902    fn parse_real8(data: &[u8]) -> Result<f64, Box<dyn std::error::Error>> {
903        if data.len() < 8 {
904            return Err("Insufficient data for real8".into());
905        }
906        let bits = u64::from_be_bytes([
907            data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
908        ]);
909        Ok(Self::real8_to_double(bits))
910    }
911
912    /// Encode GDSII 8-byte real (gdstk `gdsii_real_from_double`).
913    fn format_real8(value: f64) -> [u8; 8] {
914        Self::real8_from_double(value).to_be_bytes()
915    }
916
917    fn real8_to_double(real: u64) -> f64 {
918        let exponent = ((real & 0x7F00000000000000) >> 54) as i64 - 256;
919        let mantissa = (real & 0x00FFFFFFFFFFFFFF) as f64 / 72057594037927936.0;
920        let result = mantissa * 2f64.powf(exponent as f64);
921        if real & 0x8000000000000000 != 0 {
922            -result
923        } else {
924            result
925        }
926    }
927
928    fn real8_from_double(value: f64) -> u64 {
929        if value == 0.0 {
930            return 0;
931        }
932        let mut sign_byte = 0u8;
933        let mut v = value;
934        if v < 0.0 {
935            sign_byte = 0x80;
936            v = -v;
937        }
938        let fexp = 0.25 * v.log2();
939        let mut exponent = fexp.ceil();
940        if exponent == fexp {
941            exponent += 1.0;
942        }
943        let mantissa = (v * 16f64.powf(14.0 - exponent)) as u64;
944        sign_byte = sign_byte.wrapping_add((64.0 + exponent) as u8);
945        ((sign_byte as u64) << 56) | (mantissa & 0x00FFFFFFFFFFFFFF)
946    }
947
948    fn parse_time(data: &[u8]) -> Result<(GDSTime, GDSTime), Box<dyn std::error::Error>> {
949        if data.len() < 24 {
950            return Err("Insufficient data for time".into());
951        }
952
953        let mod_time = GDSTime {
954            year: i16::from_be_bytes([data[0], data[1]]) as u16,
955            month: i16::from_be_bytes([data[2], data[3]]) as u16,
956            day: i16::from_be_bytes([data[4], data[5]]) as u16,
957            hour: i16::from_be_bytes([data[6], data[7]]) as u16,
958            minute: i16::from_be_bytes([data[8], data[9]]) as u16,
959            second: i16::from_be_bytes([data[10], data[11]]) as u16,
960        };
961
962        let acc_time = GDSTime {
963            year: i16::from_be_bytes([data[12], data[13]]) as u16,
964            month: i16::from_be_bytes([data[14], data[15]]) as u16,
965            day: i16::from_be_bytes([data[16], data[17]]) as u16,
966            hour: i16::from_be_bytes([data[18], data[19]]) as u16,
967            minute: i16::from_be_bytes([data[20], data[21]]) as u16,
968            second: i16::from_be_bytes([data[22], data[23]]) as u16,
969        };
970
971        Ok((mod_time, acc_time))
972    }
973
974    fn format_times(mod_time: &GDSTime, acc_time: &GDSTime) -> Vec<u8> {
975        let mut data = Vec::new();
976        data.extend_from_slice(&(mod_time.year as i16).to_be_bytes());
977        data.extend_from_slice(&(mod_time.month as i16).to_be_bytes());
978        data.extend_from_slice(&(mod_time.day as i16).to_be_bytes());
979        data.extend_from_slice(&(mod_time.hour as i16).to_be_bytes());
980        data.extend_from_slice(&(mod_time.minute as i16).to_be_bytes());
981        data.extend_from_slice(&(mod_time.second as i16).to_be_bytes());
982        data.extend_from_slice(&(acc_time.year as i16).to_be_bytes());
983        data.extend_from_slice(&(acc_time.month as i16).to_be_bytes());
984        data.extend_from_slice(&(acc_time.day as i16).to_be_bytes());
985        data.extend_from_slice(&(acc_time.hour as i16).to_be_bytes());
986        data.extend_from_slice(&(acc_time.minute as i16).to_be_bytes());
987        data.extend_from_slice(&(acc_time.second as i16).to_be_bytes());
988        data
989    }
990
991    fn parse_xy(data: &[u8]) -> Result<Vec<(i32, i32)>, Box<dyn std::error::Error>> {
992        #[allow(unknown_lints, clippy::manual_is_multiple_of)]
993        if data.len() % 8 != 0 {
994            return Err("Invalid XY data length".into());
995        }
996
997        let mut points = Vec::new();
998        for i in (0..data.len()).step_by(8) {
999            let x = i32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]);
1000            let y = i32::from_be_bytes([data[i + 4], data[i + 5], data[i + 6], data[i + 7]]);
1001            points.push((x, y));
1002        }
1003
1004        Ok(points)
1005    }
1006
1007    /// Parse GDSII UNITS record (gdstk-compatible).
1008    ///
1009    /// On disk: `(precision / user_unit, precision)` in meters — see gdstk `Library::write_gds`.
1010    /// Returns `(user_unit_meters, database_unit_meters)`.
1011    pub(crate) fn parse_units(data: &[u8]) -> Result<(f64, f64), Box<dyn std::error::Error>> {
1012        if data.len() < 16 {
1013            return Err("Insufficient data for units".into());
1014        }
1015
1016        let db_in_user = Self::parse_real8(&data[0..8])?;
1017        let db_in_meters = Self::parse_real8(&data[8..16])?;
1018        if db_in_user == 0.0 {
1019            return Err("Invalid UNITS: zero user-unit ratio".into());
1020        }
1021        let user_units = db_in_meters / db_in_user;
1022        Ok((user_units, db_in_meters))
1023    }
1024
1025    /// Write GDSII UNITS record from `(user_unit_meters, database_unit_meters)`.
1026    fn format_units(user_unit: f64, db_unit: f64) -> [u8; 16] {
1027        let ratio = if user_unit > 0.0 {
1028            db_unit / user_unit
1029        } else {
1030            db_unit
1031        };
1032        let mut out = [0u8; 16];
1033        out[0..8].copy_from_slice(&Self::format_real8(ratio));
1034        out[8..16].copy_from_slice(&Self::format_real8(db_unit));
1035        out
1036    }
1037}
1038
1039impl GDSTime {
1040    /// Creates a timestamp with the current date and time.
1041    ///
1042    /// # Examples
1043    ///
1044    /// ```
1045    /// use laykit::GDSTime;
1046    ///
1047    /// let time = GDSTime::now();
1048    /// assert!(time.year >= 2024);
1049    /// assert!(time.month >= 1 && time.month <= 12);
1050    /// ```
1051    pub fn now() -> Self {
1052        // Simple default time
1053        GDSTime {
1054            year: 2025,
1055            month: 1,
1056            day: 1,
1057            hour: 0,
1058            minute: 0,
1059            second: 0,
1060        }
1061    }
1062}
1063
1064impl GDSStructure {
1065    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1066        // BGNSTR
1067        let time_data = GDSIIFile::format_times(&self.creation_time, &self.modification_time);
1068        GDSIIFile::write_record(writer, 0x05, DataType::TwoByteSignedInt, &time_data)?;
1069
1070        // STRNAME
1071        GDSIIFile::write_record(writer, 0x06, DataType::AsciiString, self.name.as_bytes())?;
1072
1073        // STRCLASS - Structure class
1074        if let Some(strclass) = self.strclass {
1075            GDSIIFile::write_record(
1076                writer,
1077                0x34,
1078                DataType::TwoByteSignedInt,
1079                &strclass.to_be_bytes(),
1080            )?;
1081        }
1082
1083        // Write elements
1084        for element in &self.elements {
1085            element.write(writer)?;
1086        }
1087
1088        // ENDSTR
1089        GDSIIFile::write_record(writer, 0x07, DataType::NoData, &[])?;
1090
1091        Ok(())
1092    }
1093}
1094
1095impl GDSElement {
1096    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1097        match self {
1098            GDSElement::Boundary(b) => b.write(writer),
1099            GDSElement::Path(p) => p.write(writer),
1100            GDSElement::StructRef(s) => s.write(writer),
1101            GDSElement::ArrayRef(a) => a.write(writer),
1102            GDSElement::Text(t) => t.write(writer),
1103            GDSElement::Node(n) => n.write(writer),
1104            GDSElement::Box(b) => b.write(writer),
1105        }
1106    }
1107}
1108
1109impl Boundary {
1110    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1111        // BOUNDARY
1112        GDSIIFile::write_record(writer, 0x08, DataType::NoData, &[])?;
1113
1114        // ELFLAGS and PLEX (must come before other element data)
1115        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1116
1117        // LAYER
1118        GDSIIFile::write_record(
1119            writer,
1120            0x0D,
1121            DataType::TwoByteSignedInt,
1122            &self.layer.to_be_bytes(),
1123        )?;
1124
1125        // DATATYPE
1126        GDSIIFile::write_record(
1127            writer,
1128            0x0E,
1129            DataType::TwoByteSignedInt,
1130            &self.datatype.to_be_bytes(),
1131        )?;
1132
1133        // XY
1134        let mut xy_data = Vec::new();
1135        for (x, y) in &self.xy {
1136            xy_data.extend_from_slice(&x.to_be_bytes());
1137            xy_data.extend_from_slice(&y.to_be_bytes());
1138        }
1139        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1140
1141        // Properties
1142        GDSIIFile::write_properties(writer, &self.properties)?;
1143
1144        // ENDEL
1145        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1146
1147        Ok(())
1148    }
1149}
1150
1151impl GPath {
1152    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1153        // PATH
1154        GDSIIFile::write_record(writer, 0x09, DataType::NoData, &[])?;
1155
1156        // ELFLAGS and PLEX
1157        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1158
1159        // LAYER
1160        GDSIIFile::write_record(
1161            writer,
1162            0x0D,
1163            DataType::TwoByteSignedInt,
1164            &self.layer.to_be_bytes(),
1165        )?;
1166
1167        // DATATYPE
1168        GDSIIFile::write_record(
1169            writer,
1170            0x0E,
1171            DataType::TwoByteSignedInt,
1172            &self.datatype.to_be_bytes(),
1173        )?;
1174
1175        // PATHTYPE
1176        GDSIIFile::write_record(
1177            writer,
1178            0x21,
1179            DataType::TwoByteSignedInt,
1180            &self.pathtype.to_be_bytes(),
1181        )?;
1182
1183        // WIDTH
1184        if let Some(w) = self.width {
1185            GDSIIFile::write_record(writer, 0x0F, DataType::FourByteSignedInt, &w.to_be_bytes())?;
1186        }
1187
1188        // BGNEXTN
1189        if let Some(bgn) = self.bgnextn {
1190            GDSIIFile::write_record(
1191                writer,
1192                0x30,
1193                DataType::FourByteSignedInt,
1194                &bgn.to_be_bytes(),
1195            )?;
1196        }
1197
1198        // ENDEXTN
1199        if let Some(end) = self.endextn {
1200            GDSIIFile::write_record(
1201                writer,
1202                0x31,
1203                DataType::FourByteSignedInt,
1204                &end.to_be_bytes(),
1205            )?;
1206        }
1207
1208        // XY
1209        let mut xy_data = Vec::new();
1210        for (x, y) in &self.xy {
1211            xy_data.extend_from_slice(&x.to_be_bytes());
1212            xy_data.extend_from_slice(&y.to_be_bytes());
1213        }
1214        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1215
1216        // Properties
1217        GDSIIFile::write_properties(writer, &self.properties)?;
1218
1219        // ENDEL
1220        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1221
1222        Ok(())
1223    }
1224}
1225
1226impl StructRef {
1227    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1228        // SREF
1229        GDSIIFile::write_record(writer, 0x0A, DataType::NoData, &[])?;
1230
1231        // ELFLAGS and PLEX
1232        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1233
1234        // SNAME
1235        GDSIIFile::write_record(writer, 0x12, DataType::AsciiString, self.sname.as_bytes())?;
1236
1237        // STRANS
1238        if let Some(ref st) = self.strans {
1239            st.write(writer)?;
1240        }
1241
1242        // XY
1243        let mut xy_data = Vec::new();
1244        xy_data.extend_from_slice(&self.xy.0.to_be_bytes());
1245        xy_data.extend_from_slice(&self.xy.1.to_be_bytes());
1246        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1247
1248        // Properties
1249        GDSIIFile::write_properties(writer, &self.properties)?;
1250
1251        // ENDEL
1252        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1253
1254        Ok(())
1255    }
1256}
1257
1258impl ArrayRef {
1259    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1260        // AREF
1261        GDSIIFile::write_record(writer, 0x0B, DataType::NoData, &[])?;
1262
1263        // ELFLAGS and PLEX
1264        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1265
1266        // SNAME
1267        GDSIIFile::write_record(writer, 0x12, DataType::AsciiString, self.sname.as_bytes())?;
1268
1269        // STRANS
1270        if let Some(ref st) = self.strans {
1271            st.write(writer)?;
1272        }
1273
1274        // COLROW
1275        let mut colrow_data = Vec::new();
1276        colrow_data.extend_from_slice(&(self.columns as i16).to_be_bytes());
1277        colrow_data.extend_from_slice(&(self.rows as i16).to_be_bytes());
1278        GDSIIFile::write_record(writer, 0x13, DataType::TwoByteSignedInt, &colrow_data)?;
1279
1280        // XY (3 points)
1281        let mut xy_data = Vec::new();
1282        for (x, y) in &self.xy {
1283            xy_data.extend_from_slice(&x.to_be_bytes());
1284            xy_data.extend_from_slice(&y.to_be_bytes());
1285        }
1286        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1287
1288        // Properties
1289        GDSIIFile::write_properties(writer, &self.properties)?;
1290
1291        // ENDEL
1292        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1293
1294        Ok(())
1295    }
1296}
1297
1298impl GText {
1299    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1300        // TEXT
1301        GDSIIFile::write_record(writer, 0x0C, DataType::NoData, &[])?;
1302
1303        // ELFLAGS and PLEX
1304        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1305
1306        // LAYER
1307        GDSIIFile::write_record(
1308            writer,
1309            0x0D,
1310            DataType::TwoByteSignedInt,
1311            &self.layer.to_be_bytes(),
1312        )?;
1313
1314        // TEXTTYPE
1315        GDSIIFile::write_record(
1316            writer,
1317            0x16,
1318            DataType::TwoByteSignedInt,
1319            &self.texttype.to_be_bytes(),
1320        )?;
1321
1322        // PRESENTATION
1323        if let Some(p) = self.presentation {
1324            GDSIIFile::write_record(writer, 0x17, DataType::TwoByteSignedInt, &p.to_be_bytes())?;
1325        }
1326
1327        // STRANS
1328        if let Some(ref st) = self.strans {
1329            st.write(writer)?;
1330        }
1331
1332        // XY
1333        let mut xy_data = Vec::new();
1334        xy_data.extend_from_slice(&self.xy.0.to_be_bytes());
1335        xy_data.extend_from_slice(&self.xy.1.to_be_bytes());
1336        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1337
1338        // STRING
1339        GDSIIFile::write_record(writer, 0x19, DataType::AsciiString, self.string.as_bytes())?;
1340
1341        // Properties
1342        GDSIIFile::write_properties(writer, &self.properties)?;
1343
1344        // ENDEL
1345        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1346
1347        Ok(())
1348    }
1349}
1350
1351impl Node {
1352    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1353        // NODE
1354        GDSIIFile::write_record(writer, 0x15, DataType::NoData, &[])?;
1355
1356        // ELFLAGS and PLEX
1357        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1358
1359        // LAYER
1360        GDSIIFile::write_record(
1361            writer,
1362            0x0D,
1363            DataType::TwoByteSignedInt,
1364            &self.layer.to_be_bytes(),
1365        )?;
1366
1367        // NODETYPE
1368        GDSIIFile::write_record(
1369            writer,
1370            0x2A,
1371            DataType::TwoByteSignedInt,
1372            &self.nodetype.to_be_bytes(),
1373        )?;
1374
1375        // XY
1376        let mut xy_data = Vec::new();
1377        for (x, y) in &self.xy {
1378            xy_data.extend_from_slice(&x.to_be_bytes());
1379            xy_data.extend_from_slice(&y.to_be_bytes());
1380        }
1381        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1382
1383        // Properties
1384        GDSIIFile::write_properties(writer, &self.properties)?;
1385
1386        // ENDEL
1387        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1388
1389        Ok(())
1390    }
1391}
1392
1393impl GDSBox {
1394    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1395        // BOX
1396        GDSIIFile::write_record(writer, 0x2D, DataType::NoData, &[])?;
1397
1398        // ELFLAGS and PLEX
1399        GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1400
1401        // LAYER
1402        GDSIIFile::write_record(
1403            writer,
1404            0x0D,
1405            DataType::TwoByteSignedInt,
1406            &self.layer.to_be_bytes(),
1407        )?;
1408
1409        // BOXTYPE
1410        GDSIIFile::write_record(
1411            writer,
1412            0x2E,
1413            DataType::TwoByteSignedInt,
1414            &self.boxtype.to_be_bytes(),
1415        )?;
1416
1417        // XY
1418        let mut xy_data = Vec::new();
1419        for (x, y) in &self.xy {
1420            xy_data.extend_from_slice(&x.to_be_bytes());
1421            xy_data.extend_from_slice(&y.to_be_bytes());
1422        }
1423        GDSIIFile::write_record(writer, 0x10, DataType::FourByteSignedInt, &xy_data)?;
1424
1425        // Properties
1426        GDSIIFile::write_properties(writer, &self.properties)?;
1427
1428        // ENDEL
1429        GDSIIFile::write_record(writer, 0x11, DataType::NoData, &[])?;
1430
1431        Ok(())
1432    }
1433}
1434
1435impl STrans {
1436    fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {
1437        // STRANS
1438        let mut flags: i16 = 0;
1439        if self.reflection {
1440            flags |= -0x8000_i16;
1441        }
1442        if self.absolute_magnification {
1443            flags |= 0x0004;
1444        }
1445        if self.absolute_angle {
1446            flags |= 0x0002;
1447        }
1448        GDSIIFile::write_record(
1449            writer,
1450            0x1A,
1451            DataType::TwoByteSignedInt,
1452            &flags.to_be_bytes(),
1453        )?;
1454
1455        // MAG
1456        if let Some(mag) = self.magnification {
1457            GDSIIFile::write_record(
1458                writer,
1459                0x1B,
1460                DataType::EightByteReal,
1461                &GDSIIFile::format_real8(mag),
1462            )?;
1463        }
1464
1465        // ANGLE
1466        if let Some(angle) = self.angle {
1467            GDSIIFile::write_record(
1468                writer,
1469                0x1C,
1470                DataType::EightByteReal,
1471                &GDSIIFile::format_real8(angle),
1472            )?;
1473        }
1474
1475        Ok(())
1476    }
1477}