layouttk 0.1.1

Integer-grid GDSII and OASIS layout processing with hierarchy-aware extraction
Documentation
//! Read, edit, and write hierarchical GDSII and OASIS layouts on their original integer grid.
//! Coordinates and widths are in database units. A database unit's physical size is in meters.
//! The [user guides](guides/) cover Python, file conversion, tool interoperability and benchmarks.
//!
//! Draw a marked polygon, repeat it at explicit offsets, and write OASIS in memory.
//!
//! ```rust
//! use layouttk::{Element, Format, Layer, Layout, Point, Property, Repetition, write_to};
//!
//! let mut mask = Layout::new("MASK", 1e-9)?;
//! mask.add_cell("DIE")?;
//! let mut contact = Element::Polygon {
//!     layer: Layer { number: 7, datatype: 1 },
//!     points: vec![Point { x: 0, y: 0 }, Point { x: 40, y: 0 }, Point { x: 0, y: 20 }],
//! };
//! contact.set_properties(vec![Property::gds(7, b"CONTACT")]);
//! contact.set_repetition(Some(Repetition::Offsets(vec![
//!     Point { x: -13, y: 27 }, Point { x: 51, y: 8 },
//! ])))?;
//! mask.add_element("DIE", contact)?;
//! let mut data = Vec::new();
//! write_to(&mask, &mut data, Format::Oasis)?;
//! let restored = layouttk::read_from(data.as_slice(), None)?;
//! assert_eq!(mask.cells, restored.cells);
//! # Ok::<(), layouttk::Error>(())
//! ```
pub mod conversion;
mod gds;
pub mod gds_tools;
pub mod geometry;
#[cfg(doc)]
pub mod guides;
pub mod hierarchy;
mod model;
pub mod paths;
#[cfg(feature = "python")]
mod python_arrays;
#[cfg(feature = "python")]
mod python_gds_tools;
#[cfg(feature = "python")]
mod python_geometry;
#[cfg(feature = "python")]
mod python_paths;
mod resample;
pub use resample::GridRounding;
mod oasis;
#[cfg(feature = "python")]
mod python;

pub use model::{
    Array, Cell, Element, Interval, Layer, LayerName, Layout, PathEnds, Point, Property,
    PropertyValue, Repetition, Summary, TableEntry, TableProperties, TextStyle, Transform,
};
use std::collections::BTreeSet;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::Path;

/// Distinguishes malformed data from valid format features outside the supported profile.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("invalid layout: {0}")]
    Invalid(String),
    #[error("unsupported feature: {0}")]
    Unsupported(String),
    #[error(transparent)]
    Io(#[from] io::Error),
}
impl Error {
    pub(crate) fn invalid(message: impl Into<String>) -> Self {
        Self::Invalid(message.into())
    }
    pub(crate) fn unsupported(message: impl Into<String>) -> Self {
        Self::Unsupported(message.into())
    }
}
impl Error {
    fn at_element(self, cell: &str, index: usize, element: &Element) -> Self {
        let add_context = |message: String| {
            let layer = element
                .layer()
                .map(|l| format!(", layer {}/{}", l.number, l.datatype))
                .unwrap_or_default();
            format!("cell {cell:?}, element {index}{layer}: {message}")
        };
        match self {
            Self::Invalid(message) => Self::Invalid(add_context(message)),
            Self::Unsupported(message) => Self::Unsupported(add_context(message)),
            error => error,
        }
    }
}
pub type Result<T> = std::result::Result<T, Error>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
    Gdsii,
    Oasis,
}
impl Format {
    pub fn from_path(path: &Path) -> Result<Self> {
        path.extension()
            .and_then(|e| e.to_str())
            .unwrap_or_default()
            .parse()
    }
}

impl std::str::FromStr for Format {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self> {
        match value.to_ascii_lowercase().as_str() {
            "gds" | "gdsii" | "gds2" => Ok(Self::Gdsii),
            "oas" | "oasis" => Ok(Self::Oasis),
            _ => Err(Error::invalid("expected GDSII (.gds) or OASIS (.oas)")),
        }
    }
}

pub const DEFAULT_OAS_BUDGET: usize = 512 * 1024 * 1024;

/// Reading policy. The OASIS budget accounts for retained data, separately from decoding buffers.
#[derive(Debug, Clone, Copy)]
pub struct ReadOptions<'a> {
    pub layers: Option<&'a BTreeSet<Layer>>,
    pub oas_budget_bytes: usize,
}

impl Default for ReadOptions<'_> {
    fn default() -> Self {
        Self {
            layers: None,
            oas_budget_bytes: DEFAULT_OAS_BUDGET,
        }
    }
}

impl ReadOptions<'_> {
    pub fn read(self, path: impl AsRef<Path>) -> Result<Layout> {
        self.read_from(File::open(path)?)
    }

    /// Detect the input from its header. Filtering keeps all cells and placements.
    pub fn read_from(self, reader: impl Read) -> Result<Layout> {
        self.read_fragment(reader, false)
    }

    /// Decode a standalone file or an explicitly requested fragment with external references.
    pub fn read_fragment(
        self,
        reader: impl Read,
        allow_external_references: bool,
    ) -> Result<Layout> {
        let mut reader = BufReader::new(reader);
        // Read exactly four bytes even on pipes or one-byte-at-a-time readers.
        let mut header = [0; 4];
        reader.read_exact(&mut header)?;
        let input = header.as_slice().chain(reader);
        let layout = match header {
            [0, 6, 0, 2] => gds::read(input, self.layers)?,
            [b'%', b'S', b'E', b'M'] => oasis::read(input, self.layers, self.oas_budget_bytes)?,
            _ => {
                return Err(Error::invalid(
                    "unrecognized file header (expected GDSII or OASIS)",
                ));
            }
        };
        layout.validate_references(allow_external_references)?;
        Ok(layout)
    }
}

pub fn read_from(reader: impl Read, layers: Option<&BTreeSet<Layer>>) -> Result<Layout> {
    ReadOptions {
        layers,
        ..Default::default()
    }
    .read_from(reader)
}

pub fn read(path: impl AsRef<Path>, layers: Option<&BTreeSet<Layer>>) -> Result<Layout> {
    ReadOptions {
        layers,
        ..Default::default()
    }
    .read(path)
}

pub fn write_to(layout: &Layout, writer: impl Write, format: Format) -> Result<()> {
    layout.validate()?;
    let mut writer = BufWriter::new(writer);
    match format {
        Format::Gdsii => gds::write(layout, &mut writer)?,
        Format::Oasis => oasis::write(layout, &mut writer)?,
    }
    writer.flush()?;
    Ok(())
}

/// Exercise the same encoder as a file write, reporting the first error without creating a file.
pub fn check_write(layout: &Layout, format: Format) -> Result<()> {
    write_to(layout, io::sink(), format)
}

/// Finish serialization in the destination directory before replacing the target.
pub fn write(layout: &Layout, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let format = Format::from_path(path)?;
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
    write_to(layout, tmp.as_file_mut(), format)?;
    tmp.persist(path).map_err(|e| e.error)?;
    Ok(())
}