mod legacy;
#[cfg(test)]
mod tests;
mod xml;
use serde_json::{Value, json};
use super::Input;
use super::cells::{self, Array, BAD, Cells, Cursor, Kind, Model, Piece, Points, Role};
use super::stream;
use crate::document::Document;
use crate::num::f32_of;
use crate::{Context as _, ErrorKind, Result};
const MAX_FIELD_VALUES: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Ty {
Bit,
I8,
U8,
I16,
U16,
I32,
U32,
I64,
U64,
F32,
F64,
}
impl Ty {
fn size(self) -> usize {
match self {
Ty::Bit | Ty::I8 | Ty::U8 => 1,
Ty::I16 | Ty::U16 => 2,
Ty::I32 | Ty::U32 | Ty::F32 => 4,
Ty::I64 | Ty::U64 | Ty::F64 => 8,
}
}
}
#[allow(
clippy::cast_precision_loss,
reason = "attributes are single precision; whole numbers past 2^24 round"
)]
fn wide(x: i64) -> f32 {
x as f32
}
#[allow(
clippy::cast_precision_loss,
reason = "attributes are single precision; whole numbers past 2^24 round"
)]
fn wide_unsigned(x: u64) -> f32 {
x as f32
}
macro_rules! decode {
($b:expr, $big:expr, $n:literal, $t:ty, $f:expr) => {{
let (chunks, _) = $b.as_chunks::<$n>();
if $big {
chunks.iter().map(|&c| $f(<$t>::from_be_bytes(c))).collect()
} else {
chunks.iter().map(|&c| $f(<$t>::from_le_bytes(c))).collect()
}
}};
}
fn floats_of(b: &[u8], ty: Ty, big: bool) -> Vec<f32> {
match ty {
Ty::Bit | Ty::U8 => b.iter().map(|&x| f32::from(x)).collect(),
Ty::I8 => b.iter().map(|&x| f32::from(x.cast_signed())).collect(),
Ty::I16 => decode!(b, big, 2, i16, f32::from),
Ty::U16 => decode!(b, big, 2, u16, f32::from),
Ty::I32 => decode!(b, big, 4, i32, |x| wide(i64::from(x))),
Ty::U32 => decode!(b, big, 4, u32, |x| wide(i64::from(x))),
Ty::I64 => decode!(b, big, 8, i64, wide),
Ty::U64 => decode!(b, big, 8, u64, wide_unsigned),
Ty::F32 => decode!(b, big, 4, f32, |x| x),
Ty::F64 => decode!(b, big, 8, f64, f32_of),
}
}
fn ids_of(b: &[u8], ty: Ty, big: bool) -> Vec<u32> {
fn id<T: TryInto<u32>>(x: T) -> u32 {
x.try_into().unwrap_or(BAD)
}
match ty {
Ty::Bit | Ty::U8 => b.iter().map(|&x| u32::from(x)).collect(),
Ty::I8 => b.iter().map(|&x| id(x.cast_signed())).collect(),
Ty::I16 => decode!(b, big, 2, i16, id),
Ty::U16 => decode!(b, big, 2, u16, u32::from),
Ty::I32 => decode!(b, big, 4, i32, id),
Ty::U32 => decode!(b, big, 4, u32, |x| x),
Ty::I64 => decode!(b, big, 8, i64, id),
Ty::U64 => decode!(b, big, 8, u64, id),
Ty::F32 | Ty::F64 => vec![BAD; b.len() / ty.size()],
}
}
fn packed(b: &[u8], n: usize) -> Vec<u8> {
(0..n).map(|i| (b[i / 8] >> (7 - i % 8)) & 1).collect()
}
fn check_dims(dims: [u32; 3]) -> Result<()> {
let points = dims.iter().try_fold(1u64, |n, &d| n.checked_mul(u64::from(d)));
ensure!(
dims.iter().all(|&d| d >= 1),
Corrupt,
"VTK dimensions {dims:?} have a zero"
);
ensure!(
points.is_some_and(|n| n < u64::from(BAD)),
LimitExceeded,
"VTK dimensions {dims:?} are too many points"
);
Ok(())
}
pub(crate) fn load(input: Input<'_>) -> Result<Document> {
let data = input.read()?;
let data = data.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&data);
let start = data.iter().position(|&b| !stream::space(b)).unwrap_or(data.len());
let model = match data.get(start) {
Some(b'<' | 0xFE | 0xFF) => xml::read(data)?,
Some(b'#') => legacy::read(data)?,
Some(_) => bail!(UnknownFormat, "not a VTK file"),
None => bail!(Empty, "VTK file is empty"),
};
cells::build(model, "VTK", input.limit)
}
fn field_note(values: &[f32]) -> Option<Value> {
(!values.is_empty() && values.len() <= MAX_FIELD_VALUES).then(|| {
let list: Vec<Value> = values
.iter()
.map(|&v| if v.is_finite() { json!(v) } else { Value::Null })
.collect();
Value::Array(list)
})
}
fn count(token: Option<&[u8]>, what: &str) -> Result<usize> {
token
.and_then(stream::int::<usize>)
.with_context(ErrorKind::Corrupt, || format!("VTK {what} count is missing"))
}