use super::{MAX_POINTS, MAX_STRING, ORIGIN};
use crate::{Error, Point, Result};
use std::io::BufRead;
pub(super) struct Input<R> {
pub inner: R,
pub pos: u64,
}
impl<R: BufRead> Input<R> {
pub fn new(inner: R) -> Self {
Self { inner, pos: 0 }
}
pub fn eof(&mut self) -> Result<bool> {
Ok(self.inner.fill_buf()?.is_empty())
}
pub fn bytes(&mut self, buf: &mut [u8]) -> Result<()> {
self.inner.read_exact(buf)?;
self.pos += buf.len() as u64;
Ok(())
}
pub fn byte(&mut self) -> Result<u8> {
let mut buf = [0];
self.bytes(&mut buf)?;
Ok(buf[0])
}
fn var(&mut self) -> Result<u128> {
let mut number = 0u128;
for shift in (0..70).step_by(7) {
let b = self.byte()?;
number |= u128::from(b & 127) << shift;
if b < 128 {
return Ok(number);
}
}
Err(Error::invalid("overlong OASIS integer"))
}
pub fn uint(&mut self) -> Result<u64> {
self.var()?
.try_into()
.map_err(|_| Error::invalid("OASIS unsigned integer overflows u64"))
}
pub fn unsigned_coord(&mut self) -> Result<i64> {
coord(i128::from(self.uint()?))
}
pub fn count(&mut self, max: usize) -> Result<usize> {
let n = self.uint()?;
if n > max as u64 {
return Err(Error::unsupported(format!(
"OASIS count {n} exceeds limit {max}"
)));
}
Ok(n as usize)
}
pub fn blob(&mut self) -> Result<Vec<u8>> {
let mut bytes = vec![0; self.count(MAX_STRING)?];
self.bytes(&mut bytes)?;
Ok(bytes)
}
pub fn string(&mut self, name: bool) -> Result<String> {
let bytes = self.blob()?;
if !legal_string(&bytes, name) {
return Err(Error::invalid("invalid OASIS name or text characters"));
}
Ok(String::from_utf8(bytes).expect("ASCII was verified"))
}
pub fn sint(&mut self) -> Result<i64> {
signed(self.var()?)
}
pub fn real(&mut self) -> Result<f64> {
let t = self.uint()?;
self.real_payload(t)
}
pub fn real_payload(&mut self, t: u64) -> Result<f64> {
let value = match t {
0..=5 => {
let first = self.uint()? as f64;
let abs = match t {
0 | 1 => first,
2 | 3 => 1.0 / first,
_ => first / (self.uint()? as f64),
};
if t % 2 == 1 { -abs } else { abs }
}
6 => {
let mut b = [0; 4];
self.bytes(&mut b)?;
f32::from_le_bytes(b) as f64
}
7 => {
let mut b = [0; 8];
self.bytes(&mut b)?;
f64::from_le_bytes(b)
}
_ => return Err(Error::invalid("invalid OASIS real type")),
};
if !value.is_finite() {
return Err(Error::invalid("non-finite OASIS real"));
}
Ok(value)
}
pub fn delta(&mut self) -> Result<Point> {
let n = self.var()?;
if n & 1 == 0 {
direction(n >> 1, 3)
} else {
Ok(Point {
x: signed(n >> 1)?,
y: self.sint()?,
})
}
}
pub fn points(&mut self, polygon: bool, retained_bytes: usize) -> Result<Vec<Point>> {
let kind = self.uint()?;
if kind > 5 {
return Err(Error::invalid("unknown OASIS point-list type"));
}
let implicit = 1 + usize::from(polygon && kind <= 1);
let count = self.count(MAX_POINTS - implicit)?;
if (count + implicit) * size_of::<Point>() > retained_bytes {
return Err(Error::unsupported(
"OASIS modal point list exceeds the configured byte budget",
));
}
let mut out = Vec::with_capacity(count + implicit);
let mut point = ORIGIN;
let mut previous_delta = ORIGIN;
out.push(point);
for i in 0..count {
let d = match kind {
0 | 1 => {
let v = self.sint()?;
if (i + kind as usize).is_multiple_of(2) {
Point { x: v, y: 0 }
} else {
Point { x: 0, y: v }
}
}
2 => direction(self.var()?, 2)?,
3 => direction(self.var()?, 3)?,
4 => self.delta()?,
_ => {
previous_delta = add(previous_delta, self.delta()?)?;
previous_delta
}
};
point = add(point, d)?;
out.push(point);
}
if polygon && kind <= 1 {
if count % 2 != 0 {
return Err(Error::invalid("odd OASIS alternating polygon delta count"));
}
out.push(if kind == 0 {
Point { x: 0, y: point.y }
} else {
Point { x: point.x, y: 0 }
});
}
if out.len() < if polygon { 3 } else { 2 } {
return Err(Error::invalid("too few OASIS vertices"));
}
Ok(out)
}
}
pub(crate) fn legal_string(bytes: &[u8], name: bool) -> bool {
(!name || !bytes.is_empty())
&& bytes
.iter()
.all(|b| ((if name { 33 } else { 32 })..=126).contains(b))
}
pub(super) fn coord(x: i128) -> Result<i64> {
x.try_into()
.map_err(|_| Error::invalid("OASIS coordinate overflows i64"))
}
fn signed(encoded: u128) -> Result<i64> {
let abs = (encoded >> 1) as i128;
coord(if encoded & 1 != 0 { -abs } else { abs })
}
fn direction(encoded: u128, bits: u32) -> Result<Point> {
let length = (encoded >> bits) as i128;
let (x, y) = [
(1, 0),
(0, 1),
(-1, 0),
(0, -1),
(1, 1),
(-1, 1),
(-1, -1),
(1, -1),
][(encoded & ((1 << bits) - 1)) as usize];
Ok(Point {
x: coord(x * length)?,
y: coord(y * length)?,
})
}
pub(super) fn add(a: Point, b: Point) -> Result<Point> {
Ok(Point {
x: coord(i128::from(a.x) + i128::from(b.x))?,
y: coord(i128::from(a.y) + i128::from(b.y))?,
})
}