layouttk 0.1.0

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
//! Record-level GDSII utilities. Raw cells retain their source database unit
//! and can contain records outside the editable layout profile.
use crate::{Cell, Element, Error, Layout, PropertyValue, Result, TableEntry};
use sha1::{Digest, Sha1};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;

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 SNAME: u8 = 0x12;

/// Six on-disk year, month, day, hour, minute and second fields. Some
/// producers use calendar years, others years since 1900. No timezone is encoded.
pub type Timestamp = [u16; 6];

fn selected_cell<'a>(layout: &'a Layout, name: &str) -> Result<&'a Cell> {
    layout
        .cells
        .iter()
        .find(|cell| cell.name == name)
        .ok_or_else(|| Error::invalid(format!("unknown cell {name:?}")))
}

/// GDS records cannot carry properties attached to the OASIS name-table
/// entry used by a label or property. Check just the entries a fragment uses.
#[derive(Default)]
struct AnnotatedStrings<'a> {
    labels: BTreeSet<&'a str>,
    names: BTreeSet<&'a str>,
    values: BTreeSet<&'a [u8]>,
}
impl<'a> AnnotatedStrings<'a> {
    fn in_layout(layout: &'a Layout) -> Self {
        let mut set = Self::default();
        for table in &layout.table_properties {
            if table.reference.is_some() || table.properties.is_empty() {
                continue;
            }
            match &table.entry {
                TableEntry::Text(s) => {
                    set.labels.insert(s);
                }
                TableEntry::PropertyName(s) => {
                    set.names.insert(s);
                }
                TableEntry::PropertyString(b) => {
                    set.values.insert(b);
                }
                TableEntry::CellName(_) => {}
            }
        }
        set
    }

    fn check(&self, element: &Element) -> Result<()> {
        if matches!(element.unadorned(), Element::Text { text, .. } if self.labels.contains(text.as_str()))
        {
            return Err(Error::unsupported(
                "GDSII fragment cannot preserve properties on the bound OASIS TEXTSTRING",
            ));
        }
        for prop in element.properties() {
            if self.names.contains(prop.name.as_str()) {
                return Err(Error::unsupported(
                    "GDSII fragment cannot preserve properties on the bound OASIS PROPNAME",
                ));
            }
            if prop.values.iter().any(
                |v| matches!(v, PropertyValue::Binary(b) if self.values.contains(b.as_slice())),
            ) {
                return Err(Error::unsupported(
                    "GDSII fragment cannot preserve properties on the bound OASIS PROPSTRING",
                ));
            }
        }
        Ok(())
    }
}

/// Encode the selected zero-based element on the layout's current integer grid.
/// The fragment starts with BOUNDARY, PATH, TEXT, SREF or AREF, includes the
/// element's ordered PROPATTR/PROPVALUE pairs, and ends with ENDEL. SREF and
/// AREF preserve the target name and do not include the target cell's definition.
/// To change the destination precision, call [Layout::resample] or [Layout::regrid_exact] first.
pub fn element_bytes(layout: &Layout, name: &str, index: usize) -> Result<Vec<u8>> {
    let cell = selected_cell(layout, name)?;
    let elem = cell
        .elements
        .get(index)
        .ok_or_else(|| Error::invalid(format!("cell {name:?} has no element at index {index}")))?;
    let mut bytes = Vec::new();
    elem.validate()
        .and_then(|()| AnnotatedStrings::in_layout(layout).check(elem))
        .and_then(|()| crate::gds::write_element(&mut bytes, elem))
        .map_err(|e| e.at_element(name, index, elem))?;
    Ok(bytes)
}

fn selected_gds_cell<'a>(layout: &'a Layout, name: &str) -> Result<&'a Cell> {
    let cell = selected_cell(layout, name)?;
    if !layout.table_properties.is_empty() {
        let tables = AnnotatedStrings::in_layout(layout);
        for (i, elem) in cell.elements.iter().enumerate() {
            tables
                .check(elem)
                .map_err(|err| err.at_element(name, i, elem))?;
        }
    }
    Ok(cell)
}

/// Encode one editable cell from BGNSTR through ENDSTR, in stored element order.
/// The default six timestamp fields match the regular GDSII writer. The caller
/// supplies the destination library, DBU and any referenced cell definitions.
pub fn cell_bytes(layout: &Layout, name: &str, timestamp: Option<Timestamp>) -> Result<Vec<u8>> {
    let cell = selected_gds_cell(layout, name)?;
    let timestamp = timestamp.unwrap_or(crate::gds::DEFAULT_TIMESTAMP);
    check_timestamp(timestamp)?;
    for (i, e) in cell.elements.iter().enumerate() {
        e.validate().map_err(|err| err.at_element(name, i, e))?;
    }
    let mut bytes = Vec::new();
    crate::gds::write_cell(&mut bytes, cell, timestamp)?;
    Ok(bytes)
}

struct RecordStream<R> {
    r: R,
    bytes: Vec<u8>,
    offset: u64,
    next: u64,
}
impl<R: Read> RecordStream<R> {
    fn new(r: R) -> Self {
        Self {
            r,
            bytes: Vec::new(),
            offset: 0,
            next: 0,
        }
    }
    fn invalid(&self, message: &str) -> Error {
        Error::invalid(format!("GDSII byte {}: {message}", self.offset))
    }
    fn read(&mut self) -> Result<u8> {
        self.offset = self.next;
        let mut header = [0; 4];
        self.r.read_exact(&mut header)?;
        let size = usize::from(u16::from_be_bytes([header[0], header[1]]));
        if size < 4 || !size.is_multiple_of(2) {
            return Err(self.invalid("invalid record length"));
        }
        self.bytes.resize(size, 0);
        self.bytes[..4].copy_from_slice(&header);
        self.r.read_exact(&mut self.bytes[4..])?;
        self.next += size as u64;
        Ok(header[2])
    }
    fn check(&self, record: u8, dtype: u8, length: Option<usize>) -> Result<()> {
        if self.bytes[2] != record
            || self.bytes[3] != dtype
            || length.is_some_and(|n| self.bytes.len() != n)
        {
            return Err(self.invalid(&format!("invalid record, expected 0x{record:02x}")));
        }
        Ok(())
    }
    fn name(&self, record: u8) -> Result<String> {
        self.check(record, 6, None)?;
        let p = &self.bytes[4..];
        let value = p.strip_suffix(&[0]).unwrap_or(p);
        if value.is_empty() || !value.is_ascii() || value.contains(&0) {
            return Err(self.invalid("invalid GDSII name"));
        }
        Ok(String::from_utf8(value.to_vec()).unwrap())
    }
    fn header(&mut self) -> Result<(f64, f64)> {
        self.read()?;
        self.check(HEADER, 2, Some(6))?;
        self.read()?;
        self.check(BGNLIB, 2, Some(28))?;
        let mut named = false;
        loop {
            match self.read()? {
                LIBNAME if !named => {
                    self.name(LIBNAME)?;
                    named = true;
                }
                UNITS if named => {
                    self.check(UNITS, 5, Some(20))?;
                    let ratio = crate::gds::decode_real(&self.bytes[4..12], false)?;
                    let precision = crate::gds::decode_real(&self.bytes[12..20], true)?;
                    if ratio <= 0. || precision <= 0. {
                        return Err(self.invalid("non-positive GDSII units"));
                    }
                    return Ok((precision / ratio, precision));
                }
                // Optional library metadata does not affect coordinates or raw structure bytes.
                0x1f | 0x20 | 0x22 | 0x23 | 0x36..=0x3b => {}
                _ => return Err(self.invalid("expected LIBNAME and UNITS in the library header")),
            }
        }
    }
    fn cell(&mut self) -> Result<(String, RawCell)> {
        self.check(BGNSTR, 2, Some(28))?;
        let offset = self.offset;
        self.read()?;
        let name = self.name(STRNAME)?;
        let mut dependencies = BTreeSet::new();
        loop {
            match self.read()? {
                ENDSTR => {
                    self.check(ENDSTR, 0, Some(4))?;
                    break;
                }
                SNAME => {
                    dependencies.insert(self.name(SNAME)?);
                }
                HEADER | BGNLIB | LIBNAME | UNITS | BGNSTR | STRNAME | ENDLIB => {
                    return Err(self.invalid("misplaced record inside a structure"));
                }
                _ => {}
            }
        }
        Ok((
            name,
            RawCell {
                offset,
                length: self.next - offset,
                dependencies,
            },
        ))
    }
}

/// The physical user unit and database-unit precision, both in metres.
/// Stops immediately after UNITS, leaving a stream positioned at the next record.
pub fn get_gds_units(reader: impl Read) -> Result<(f64, f64)> {
    RecordStream::new(reader).header()
}

#[derive(Debug, Clone)]
pub struct RawCell {
    pub offset: u64,
    pub length: u64,
    pub dependencies: BTreeSet<String>,
}
impl RawCell {
    /// Copy the original structure, including BGNSTR, STRNAME, all element records and ENDSTR.
    pub fn copy_to(&self, reader: &mut (impl Read + Seek), writer: impl Write) -> Result<()> {
        copy_range(reader, writer, self.offset, self.length)
    }
}

fn copy_range<R: Read + Seek, W: Write>(
    reader: &mut R,
    mut writer: W,
    offset: u64,
    length: u64,
) -> Result<()> {
    reader.seek(SeekFrom::Start(offset))?;
    if io::copy(&mut reader.take(length), &mut writer)? != length {
        return Err(Error::invalid("source file ended before the indexed range"));
    }
    Ok(())
}

#[derive(Debug)]
pub struct GdsIndex {
    pub unit_meters: f64,
    pub dbu_meters: f64,
    pub cells: BTreeMap<String, RawCell>,
}

impl GdsIndex {
    /// Build a structural index without allocating polygon or path coordinates.
    /// Offsets are from the beginning of the input; use the same unchanged file for copying.
    pub fn read(reader: impl Read) -> Result<Self> {
        let mut stream = RecordStream::new(BufReader::new(reader));
        let (unit_meters, dbu_meters) = stream.header()?;
        let mut cells = BTreeMap::new();
        loop {
            match stream.read()? {
                BGNSTR => {
                    let (name, entry) = stream.cell()?;
                    if cells.insert(name.clone(), entry).is_some() {
                        return Err(stream.invalid(&format!("duplicate cell {name:?}")));
                    }
                }
                ENDLIB => {
                    stream.check(ENDLIB, 0, Some(4))?;
                    break;
                }
                _ => return Err(stream.invalid("expected BGNSTR or ENDLIB")),
            }
        }
        let mut tail = [0; 8192];
        loop {
            match stream.r.read(&mut tail) {
                Ok(0) => break,
                Ok(n) if tail[..n].iter().all(|x| *x == 0) => {}
                Ok(_) => return Err(stream.invalid("nonzero bytes after ENDLIB")),
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Ok(Self {
            unit_meters,
            dbu_meters,
            cells,
        })
    }
}

pub fn get_binary_cells(mut reader: impl Read + Seek) -> Result<BTreeMap<String, Vec<u8>>> {
    reader.seek(SeekFrom::Start(0))?;
    let index = GdsIndex::read(&mut reader)?;
    let mut result = BTreeMap::new();
    for (name, range) in index.cells {
        let mut bytes = Vec::new();
        range.copy_to(&mut reader, &mut bytes)?;
        result.insert(name, bytes);
    }
    Ok(result)
}

/// gdspy canonical content: cell bodies sorted lexicographically, excluding
/// BGNSTR timestamps and ENDSTR. Library name, unit records and order are excluded.
pub fn canonical_content(mut reader: impl Read + Seek, mut output: impl Write) -> Result<()> {
    reader.seek(SeekFrom::Start(0))?;
    let index = GdsIndex::read(&mut reader)?;
    let mut cells: Vec<_> = index.cells.iter().collect();
    // Each cell body begins with STRNAME; its big-endian length precedes the
    // unique ASCII name. No geometry is needed to compute the sorting order.
    cells.sort_unstable_by(|(a, _), (b, _)| {
        a.len()
            .next_multiple_of(2)
            .cmp(&b.len().next_multiple_of(2))
            .then_with(|| a.cmp(b))
    });
    for (_, cell) in cells {
        copy_range(&mut reader, &mut output, cell.offset + 28, cell.length - 32)?;
    }
    Ok(())
}

pub fn gdsii_hash(reader: impl Read + Seek) -> Result<String> {
    struct HashSink(Sha1);
    impl Write for HashSink {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.update(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }
    let mut hash = HashSink(Sha1::new());
    canonical_content(reader, &mut hash)?;
    let mut hex = String::with_capacity(40);
    for byte in hash.0.finalize() {
        use std::fmt::Write as _;
        write!(&mut hex, "{byte:02x}").expect("writing to String is infallible");
    }
    Ok(hex)
}

fn check_timestamp(t: Timestamp) -> Result<()> {
    let [year, month, day, hour, minute, second] = t;
    let year = i32::from(year);
    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    let max_day = match month {
        2 => 28 + u16::from(leap),
        4 | 6 | 9 | 11 => 30,
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        _ => 0,
    };
    if year > i32::from(i16::MAX)
        || day == 0
        || day > max_day
        || hour >= 24
        || minute >= 60
        || second >= 60
    {
        return Err(Error::invalid("invalid GDSII date or time"));
    }
    Ok(())
}

/// Write an exact copy with new BGNLIB/BGNSTR timestamps, including original file padding.
pub fn rewrite_timestamps(
    mut reader: impl Read + Seek,
    mut out: impl Write,
    timestamp: Timestamp,
) -> Result<()> {
    check_timestamp(timestamp)?;
    reader.seek(SeekFrom::Start(0))?;
    let index = GdsIndex::read(&mut reader)?;
    let mut locations: Vec<_> = index.cells.values().map(|c| c.offset + 4).collect();
    locations.push(10); // HEADER is 6 bytes; BGNLIB's payload begins 4 bytes later.
    locations.sort_unstable();
    let mut pos = 0;
    let encoded = crate::gds::encode_dates(timestamp);
    for next in locations {
        copy_range(&mut reader, &mut out, pos, next - pos)?;
        out.write_all(&encoded)?;
        pos = next + 24;
    }
    reader.seek(SeekFrom::Start(pos))?;
    io::copy(&mut reader, &mut out)?;
    out.flush()?;
    Ok(())
}

/// Replace the file only after validating and writing the entire transformed stream.
pub fn set_gdsii_timestamp(path: impl AsRef<Path>, timestamp: Timestamp) -> Result<()> {
    let path = path.as_ref();
    let src = File::open(path)?;
    let perms = src.metadata()?.permissions();
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
    rewrite_timestamps(
        BufReader::new(src),
        BufWriter::new(tmp.as_file_mut()),
        timestamp,
    )?;
    fs::set_permissions(tmp.path(), perms)?;
    tmp.persist(path).map_err(|e| e.error)?;
    Ok(())
}

/// Incremental library writer. Raw-cell data uses the destination DBU; the
/// caller must supply the original DBU when assembling imported raw cells.
pub struct GdsWriter<W: Write> {
    output: W,
    precision: f64,
    timestamp: Timestamp,
    dependencies: BTreeMap<String, BTreeSet<String>>,
    poisoned: bool,
    allow_external: bool,
}
impl<W: Write> GdsWriter<W> {
    pub fn new(
        mut output: W,
        name: &str,
        unit_meters: f64,
        precision: f64,
        timestamp: Timestamp,
    ) -> Result<Self> {
        check_timestamp(timestamp)?;
        crate::gds::write_header(&mut output, name, unit_meters, precision, timestamp)?;
        Ok(Self {
            output,
            precision,
            timestamp,
            dependencies: BTreeMap::new(),
            poisoned: false,
            allow_external: false,
        })
    }
    /// Permit references to cells supplied by another library. Internal cycles remain invalid.
    #[must_use]
    pub fn allow_external_references(mut self, allow: bool) -> Self {
        self.allow_external = allow;
        self
    }
    fn check_name(&self, name: &str) -> Result<()> {
        if self.poisoned {
            return Err(Error::invalid(
                "GDSII writer encountered an earlier I/O error",
            ));
        }
        if self.dependencies.contains_key(name) {
            return Err(Error::invalid(format!("duplicate cell {name:?}")));
        }
        Ok(())
    }
    /// Serialize a named cell using the associated source DBU and table bindings.
    pub fn write_layout_cell(
        &mut self,
        layout: &Layout,
        name: &str,
        timestamp: Option<Timestamp>,
    ) -> Result<()> {
        if self.precision != layout.dbu_meters {
            return Err(Error::invalid(
                "the source and writer database units differ",
            ));
        }
        self.write_cell(selected_gds_cell(layout, name)?, timestamp)
    }
    /// The caller supplies a standalone cell already on the destination grid.
    pub fn write_cell(&mut self, cell: &Cell, timestamp: Option<Timestamp>) -> Result<()> {
        self.check_name(&cell.name)?;
        let timestamp = timestamp.unwrap_or(self.timestamp);
        check_timestamp(timestamp)?;
        let mut references = BTreeSet::new();
        for element in &cell.elements {
            element.validate()?;
            if let Element::Reference { cell, .. } = element.unadorned() {
                references.insert(cell.clone());
            }
        }
        // Preflight format limits before modifying a non-seekable output.
        crate::gds::write_cell(io::sink(), cell, timestamp)?;
        self.poisoned = true;
        crate::gds::write_cell(&mut self.output, cell, timestamp)?;
        self.poisoned = false;
        self.dependencies.insert(cell.name.clone(), references);
        Ok(())
    }
    pub fn write_raw_cell(&mut self, bytes: &[u8]) -> Result<()> {
        let mut stream = RecordStream::new(bytes);
        stream.read()?;
        let (name, entry) = stream.cell()?;
        if entry.length != bytes.len() as u64 {
            return Err(Error::invalid("raw cell contains trailing bytes"));
        }
        self.check_name(&name)?;
        self.poisoned = true;
        self.output.write_all(bytes)?;
        self.poisoned = false;
        self.dependencies.insert(name, entry.dependencies);
        Ok(())
    }
    pub fn finish(mut self) -> Result<W> {
        if self.poisoned {
            return Err(Error::invalid("cannot finish after an I/O error"));
        }
        let mut incoming: BTreeMap<&str, usize> =
            self.dependencies.keys().map(|s| (s.as_str(), 0)).collect();
        for (name, targets) in &self.dependencies {
            for t in targets {
                if let Some(count) = incoming.get_mut(t.as_str()) {
                    *count += 1;
                } else if !self.allow_external {
                    return Err(Error::invalid(format!(
                        "cell {name:?} references missing cell {t:?}"
                    )));
                }
            }
        }
        let mut roots: Vec<_> = incoming
            .iter()
            .filter(|(_, n)| **n == 0)
            .map(|(s, _)| *s)
            .collect();
        let mut count = 0;
        while let Some(n) = roots.pop() {
            count += 1;
            for t in &self.dependencies[n] {
                let Some(pending) = incoming.get_mut(t.as_str()) else {
                    continue;
                };
                *pending -= 1;
                if *pending == 0 {
                    roots.push(t);
                }
            }
        }
        if count != incoming.len() {
            return Err(Error::invalid("cyclic GDSII cell references"));
        }
        self.output.write_all(&[0, 4, ENDLIB, 0])?;
        self.output.flush()?;
        Ok(self.output)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Format, Layout};
    use std::io::Cursor;

    fn original() -> Vec<u8> {
        let mut layout = Layout::new("demo", 1e-9).unwrap();
        layout.add_cell("LONGNAME").unwrap();
        layout.add_cell("ABC").unwrap();
        let mut source = Vec::new();
        crate::write_to(&layout, &mut source, Format::Gdsii).unwrap();
        source
    }

    #[test]
    fn fragments_include_ordered_properties_and_use_exact_record_boundaries() {
        let mut l = Layout::new("LIB", 1e-9).unwrap();
        l.add_cell("A").unwrap();
        l.add_element(
            "A",
            Element::Reference {
                cell: "EXT".into(),
                origin: crate::Point { x: -2, y: 3 },
                transform: Default::default(),
                array: None,
            }
            .with_properties(vec![
                crate::Property::gds(5, b"a"),
                crate::Property::gds(5, b"b"),
            ]),
        )
        .unwrap();
        let fragment = element_bytes(&l, "A", 0).unwrap();
        assert_eq!(&fragment[..4], &[0, 4, 0x0a, 0]);
        assert_eq!(&fragment[fragment.len() - 4..], &[0, 4, 0x11, 0]);
        let whole = cell_bytes(&l, "A", None).unwrap();
        assert_eq!(&whole[34..whole.len() - 4], fragment);
        let mut writer = GdsWriter::new(Vec::new(), "LIB", 1e-6, 1e-9, [2024, 2, 29, 0, 0, 0])
            .unwrap()
            .allow_external_references(true);
        writer.write_raw_cell(&whole).unwrap();
        let restored = crate::gds::read(writer.finish().unwrap().as_slice(), None).unwrap();
        assert_eq!(restored.cells, l.cells);
        assert!(cell_bytes(&l, "A", Some([2023, 2, 29, 0, 0, 0])).is_err());
        assert!(element_bytes(&l, "A", 1).is_err());
    }
    #[test]
    fn raw_cells_hash_unit_and_incremental_writer_match_gdspy_contract() {
        let bytes = original();
        let (unit, dbu) = get_gds_units(bytes.as_slice()).unwrap();
        assert!((unit - 1e-6).abs() < 1e-20);
        assert_eq!(dbu, 1e-9);
        let cells = get_binary_cells(Cursor::new(&bytes)).unwrap();
        let mut canonical = Vec::new();
        canonical_content(Cursor::new(&bytes), &mut canonical).unwrap();
        let expected: Vec<_> = ["ABC", "LONGNAME"]
            .iter()
            .flat_map(|&k| {
                let data = &cells[k];
                data[28..data.len() - 4].iter().copied()
            })
            .collect();
        assert_eq!(canonical, expected);
        let mut w =
            GdsWriter::new(Vec::new(), "another", 1e-6, dbu, [2020, 5, 9, 2, 3, 4]).unwrap();
        w.write_raw_cell(&cells["ABC"]).unwrap();
        assert!(w.write_raw_cell(&cells["ABC"]).is_err());
        w.write_raw_cell(&cells["LONGNAME"]).unwrap();
        let copied = w.finish().unwrap();
        assert_eq!(
            gdsii_hash(Cursor::new(bytes)).unwrap(),
            gdsii_hash(Cursor::new(copied)).unwrap()
        );
    }
    #[test]
    fn timestamp_replacement_preserves_all_other_bytes_and_padding() {
        let mut input = original();
        input.extend([0; 200]);
        let mut output = Vec::new();
        let stamp = [2024, 2, 29, 14, 13, 12];
        rewrite_timestamps(Cursor::new(&input), &mut output, stamp).unwrap();
        let index = GdsIndex::read(output.as_slice()).unwrap();
        let mut expected = input;
        for offset in [10]
            .into_iter()
            .chain(index.cells.values().map(|c| c.offset as usize + 4))
        {
            expected[offset..offset + 24].copy_from_slice(&crate::gds::encode_dates(stamp));
        }
        assert_eq!(output, expected);
    }
    #[test]
    fn malformed_sources_never_replace_the_original_file() {
        let d = tempfile::tempdir().unwrap();
        let f = d.path().join("bad.gds");
        let mut source = original();
        source.truncate(source.len() - 2);
        fs::write(&f, &source).unwrap();
        assert!(set_gdsii_timestamp(&f, [1999, 1, 1, 0, 0, 0]).is_err());
        assert_eq!(fs::read(f).unwrap(), source);
    }
}