mod buffer;
mod entity;
mod header;
mod lexical;
mod serialize;
#[derive(Debug)]
pub enum WriteError {
UnsupportedIrVariant { detail: String },
DanglingId { detail: String },
InvalidFloat { value: f64, context: &'static str },
Io(std::io::Error),
}
impl std::fmt::Display for WriteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnsupportedIrVariant { detail } => {
write!(f, "write error: unsupported IR variant ({detail})")
}
Self::DanglingId { detail } => {
write!(f, "write error: dangling id ({detail})")
}
Self::InvalidFloat { value, context } => {
write!(f, "write error: non-finite real {value} in {context}")
}
Self::Io(e) => write!(f, "write error: io ({e})"),
}
}
}
impl std::error::Error for WriteError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for WriteError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl crate::ir::StepModel {
pub fn write_to<W: std::io::Write>(&self, mut writer: W) -> Result<(), WriteError> {
let mut buffer = buffer::WriteBuffer::new(self);
buffer.emit_all()?;
let entities = buffer.finish_entities();
let headers = header::header_for(self);
serialize::write_file(&mut writer, &headers, &entities)
}
pub fn write_to_string(&self) -> Result<String, WriteError> {
let mut buf = Vec::new();
self.write_to(&mut buf)?;
Ok(String::from_utf8(buf).expect("writer emits valid UTF-8"))
}
pub fn write_to_file<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), WriteError> {
use std::io::Write as _;
let file = std::fs::File::create(path)?;
let mut writer = std::io::BufWriter::new(file);
self.write_to(&mut writer)?;
writer.flush()?;
Ok(())
}
}