use std::collections::{BTreeMap, BTreeSet};
use std::io::{BufRead, BufReader, Cursor, Read};
use std::rc::Rc;
use super::binary::{Input, add, coord, legal_string};
use super::{MAGIC, MAX_BLOCK, ORIGIN};
use crate::{
Array, Cell, Element, Error, Interval, Layer, LayerName, Layout, PathEnds, Point, Property,
PropertyValue, Repetition, Result, Transform,
};
mod metadata;
mod offsets;
use crate::{TableEntry, TableProperties};
use flate2::{Crc, Decompress, FlushDecompress, Status};
use metadata::{PendingProperty, Scope, WireValues};
use offsets::{Directory, Location, Observed};
type In<'a> = Input<&'a mut dyn BufRead>;
#[derive(Clone)]
enum Name {
Inline(Rc<str>),
Index(u64),
}
impl Name {
fn read(input: &mut In, indexed: bool, is_name: bool) -> Result<Self> {
Ok(if indexed {
Self::Index(input.uint()?)
} else {
Self::Inline(input.string(is_name)?.into())
})
}
fn retained_bytes(&self) -> usize {
match self {
Self::Inline(s) => s.len() + 32,
Self::Index(_) => 0,
}
}
fn lookup<'a>(&'a self, names: &'a Names) -> Result<&'a str> {
match self {
Self::Inline(name) => Ok(name),
Self::Index(i) => names
.values
.get(i)
.map(String::as_str)
.ok_or_else(|| Error::invalid(format!("undefined OASIS name index {i}"))),
}
}
}
#[derive(Default)]
struct Names<T = String> {
values: BTreeMap<u64, T>,
reverse: BTreeMap<T, u64>,
explicit: Option<bool>,
}
impl<T: Ord + Clone> Names<T> {
fn insert(&mut self, name: T, index: Option<u64>, unique: bool) -> Result<u64> {
let explicit = index.is_some();
if self.explicit.is_some_and(|prev| prev != explicit) {
return Err(Error::invalid(
"mixed implicit and explicit OASIS name numbering",
));
}
self.explicit = Some(explicit);
let index = index.unwrap_or(self.values.len() as u64);
if let Some(old) = self.values.get(&index) {
if old == &name {
return Ok(index);
}
return Err(Error::invalid(
"conflicting OASIS strings for the same name index",
));
}
if unique && self.reverse.insert(name.clone(), index).is_some() {
return Err(Error::invalid(
"multiple OASIS reference numbers for one cell or property name",
));
}
self.values.insert(index, name);
Ok(index)
}
}
#[derive(Default)]
struct ModalLayer {
number: Option<u32>,
datatype: Option<u32>,
}
impl ModalLayer {
fn read(&mut self, input: &mut In, flags: u8) -> Result<Layer> {
for (bit, slot) in [(1, &mut self.number), (2, &mut self.datatype)] {
if flags & bit != 0 {
*slot = Some(
input
.uint()?
.try_into()
.map_err(|_| Error::unsupported("OASIS layer exceeds u32"))?,
);
}
}
Ok(Layer {
number: required(self.number, "layer")?,
datatype: required(self.datatype, "datatype")?,
})
}
}
fn required<T>(value: Option<T>, field: &str) -> Result<T> {
value.ok_or_else(|| Error::invalid(format!("undefined OASIS modal {field}")))
}
#[derive(Default)]
struct Modals {
relative: bool,
geom: Point,
text: Point,
placement: Point,
layer: ModalLayer,
text_layer: ModalLayer,
width: Option<u64>,
height: Option<u64>,
halfwidth: Option<i64>,
radius: Option<u64>,
compact_trapezoid: Option<u64>,
path_ends: [Option<EndLength>; 2],
polygon: Option<Vec<Point>>,
path: Option<Vec<Point>>,
target: Option<Name>,
label: Option<Name>,
repetition: Option<Rc<Repetition>>,
property_name: Option<Name>,
property_values: Option<Rc<WireValues>>,
standard: Option<bool>,
}
impl Modals {
fn retained_bytes(&self) -> usize {
let lists = [self.path.as_ref(), self.polygon.as_ref()]
.into_iter()
.flatten()
.map(|p| p.capacity() * size_of::<Point>())
.sum::<usize>();
let names = [
self.target.as_ref(),
self.label.as_ref(),
self.property_name.as_ref(),
]
.into_iter()
.flatten()
.map(Name::retained_bytes)
.sum::<usize>();
let offsets = self.repetition.as_ref().map_or(0, |r| repetition_bytes(r));
lists + names + offsets + self.property_values.as_ref().map_or(0, |v| v.bytes)
}
}
fn position(
input: &mut In,
flags: u8,
x_bit: u8,
relative: bool,
last: &mut Point,
) -> Result<Point> {
for (bit, axis) in [(x_bit, &mut last.x), (x_bit >> 1, &mut last.y)] {
if flags & bit != 0 {
let val = input.sint()?;
*axis = if relative {
coord(i128::from(*axis) + i128::from(val))?
} else {
val
};
}
}
Ok(*last)
}
fn dimension(input: &mut In) -> Result<u32> {
input
.uint()?
.checked_add(2)
.and_then(|n| u32::try_from(n).ok())
.ok_or_else(|| Error::unsupported("OASIS array dimension exceeds u32"))
}
fn repetition_bytes(r: &Repetition) -> usize {
match r {
Repetition::Offsets(v) => v.capacity() * size_of::<Point>(),
Repetition::Regular(_) => 0,
}
}
#[derive(Clone, Copy)]
enum EndLength {
Flush,
HalfWidth,
Explicit(i64),
}
impl EndLength {
fn value(self, half: i64) -> i64 {
match self {
Self::Flush => 0,
Self::HalfWidth => half,
Self::Explicit(x) => x,
}
}
}
fn repetition(
input: &mut In,
present: bool,
last: &mut Option<Rc<Repetition>>,
budget: usize,
) -> Result<Option<Rc<Repetition>>> {
if !present {
return Ok(None);
}
let ty = input.uint()?;
if ty == 0 {
return Ok(Some(required(last.clone(), "repetition")?));
}
*last = None;
if matches!(ty, 4..=7 | 10 | 11) {
let count = input.count(super::MAX_POINTS - 1)? + 1;
if count * size_of::<Point>() > budget {
return Err(Error::unsupported(
"OASIS repetition exceeds the configured byte budget",
));
}
let grid = if matches!(ty, 5 | 7 | 11) {
input.uint()?
} else {
1
};
let mut offsets = Vec::with_capacity(count);
let mut p = ORIGIN;
for _ in 0..count {
if ty <= 7 {
let step = u128::from(input.uint()?) * u128::from(grid);
let axis = if ty <= 5 { &mut p.x } else { &mut p.y };
*axis = i64::try_from(step + (*axis as u128))
.map_err(|_| Error::unsupported("OASIS repetition offset exceeds i64"))?;
} else {
let delta = input.delta()?;
p = Point {
x: coord(i128::from(p.x) + i128::from(delta.x) * i128::from(grid))?,
y: coord(i128::from(p.y) + i128::from(delta.y) * i128::from(grid))?,
};
}
offsets.push(p);
}
let r = Rc::new(Repetition::Offsets(offsets));
*last = Some(Rc::clone(&r));
return Ok(Some(r));
}
let mut a = Array {
columns: 1,
rows: 1,
column_step: ORIGIN,
row_step: ORIGIN,
};
match ty {
1 => {
a.columns = dimension(input)?;
a.rows = dimension(input)?;
a.column_step.x = input.unsigned_coord()?;
a.row_step.y = input.unsigned_coord()?;
}
2 => {
a.columns = dimension(input)?;
a.column_step.x = input.unsigned_coord()?;
}
3 => {
a.rows = dimension(input)?;
a.row_step.y = input.unsigned_coord()?;
}
8 => {
a.columns = dimension(input)?;
a.rows = dimension(input)?;
a.column_step = input.delta()?;
a.row_step = input.delta()?;
}
9 => {
a.columns = dimension(input)?;
a.column_step = input.delta()?;
}
_ => return Err(Error::invalid("invalid OASIS repetition type")),
}
let r = Rc::new(Repetition::Regular(a));
*last = Some(Rc::clone(&r));
Ok(Some(r))
}
enum Binding {
Cell(usize),
Target(usize, usize),
Label(usize, usize),
}
struct Parser<'a> {
cells: Vec<Cell>,
current: Option<usize>,
m: Modals,
cells_table: Names,
text_table: Names,
prop_names: Names,
prop_strings: Names<Vec<u8>>,
layer_names: Vec<LayerName>,
table_properties: Vec<TableProperties>,
bindings: Vec<(Binding, u64, Location)>,
at: Location,
observed: Observed,
pending: Vec<PendingProperty>,
scope: Scope,
layers: Option<&'a BTreeSet<Layer>>,
remaining: usize,
}
impl<'a> Parser<'a> {
fn new(layers: Option<&'a BTreeSet<Layer>>, max_retained_bytes: usize) -> Self {
Self {
cells: vec![],
current: None,
m: Modals::default(),
cells_table: Names::default(),
text_table: Names::default(),
prop_names: Names::default(),
prop_strings: Names::default(),
bindings: vec![],
at: Location::default(),
observed: Observed::default(),
pending: vec![],
layer_names: vec![],
table_properties: vec![],
scope: Scope::File,
layers,
remaining: max_retained_bytes,
}
}
fn spend(&mut self, bytes: usize) -> Result<()> {
if bytes > self.available()? {
return Err(Error::unsupported(
"OASIS retained data exceeds the configured byte budget",
));
}
self.remaining -= bytes;
Ok(())
}
fn available(&self) -> Result<usize> {
self.remaining
.checked_sub(self.m.retained_bytes())
.ok_or_else(|| {
Error::unsupported("OASIS modal data exceeds the configured byte budget")
})
}
fn bind(&mut self, name: Name, loc: Binding) -> Result<String> {
match name {
Name::Inline(s) => {
self.spend(s.len())?;
Ok(s.to_string())
}
Name::Index(i) => {
self.spend(48)?;
self.bindings.push((loc, i, self.at));
Ok(String::new())
}
}
}
fn cell(&self) -> Result<usize> {
self.current
.ok_or_else(|| Error::invalid("OASIS element outside a CELL"))
}
fn selected(&self, layer: Layer) -> bool {
self.layers.is_none_or(|layers| layers.contains(&layer))
}
fn record(&mut self, input: &mut In, id: u64) -> Result<()> {
self.observed.record(id, self.at);
if id == 14 {
self.observed.literal(0, self.at);
}
let previous_len = if matches!(id, 17..=27) {
Some(self.cells[self.cell()?].elements.len())
} else {
None
};
match id {
0 => {}
3..=10 => self.named(input, id)?,
11 | 12 => self.layer_name(input, id == 12)?,
13 | 14 => {
let name = Name::read(input, id == 13, true)?;
let i = self.cells.len();
self.spend(160)?;
let name = self.bind(name, Binding::Cell(i))?;
self.cells.push(Cell {
name,
elements: Vec::new(),
properties: vec![],
name_properties: vec![],
});
self.current = Some(i);
self.m = Modals::default();
self.scope = Scope::Cell(i);
}
15 | 16 => {
self.cell()?;
self.m.relative = id == 16;
}
17 | 18 => {
self.placement(input, id)?;
}
19 => {
self.text(input)?;
}
20..=22 => {
self.geometry(input, id)?;
}
23..=26 => {
self.trapezoid(input, id)?;
}
27 => {
self.circle(input)?;
}
28 | 29 => self.property(input, id)?,
_ => {
return Err(Error::unsupported(format!(
"OASIS record {id} at record-stream offset {}",
input.pos - 1
)));
}
}
if let Some(i) = previous_len {
let c = self.cell()?;
self.scope = if self.cells[c].elements.len() > i {
Scope::Element(c, i)
} else {
Scope::Dropped
};
}
self.available()?;
Ok(())
}
fn read_repetition(&mut self, input: &mut In, present: bool) -> Result<Option<Rc<Repetition>>> {
let budget = self.available()?
+ self
.m
.repetition
.as_ref()
.map_or(0, |r| repetition_bytes(r));
repetition(input, present, &mut self.m.repetition, budget)
}
fn placement(&mut self, input: &mut In, id: u64) -> Result<()> {
let c = self.cell()?;
let f = input.byte()?;
if f & 128 != 0 {
if f & 64 == 0 {
self.observed.literal(0, self.at);
}
self.m.target = Some(Name::read(input, f & 64 != 0, true)?);
}
let name = required(self.m.target.clone(), "placement target")?;
let mut tr = Transform {
magnification: 1.0,
angle_deg: 0.0,
reflect_x: f & 1 != 0,
};
if id == 17 {
tr.angle_deg = f64::from((f >> 1) & 3) * 90.0;
} else {
if f & 4 != 0 {
tr.magnification = input.real()?;
}
if f & 2 != 0 {
tr.angle_deg = input.real()?;
}
}
if tr.magnification <= 0.0 {
return Err(Error::invalid("nonpositive OASIS magnification"));
}
let origin = position(input, f, 32, self.m.relative, &mut self.m.placement)?;
let array = self.read_repetition(input, f & 8 != 0)?;
self.spend(192)?;
self.spend(array.as_ref().map_or(0, |r| repetition_bytes(r)))?;
let cell = self.bind(name, Binding::Target(c, self.cells[c].elements.len()))?;
self.cells[c].elements.push(Element::Reference {
cell,
origin,
transform: tr,
array: array.as_deref().cloned(),
});
Ok(())
}
fn text(&mut self, input: &mut In) -> Result<()> {
let c = self.cell()?;
let f = input.byte()?;
if f & 128 != 0 {
return Err(Error::invalid("reserved OASIS TEXT bit set"));
}
if f & 64 != 0 {
if f & 32 == 0 {
self.observed.literal(1, self.at);
}
self.m.label = Some(Name::read(input, f & 32 != 0, false)?);
}
let name = required(self.m.label.clone(), "text string")?;
let layer = self.m.text_layer.read(input, f)?;
let origin = position(input, f, 16, self.m.relative, &mut self.m.text)?;
let array = self.read_repetition(input, f & 4 != 0)?;
if self.selected(layer) {
self.spend(192)?;
let text = self.bind(name, Binding::Label(c, self.cells[c].elements.len()))?;
let element = Element::Text {
text_reference: None,
layer,
origin,
text,
style: None,
};
self.store_shape(c, element, array)?;
}
Ok(())
}
fn geometry(&mut self, input: &mut In, id: u64) -> Result<()> {
let c = self.cell()?;
let f = input.byte()?;
let layer = self.m.layer.read(input, f)?;
if id == 20 {
if f & 0xa0 == 0xa0 {
return Err(Error::invalid("OASIS square has explicit height"));
}
if f & 64 != 0 {
self.m.width = Some(input.uint()?);
}
if f & 128 != 0 {
self.m.height = self.m.width;
} else if f & 32 != 0 {
self.m.height = Some(input.uint()?);
}
} else {
if id == 22 {
if f & 64 != 0 {
self.m.halfwidth = Some(input.unsigned_coord()?);
}
if f & 128 != 0 {
let scheme = input.uint()?;
if scheme > 15 {
return Err(Error::invalid("invalid OASIS PATH extension"));
}
for (slot, code) in self.m.path_ends.iter_mut().zip([scheme >> 2, scheme & 3]) {
match code {
1 => *slot = Some(EndLength::Flush),
2 => *slot = Some(EndLength::HalfWidth),
3 => *slot = Some(EndLength::Explicit(input.sint()?)),
_ => {}
}
}
}
} else if f & 0xc0 != 0 {
return Err(Error::invalid("reserved OASIS POLYGON bits set"));
}
if f & 32 != 0 {
if id == 21 {
self.m.polygon = None;
} else {
self.m.path = None;
}
let p = input.points(id == 21, self.available()?)?;
if id == 21 {
self.m.polygon = Some(p);
} else {
self.m.path = Some(p);
}
}
}
let origin = position(input, f, 16, self.m.relative, &mut self.m.geom)?;
let array = self.read_repetition(input, f & 4 != 0)?;
let selected = self.selected(layer);
let elm = if id == 20 {
let w = required(self.m.width, "rectangle width")?;
let h = required(self.m.height, "rectangle height")?;
let far = Point {
x: coord(i128::from(origin.x) + i128::from(w))?,
y: coord(i128::from(origin.y) + i128::from(h))?,
};
if !selected {
return Ok(());
}
self.spend(256)?;
Element::Polygon {
layer,
points: vec![
origin,
Point {
x: far.x,
y: origin.y,
},
far,
Point {
x: origin.x,
y: far.y,
},
],
}
} else {
let slot = if id == 21 {
&self.m.polygon
} else {
&self.m.path
};
let count = required(slot.as_ref(), "point list")?.len();
if !selected {
return Ok(());
}
self.spend(192 + count * size_of::<Point>())?;
let src = if id == 21 {
&self.m.polygon
} else {
&self.m.path
};
let mut points = src
.as_ref()
.unwrap()
.iter()
.map(|p| add(origin, *p))
.collect::<Result<Vec<_>>>()?;
if id == 21 {
if points.first() == points.last() {
points.pop();
}
if points.len() < 3 {
return Err(Error::invalid("degenerate OASIS POLYGON"));
}
Element::Polygon { layer, points }
} else {
let width = required(self.m.halfwidth, "path half-width")?
.checked_mul(2)
.ok_or_else(|| Error::unsupported("OASIS width exceeds i64"))?;
let [begin, end] = self.m.path_ends;
let ends = match (
required(begin, "start path extension")?,
required(end, "end path extension")?,
) {
(EndLength::Flush, EndLength::Flush) => PathEnds::Flush,
(EndLength::HalfWidth, EndLength::HalfWidth) => PathEnds::HalfWidth,
(a, b) => PathEnds::Explicit {
begin: a.value(width / 2),
end: b.value(width / 2),
},
};
if matches!(ends, PathEnds::Flush) {
Element::Path {
layer,
points,
width,
}
} else {
Element::ExtendedPath {
layer,
points,
width,
ends,
absolute_width: false,
}
}
}
};
self.store_shape(c, elm, array)?;
Ok(())
}
fn circle(&mut self, input: &mut In) -> Result<()> {
let cell = self.cell()?;
let flags = input.byte()?;
if flags & 0xc0 != 0 {
return Err(Error::invalid("reserved OASIS CIRCLE bits set"));
}
let layer = self.m.layer.read(input, flags)?;
if flags & 32 != 0 {
self.m.radius = Some(input.uint()?);
}
let radius = required(self.m.radius, "circle radius")?;
let center = position(input, flags, 16, self.m.relative, &mut self.m.geom)?;
let array = self.read_repetition(input, flags & 4 != 0)?;
if self.selected(layer) {
self.spend(192)?;
self.store_shape(
cell,
Element::Circle {
layer,
center,
radius,
},
array,
)?;
}
Ok(())
}
fn trapezoid(&mut self, input: &mut In, id: u64) -> Result<()> {
use super::trapezoid::{Trapezoid, dimensions};
let cell = self.cell()?;
let flags = input.byte()?;
let layer = self.m.layer.read(input, flags)?;
if id == 26 && flags & 128 != 0 {
self.m.compact_trapezoid = Some(input.uint()?);
}
if flags & 64 != 0 {
self.m.width = Some(input.uint()?);
}
if flags & 32 != 0 {
self.m.height = Some(input.uint()?);
}
let trapezoid = if id == 26 {
let kind = required(self.m.compact_trapezoid, "compact trapezoid type")?;
let (width, height) = dimensions(kind, flags, self.m.width, self.m.height)?;
self.m.width = Some(width);
self.m.height = Some(height);
Trapezoid::compact(kind, width, height)?
} else {
let width = required(self.m.width, "trapezoid width")?;
let height = required(self.m.height, "trapezoid height")?;
let a = if id != 25 { input.sint()? } else { 0 };
let b = if id != 24 { input.sint()? } else { 0 };
Trapezoid::general(width, height, flags & 128 != 0, a, b)
};
let origin = position(input, flags, 16, self.m.relative, &mut self.m.geom)?;
let array = self.read_repetition(input, flags & 4 != 0)?;
let corners = trapezoid.corners(origin)?;
if self.selected(layer) {
self.spend(256)?;
let mut points = corners.to_vec();
points.dedup();
if points.first() == points.last() {
points.pop();
}
if points.len() < 3 {
return Err(Error::unsupported(
"degenerate OASIS trapezoid cannot form a polygon",
));
}
self.store_shape(cell, Element::Polygon { layer, points }, array)?;
}
Ok(())
}
fn store_shape(
&mut self,
cell: usize,
element: Element,
array: Option<Rc<Repetition>>,
) -> Result<()> {
let shape = if let Some(array) = array {
self.spend(size_of::<Element>() + repetition_bytes(&array))?;
Element::Repeated {
element: Box::new(element),
array: array.as_ref().clone(),
}
} else {
element
};
self.cells[cell].elements.push(shape);
Ok(())
}
fn block(&mut self, input: &mut In) -> Result<()> {
if input.uint()? != 0 {
return Err(Error::unsupported("unknown OASIS CBLOCK compression"));
}
let raw_size = input.count(MAX_BLOCK)?;
let comp_size = input.count(MAX_BLOCK)?;
let mut data = vec![0; comp_size];
input.bytes(&mut data)?;
let mut raw = Vec::with_capacity(raw_size + 1);
let mut decoder = Decompress::new(false);
let status = decoder
.decompress_vec(&data, &mut raw, FlushDecompress::Finish)
.map_err(|_| Error::invalid("invalid OASIS CBLOCK DEFLATE stream"))?;
if status != Status::StreamEnd
|| decoder.total_in() != comp_size as u64
|| raw.len() != raw_size
{
return Err(Error::invalid(
"OASIS CBLOCK length or termination mismatch",
));
}
let mut stream = Cursor::new(raw);
let mut inner = Input::new(&mut stream as &mut dyn BufRead);
let block_file = self.at.file;
while !inner.eof()? {
let at = Location {
file: block_file,
local: Some(inner.pos),
};
self.at = at;
let id = inner.uint().map_err(|e| at.annotate(e))?;
if matches!(id, 1 | 2 | 34) {
return Err(at.annotate(Error::invalid(
"nested CBLOCK or file boundary inside CBLOCK",
)));
}
self.record(&mut inner, id).map_err(|e| at.annotate(e))?;
}
Ok(())
}
fn finish(mut self, dbu_meters: f64) -> Result<Layout> {
self.m = Modals::default();
self.spend("LIBRARY".len())?;
let explicit = self.explicit_table_refs();
for (loc, index, at) in std::mem::take(&mut self.bindings) {
let names = if matches!(loc, Binding::Label(..)) {
&self.text_table
} else {
&self.cells_table
};
let val = names.values.get(&index).ok_or_else(|| {
at.annotate(Error::invalid(format!(
"undefined OASIS name index {index}"
)))
})?;
let n = val.len();
if n > self.remaining {
return Err(Error::unsupported(
"OASIS resolved name exceeds the configured byte budget",
));
}
self.remaining -= n;
let s = val.clone();
match loc {
Binding::Cell(c) => self.cells[c].name = s,
Binding::Target(c, i) => {
if let Element::Reference { cell, .. } = &mut self.cells[c].elements[i] {
*cell = s
}
}
Binding::Label(c, i) => {
let shape = match &mut self.cells[c].elements[i] {
Element::Repeated { element, .. } => element.as_mut(),
element => element,
};
if let Element::Text {
text,
text_reference,
..
} = shape
{
*text_reference = explicit.contains(&(6, index)).then_some(index);
*text = s
}
}
}
}
let properties = self.resolve_properties(&explicit)?;
Ok(Layout {
name: "LIBRARY".to_owned(),
dbu_meters,
properties,
layer_names: self.layer_names,
table_properties: self.table_properties,
cells: self.cells,
})
}
}
type Signature = Option<(u8, u32)>;
fn end(input: &mut In, tables: Option<Directory>) -> Result<(Signature, Directory)> {
let mut tail = [0; 255];
input.bytes(&mut tail)?;
let mut cursor = Cursor::new(&tail);
let mut r = Input::new(&mut cursor as &mut dyn BufRead);
let tables = if let Some(tables) = tables {
tables
} else {
offsets::read(&mut r)?
};
let mut pad = 0usize;
let mut shift = 0usize;
loop {
let b = r.byte()?;
if b & 127 != 0 {
if shift > 7 {
return Err(Error::invalid("oversized OASIS END padding"));
}
pad |= usize::from(b & 127) << shift;
}
if b < 128 {
break;
}
shift += 7;
}
if pad > 254 {
return Err(Error::invalid("oversized OASIS END padding"));
}
let mut discard = [0; 254];
r.bytes(&mut discard[..pad])?;
let validation = match r.uint()? {
0 => None,
ty @ (1 | 2) => {
let mut sig = [0; 4];
r.bytes(&mut sig)?;
Some((ty as u8, u32::from_le_bytes(sig)))
}
_ => return Err(Error::invalid("unknown OASIS validation scheme")),
};
if !r.eof()? || !input.eof()? {
return Err(Error::invalid("trailing data or incorrect OASIS END size"));
}
Ok((validation, tables))
}
struct Checked<R> {
inner: R,
crc: Crc,
sum: u32,
tail: Vec<u8>,
}
impl<R: Read> Read for Checked<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
if n == 0 {
return Ok(0);
}
let prefix = (self.tail.len() + n).saturating_sub(4);
let old = prefix.min(self.tail.len());
self.crc.update(&self.tail[..old]);
self.sum = self.tail[..old]
.iter()
.fold(self.sum, |a, b| a.wrapping_add(u32::from(*b)));
self.tail.drain(..old);
let k = prefix - old;
self.crc.update(&buf[..k]);
self.sum = buf[..k]
.iter()
.fold(self.sum, |a, b| a.wrapping_add(u32::from(*b)));
self.tail.extend_from_slice(&buf[k..n]);
Ok(n)
}
}
pub(crate) fn read<R: Read>(
r: R,
layers: Option<&BTreeSet<Layer>>,
max_retained_bytes: usize,
) -> Result<Layout> {
let checked = Checked {
inner: r,
crc: Crc::new(),
sum: 0,
tail: Vec::with_capacity(4),
};
let mut buffered = BufReader::new(checked);
let mut file = Input::new(&mut buffered as &mut dyn BufRead);
let (dbu_meters, tables) = (|| -> Result<_> {
let mut magic = [0; 13];
file.bytes(&mut magic)?;
if &magic != MAGIC || file.uint()? != 1 {
return Err(Error::invalid("missing OASIS magic or START"));
}
if file.string(false)? != "1.0" {
return Err(Error::unsupported("OASIS version other than 1.0"));
}
let dbu_meters = 1e-6 / file.real()?;
if !dbu_meters.is_finite() || dbu_meters <= 0.0 {
return Err(Error::invalid("invalid OASIS database unit"));
}
let tables = match file.uint()? {
0 => Some(offsets::read(&mut file)?),
1 => None,
_ => return Err(Error::invalid("invalid OASIS START offset flag")),
};
Ok((dbu_meters, tables))
})()
.map_err(|e| {
Location {
file: file.pos,
local: None,
}
.annotate(e)
})?;
let mut parser = Parser::new(layers, max_retained_bytes);
let (validation, directory) = loop {
let at = Location {
file: file.pos,
local: None,
};
if file.eof()? {
return Err(at.annotate(Error::invalid("OASIS file missing END")));
}
parser.at = at;
let id = file.uint().map_err(|e| at.annotate(e))?;
match id {
2 => break end(&mut file, tables).map_err(|e| at.annotate(e))?,
34 => parser.block(&mut file).map_err(|e| {
if parser.at.local.is_some() {
e
} else {
at.annotate(e)
}
})?,
_ => parser.record(&mut file, id).map_err(|e| at.annotate(e))?,
}
};
parser.observed.validate(directory)?;
if let Some((ty, expected)) = validation {
let actual = if ty == 1 {
buffered.get_ref().crc.sum()
} else {
buffered.get_ref().sum
};
if actual != expected {
return Err(parser
.at
.annotate(Error::invalid("OASIS validation signature mismatch")));
}
}
parser.finish(dbu_meters)
}