use std::{
cell::RefCell,
io::{BufReader, Read},
path::Path,
rc::Rc,
};
use npyz::{DType, NpyFile, Order, TypeChar};
use crate::{
data::{RawKey, RawKeyValues},
Result,
};
use super::{
super::{bindings::BindingObject, codec::invalid},
text::rectangle,
};
pub(super) fn npy<'a>(reader: impl Read) -> Result<BindingObject<'a>> {
let npy = NpyFile::new(reader)?;
let dtype = npy.dtype();
let DType::Plain(kind) = dtype else {
return Err(invalid(
"structured NumPy dtype is not an admitted value array",
));
};
if !matches!(npy.shape(), [_] | [_, _]) {
return Err(invalid("NumPy input must have rank one or two"));
}
let shape = npy
.shape()
.iter()
.map(|&extent| {
usize::try_from(extent).map_err(|_| invalid("NumPy extent exceeds native shape range"))
})
.collect::<Result<Vec<_>>>()?;
let count = shape
.iter()
.try_fold(1usize, |count, &axis| count.checked_mul(axis))
.ok_or_else(|| invalid("NumPy shape exceeds native element count"))?;
let fortran = npy.order() == Order::Fortran;
let numeric = matches!(
kind.type_char(),
TypeChar::Float | TypeChar::Int | TypeChar::Uint
);
macro_rules! read {
($type:ty, $convert:expr) => {{
let reader = npy
.data::<$type>()
.map_err(|error| invalid(format!("NumPy dtype: {error}")))?;
let mut values = Vec::new();
crate::data::source::reserve_source(&mut values, count)?;
for value in reader {
crate::operation::check()?;
values.push(Some(($convert)(value?)));
}
values
}};
}
let values = match (kind.type_char(), kind.size_field()) {
(TypeChar::Float, 2) => read!(half::f16, |value| RawKey::Float(f64::from(value))),
(TypeChar::Float, 4) => read!(f32, |value| RawKey::Float(f64::from(value))),
(TypeChar::Float, 8) => read!(f64, RawKey::Float),
(TypeChar::Int, 1) => read!(i8, |value: i8| RawKey::Integer(value.into())),
(TypeChar::Int, 2) => read!(i16, |value: i16| RawKey::Integer(value.into())),
(TypeChar::Int, 4) => read!(i32, |value: i32| RawKey::Integer(value.into())),
(TypeChar::Int, 8) => read!(i64, |value: i64| RawKey::Integer(value.into())),
(TypeChar::Uint, 1) => read!(u8, |value: u8| RawKey::Integer(value.into())),
(TypeChar::Uint, 2) => read!(u16, |value: u16| RawKey::Integer(value.into())),
(TypeChar::Uint, 4) => read!(u32, |value: u32| RawKey::Integer(value.into())),
(TypeChar::Uint, 8) => read!(u64, |value: u64| RawKey::Integer(value.into())),
(TypeChar::Bool, 1) => read!(bool, RawKey::Boolean),
(TypeChar::UnicodeStr, _) => read!(String, RawKey::String),
_ => return Err(invalid(format!("unsupported NumPy value dtype {kind:?}"))),
};
match shape.as_slice() {
[_] => RawKeyValues::nullable("value", values)
.map(|values| BindingObject::keys(values, numeric)),
[rows, columns] => rectangle(*rows, *columns, &values, fortran, Some(numeric), &[]),
_ => unreachable!("validated NumPy rank"),
}
}
pub(super) fn npz<'a>(path: &Path) -> Result<BindingObject<'a>> {
let archive =
zip::ZipArchive::new(BufReader::new(std::fs::File::open(path)?)).map_err(zip_error)?;
let archive = Rc::new(RefCell::new(archive));
let mut fields = Vec::new();
let mut names = std::collections::HashSet::new();
{
let mut archive_ref = archive.borrow_mut();
for index in 0..archive_ref.len() {
crate::operation::check()?;
let file = archive_ref.by_index_raw(index).map_err(zip_error)?;
let Some(key) = file.name().strip_suffix(".npy") else {
continue;
};
if file.is_dir() || key.is_empty() {
continue;
}
if !names.insert(key.to_owned()) {
return Err(invalid(format!("duplicate NumPy archive key {key:?}")));
}
let key = RawKey::from(key);
let archive = Rc::clone(&archive);
let value = BindingObject::deferred(move || {
let mut archive = archive.borrow_mut();
let file = archive.by_index(index).map_err(zip_error)?;
let mut file = BufReader::new(file);
let values = npy(&mut file)?;
let mut extra = [0_u8; 1];
if file.read(&mut extra)? != 0 {
return Err(invalid("trailing bytes in NumPy archive member"));
}
Ok(values)
});
fields.push((key, value));
}
}
Ok(BindingObject::members(fields))
}
fn zip_error(error: zip::result::ZipError) -> crate::Error {
match error {
zip::result::ZipError::Io(error) => crate::Error::Io(error),
error => invalid(format!("NPZ: {error}")),
}
}