layouttk 0.1.1

Integer-grid GDSII and OASIS layout processing with hierarchy-aware extraction
Documentation
//! GDSII utilities shared by the native codec and the Python compatibility API.
use crate::gds_tools::{self, GdsWriter, Timestamp};
use crate::python::PyLayout;
use crate::{Error, Result};
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyDict};
use std::fs::File;
use std::io::{BufReader, BufWriter, Cursor, Read, Seek};
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;

trait FileInput: Read + Seek {}
impl<T: Read + Seek> FileInput for T {}
fn input(path: Option<PathBuf>, data: &[u8]) -> Result<Box<dyn FileInput + '_>> {
    match path {
        Some(path) => Ok(Box::new(BufReader::new(File::open(path)?))),
        None => Ok(Box::new(Cursor::new(data))),
    }
}

#[pyfunction]
#[pyo3(signature=(path, data))]
fn _gds_units(py: Python<'_>, path: Option<PathBuf>, data: &[u8]) -> PyResult<(f64, f64)> {
    Ok(py.detach(|| gds_tools::get_gds_units(input(path, data)?))?)
}

#[pyfunction]
#[pyo3(signature=(path, data))]
fn _gds_sha1(py: Python<'_>, path: Option<PathBuf>, data: &[u8]) -> PyResult<String> {
    Ok(py.detach(|| gds_tools::gdsii_hash(input(path, data)?))?)
}

#[pyfunction]
#[pyo3(signature=(path, data))]
fn _gds_cells(py: Python<'_>, path: Option<PathBuf>, data: &[u8]) -> PyResult<Py<PyDict>> {
    let cells = py.detach(|| gds_tools::get_binary_cells(input(path, data)?))?;
    let result = PyDict::new(py);
    for (name, data) in cells {
        result.set_item(name, PyBytes::new(py, &data))?;
    }
    Ok(result.unbind())
}

#[pyfunction]
fn _gds_set_timestamp(py: Python<'_>, path: PathBuf, timestamp: Timestamp) -> PyResult<()> {
    Ok(py.detach(|| gds_tools::set_gdsii_timestamp(path, timestamp))?)
}

#[pyfunction]
fn _gds_element_bytes<'py>(
    py: Python<'py>,
    layout: &PyLayout,
    cell: &str,
    index: usize,
) -> PyResult<Bound<'py, PyBytes>> {
    let bytes = py.detach(|| gds_tools::element_bytes(&layout.inner, cell, index))?;
    Ok(PyBytes::new(py, &bytes))
}

#[pyfunction]
#[pyo3(signature=(layout,cell,timestamp=None))]
fn _gds_cell_bytes<'py>(
    py: Python<'py>,
    layout: &PyLayout,
    cell: &str,
    timestamp: Option<Timestamp>,
) -> PyResult<Bound<'py, PyBytes>> {
    let bytes = py.detach(|| gds_tools::cell_bytes(&layout.inner, cell, timestamp))?;
    Ok(PyBytes::new(py, &bytes))
}

#[pyclass(module = "layouttk._native", name = "_GdsWriter")]
struct PyGdsWriter {
    writer: Option<GdsWriter<BufWriter<NamedTempFile>>>,
    target: PathBuf,
}
#[pymethods]
impl PyGdsWriter {
    #[new]
    fn new(
        target: PathBuf,
        name: &str,
        unit: f64,
        precision: f64,
        timestamp: Timestamp,
        allow_external_references: bool,
    ) -> PyResult<Self> {
        let parent = target
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or(Path::new("."));
        let tmp = NamedTempFile::new_in(parent)?;
        let writer = GdsWriter::new(BufWriter::new(tmp), name, unit, precision, timestamp)?
            .allow_external_references(allow_external_references);
        Ok(Self {
            writer: Some(writer),
            target,
        })
    }
    fn write_binary_cell(&mut self, py: Python<'_>, data: &[u8]) -> PyResult<()> {
        let writer = self
            .writer
            .as_mut()
            .ok_or_else(|| Error::invalid("GdsWriter is closed"))?;
        Ok(py.detach(|| writer.write_raw_cell(data))?)
    }
    #[pyo3(signature=(layout,name,timestamp=None))]
    fn write_layout_cell(
        &mut self,
        py: Python<'_>,
        layout: &PyLayout,
        name: &str,
        timestamp: Option<Timestamp>,
    ) -> PyResult<()> {
        let writer = self
            .writer
            .as_mut()
            .ok_or_else(|| Error::invalid("GdsWriter is closed"))?;
        Ok(py.detach(|| writer.write_layout_cell(&layout.inner, name, timestamp))?)
    }
    fn close(&mut self, py: Python<'_>) -> PyResult<()> {
        let Some(writer) = self.writer.take() else {
            return Ok(());
        };
        let path = &self.target;
        py.detach(|| -> Result<()> {
            let result = writer.finish()?.into_inner().map_err(|e| e.into_error())?;
            result.persist(path).map_err(|e| e.error)?;
            Ok(())
        })?;
        Ok(())
    }
    fn abort(&mut self) {
        self.writer.take();
    }
}

pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(_gds_units, m)?)?;
    m.add_function(wrap_pyfunction!(_gds_sha1, m)?)?;
    m.add_function(wrap_pyfunction!(_gds_cells, m)?)?;
    m.add_function(wrap_pyfunction!(_gds_element_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(_gds_cell_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(_gds_set_timestamp, m)?)?;
    m.add_class::<PyGdsWriter>()?;
    Ok(())
}