1use std::fs::File;
6use std::io::{BufReader, BufWriter, Read, Write};
7use std::path::Path;
8
9#[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), pub reflibs: Vec<String>, pub fonts: Vec<String>, pub generations: Option<i16>, pub attrtable: Option<String>, 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>, 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>, pub plex: Option<i32>, 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>, pub endextn: Option<i32>, pub xy: Vec<(i32, i32)>,
73 pub elflags: Option<i16>, pub plex: Option<i32>, 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>, pub plex: Option<i32>, 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)>, pub strans: Option<STrans>,
95 pub elflags: Option<i16>, pub plex: Option<i32>, 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>, pub plex: Option<i32>, 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>, pub plex: Option<i32>, 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>, pub plex: Option<i32>, 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#[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#[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 pub fn new(library_name: String) -> Self {
191 let now = GDSTime::now();
192 GDSIIFile {
193 version: 600, modification_time: now.clone(),
195 access_time: now,
196 library_name,
197 units: (1e-6, 1e-9), reflibs: Vec::new(),
199 fonts: Vec::new(),
200 generations: None,
201 attrtable: None,
202 structures: Vec::new(),
203 }
204 }
205
206 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 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 #[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 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 gds.version = Self::parse_i16(&data)? as u16;
264 }
265 0x01 => {
266 let times = Self::parse_time(&data)?;
268 gds.modification_time = times.0;
269 gds.access_time = times.1;
270 }
271 0x02 => {
272 gds.library_name = Self::parse_string(&data)?;
274 }
275 0x03 => {
276 gds.units = Self::parse_units(&data)?;
278 }
279 0x1F => {
280 let reflib = Self::parse_string(&data)?;
282 gds.reflibs.push(reflib);
283 }
284 0x29 => {
285 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 gds.generations = Some(Self::parse_i16(&data)?);
298 }
299 0x3D => {
300 gds.attrtable = Some(Self::parse_string(&data)?);
302 }
303 0x04 => {
304 break;
306 }
307 0x05 => {
308 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 if let Some(ref mut structure) = current_structure {
321 structure.name = Self::parse_string(&data)?;
322 }
323 }
324 0x34 => {
325 if let Some(ref mut structure) = current_structure {
327 structure.strclass = Some(Self::parse_i16(&data)?);
328 }
329 }
330 0x07 => {
331 if let Some(structure) = current_structure.take() {
333 gds.structures.push(structure);
334 }
335 }
336 0x08 => {
337 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 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 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 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 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 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 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 = Some(Self::parse_i16(&data)?);
418 }
419 0x0E => {
420 datatype = Some(Self::parse_i16(&data)?);
422 }
423 0x0F => {
424 width = Some(Self::parse_i32(&data)?);
426 }
427 0x10 => {
428 xy = Self::parse_xy(&data)?;
430 }
431 0x11 => {
432 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 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 = Some(Self::parse_string(&data)?);
571 }
572 0x13 => {
573 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 = Some(Self::parse_i16(&data)?);
581 }
582 0x17 => {
583 presentation = Some(Self::parse_i16(&data)?);
585 }
586 0x19 => {
587 text_string = Some(Self::parse_string(&data)?);
589 }
590 0x1A => {
591 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 let mag = Self::parse_real8(&data)?;
604 if let Some(ref mut st) = strans {
605 st.magnification = Some(mag);
606 }
607 }
608 0x1C => {
609 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 = Some(Self::parse_i16(&data)?);
618 }
619 0x26 => {
620 elflags = Some(Self::parse_i16(&data)?);
622 }
623 0x2A => {
624 nodetype = Some(Self::parse_i16(&data)?);
626 }
627 0x2B => {
628 current_prop_attr = Some(Self::parse_i16(&data)?);
630 }
631 0x2C => {
632 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 = Some(Self::parse_i16(&data)?);
644 }
645 0x2F => {
646 plex = Some(Self::parse_i32(&data)?);
648 }
649 0x30 => {
650 bgnextn = Some(Self::parse_i32(&data)?);
652 }
653 0x31 => {
654 endextn = Some(Self::parse_i32(&data)?);
656 }
657 _ => {
658 }
660 }
661 }
662
663 Ok(gds)
664 }
665
666 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]); full.extend_from_slice(&[0x00, 0x04, 0x04, 0x02]); 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 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 pub fn write_to_writer<W: Write>(
721 &self,
722 writer: &mut W,
723 ) -> Result<(), Box<dyn std::error::Error>> {
724 Self::write_record(
726 writer,
727 0x00,
728 DataType::TwoByteSignedInt,
729 &self.version.to_be_bytes(),
730 )?;
731
732 let time_data = Self::format_times(&self.modification_time, &self.access_time);
734 Self::write_record(writer, 0x01, DataType::TwoByteSignedInt, &time_data)?;
735
736 Self::write_record(
738 writer,
739 0x02,
740 DataType::AsciiString,
741 self.library_name.as_bytes(),
742 )?;
743
744 let units_data = Self::format_units(self.units.0, self.units.1);
746 Self::write_record(writer, 0x03, DataType::EightByteReal, &units_data)?;
747
748 for reflib in &self.reflibs {
750 Self::write_record(writer, 0x1F, DataType::AsciiString, reflib.as_bytes())?;
751 }
752
753 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); font_data.extend_from_slice(&font_bytes);
760 }
761 Self::write_record(writer, 0x29, DataType::AsciiString, &font_data)?;
762 }
763
764 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 if let Some(ref attrtable) = self.attrtable {
776 Self::write_record(writer, 0x3D, DataType::AsciiString, attrtable.as_bytes())?;
777 }
778
779 for structure in &self.structures {
781 structure.write(writer)?;
782 }
783
784 Self::write_record(writer, 0x04, DataType::NoData, &[])?;
786
787 Ok(())
788 }
789
790 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 Self::write_record(
847 writer,
848 0x2B,
849 DataType::TwoByteSignedInt,
850 &prop.attribute.to_be_bytes(),
851 )?;
852 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 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 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 let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
896 Ok(String::from_utf8_lossy(&data[..end]).into_owned())
899 }
900
901 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 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 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 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 pub fn now() -> Self {
1052 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 let time_data = GDSIIFile::format_times(&self.creation_time, &self.modification_time);
1068 GDSIIFile::write_record(writer, 0x05, DataType::TwoByteSignedInt, &time_data)?;
1069
1070 GDSIIFile::write_record(writer, 0x06, DataType::AsciiString, self.name.as_bytes())?;
1072
1073 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 for element in &self.elements {
1085 element.write(writer)?;
1086 }
1087
1088 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 GDSIIFile::write_record(writer, 0x08, DataType::NoData, &[])?;
1113
1114 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1116
1117 GDSIIFile::write_record(
1119 writer,
1120 0x0D,
1121 DataType::TwoByteSignedInt,
1122 &self.layer.to_be_bytes(),
1123 )?;
1124
1125 GDSIIFile::write_record(
1127 writer,
1128 0x0E,
1129 DataType::TwoByteSignedInt,
1130 &self.datatype.to_be_bytes(),
1131 )?;
1132
1133 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 GDSIIFile::write_properties(writer, &self.properties)?;
1143
1144 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 GDSIIFile::write_record(writer, 0x09, DataType::NoData, &[])?;
1155
1156 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1158
1159 GDSIIFile::write_record(
1161 writer,
1162 0x0D,
1163 DataType::TwoByteSignedInt,
1164 &self.layer.to_be_bytes(),
1165 )?;
1166
1167 GDSIIFile::write_record(
1169 writer,
1170 0x0E,
1171 DataType::TwoByteSignedInt,
1172 &self.datatype.to_be_bytes(),
1173 )?;
1174
1175 GDSIIFile::write_record(
1177 writer,
1178 0x21,
1179 DataType::TwoByteSignedInt,
1180 &self.pathtype.to_be_bytes(),
1181 )?;
1182
1183 if let Some(w) = self.width {
1185 GDSIIFile::write_record(writer, 0x0F, DataType::FourByteSignedInt, &w.to_be_bytes())?;
1186 }
1187
1188 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 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 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 GDSIIFile::write_properties(writer, &self.properties)?;
1218
1219 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 GDSIIFile::write_record(writer, 0x0A, DataType::NoData, &[])?;
1230
1231 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1233
1234 GDSIIFile::write_record(writer, 0x12, DataType::AsciiString, self.sname.as_bytes())?;
1236
1237 if let Some(ref st) = self.strans {
1239 st.write(writer)?;
1240 }
1241
1242 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 GDSIIFile::write_properties(writer, &self.properties)?;
1250
1251 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 GDSIIFile::write_record(writer, 0x0B, DataType::NoData, &[])?;
1262
1263 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1265
1266 GDSIIFile::write_record(writer, 0x12, DataType::AsciiString, self.sname.as_bytes())?;
1268
1269 if let Some(ref st) = self.strans {
1271 st.write(writer)?;
1272 }
1273
1274 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 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 GDSIIFile::write_properties(writer, &self.properties)?;
1290
1291 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 GDSIIFile::write_record(writer, 0x0C, DataType::NoData, &[])?;
1302
1303 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1305
1306 GDSIIFile::write_record(
1308 writer,
1309 0x0D,
1310 DataType::TwoByteSignedInt,
1311 &self.layer.to_be_bytes(),
1312 )?;
1313
1314 GDSIIFile::write_record(
1316 writer,
1317 0x16,
1318 DataType::TwoByteSignedInt,
1319 &self.texttype.to_be_bytes(),
1320 )?;
1321
1322 if let Some(p) = self.presentation {
1324 GDSIIFile::write_record(writer, 0x17, DataType::TwoByteSignedInt, &p.to_be_bytes())?;
1325 }
1326
1327 if let Some(ref st) = self.strans {
1329 st.write(writer)?;
1330 }
1331
1332 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 GDSIIFile::write_record(writer, 0x19, DataType::AsciiString, self.string.as_bytes())?;
1340
1341 GDSIIFile::write_properties(writer, &self.properties)?;
1343
1344 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 GDSIIFile::write_record(writer, 0x15, DataType::NoData, &[])?;
1355
1356 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1358
1359 GDSIIFile::write_record(
1361 writer,
1362 0x0D,
1363 DataType::TwoByteSignedInt,
1364 &self.layer.to_be_bytes(),
1365 )?;
1366
1367 GDSIIFile::write_record(
1369 writer,
1370 0x2A,
1371 DataType::TwoByteSignedInt,
1372 &self.nodetype.to_be_bytes(),
1373 )?;
1374
1375 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 GDSIIFile::write_properties(writer, &self.properties)?;
1385
1386 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 GDSIIFile::write_record(writer, 0x2D, DataType::NoData, &[])?;
1397
1398 GDSIIFile::write_elflags_plex(writer, self.elflags, self.plex)?;
1400
1401 GDSIIFile::write_record(
1403 writer,
1404 0x0D,
1405 DataType::TwoByteSignedInt,
1406 &self.layer.to_be_bytes(),
1407 )?;
1408
1409 GDSIIFile::write_record(
1411 writer,
1412 0x2E,
1413 DataType::TwoByteSignedInt,
1414 &self.boxtype.to_be_bytes(),
1415 )?;
1416
1417 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 GDSIIFile::write_properties(writer, &self.properties)?;
1427
1428 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 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 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 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}