use std::path::Path;
use super::column::Column;
use super::dataset::Dataset;
use super::source::{DataError, read_limited};
#[cfg(all(feature = "hdf5", feature = "threads"))]
pub fn read_hdf5(path: impl AsRef<Path>) -> Result<Dataset, DataError> {
let file = hdf5_pure::File::open(path.as_ref()).map_err(|error| DataError::Connector(error.to_string()))?;
let names = file
.root()
.datasets()
.map_err(|error| DataError::Connector(error.to_string()))?;
let mut columns = Vec::new();
for name in names {
let dataset = file
.dataset(&name)
.map_err(|error| DataError::Connector(error.to_string()))?;
let shape = dataset
.shape()
.map_err(|error| DataError::Connector(error.to_string()))?;
let values = dataset
.read_f64()
.map_err(|error| DataError::Connector(error.to_string()))?;
columns.extend(columns_from_flat(&name, &shape, values)?);
}
if columns.is_empty() {
return Err(DataError::Unsupported(
"the HDF5 file has no numeric datasets".to_owned(),
));
}
Ok(Dataset::from_columns(columns))
}
#[cfg(all(feature = "netcdf", feature = "threads"))]
pub fn read_netcdf(path: impl AsRef<Path>) -> Result<Dataset, DataError> {
let file = netcdf_reader::NcFile::open(path.as_ref()).map_err(|error| DataError::Connector(error.to_string()))?;
let variables = file
.variables()
.map_err(|error| DataError::Connector(error.to_string()))?;
let mut columns = Vec::new();
for variable in variables {
let name = variable.name();
let shape = variable.shape().to_vec();
let values = file
.read_variable_as_f64(name)
.map_err(|error| DataError::Connector(error.to_string()))?;
let values = values.iter().copied().collect::<Vec<_>>();
columns.extend(columns_from_flat(name, &shape, values)?);
}
if columns.is_empty() {
return Err(DataError::Unsupported(
"the NetCDF file has no numeric variables".to_owned(),
));
}
Ok(Dataset::from_columns(columns))
}
#[cfg(all(feature = "zarr", feature = "threads"))]
const MAX_ZARR_ELEMENTS: u64 = 50_000_000;
const MAX_ZARR_CHUNKS: u64 = 100_000;
const MAX_ZARR_CHUNK_BYTES: u64 = 64 * 1024 * 1024;
const MAX_ZARR_METADATA_BYTES: u64 = 1024 * 1024;
#[cfg(all(feature = "zarr", feature = "threads"))]
pub fn read_zarr(path: impl AsRef<Path>) -> Result<Dataset, DataError> {
let path = path.as_ref();
let metadata = read_text(&path.join(".zarray"))?;
let value: serde_json::Value =
serde_json::from_str(&metadata).map_err(|error| DataError::Connector(error.to_string()))?;
let shape = value
.get("shape")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| DataError::Unsupported("Zarr metadata has no shape".to_owned()))?
.iter()
.map(|entry| {
entry
.as_u64()
.ok_or_else(|| DataError::Unsupported("Zarr shape entries must be unsigned integers".to_owned()))
})
.collect::<Result<Vec<_>, _>>()?;
let chunks = value
.get("chunks")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| DataError::Unsupported("Zarr metadata has no chunks".to_owned()))?
.iter()
.map(|entry| {
entry
.as_u64()
.ok_or_else(|| DataError::Unsupported("Zarr chunk entries must be unsigned integers".to_owned()))
})
.collect::<Result<Vec<_>, _>>()?;
let dtype = value
.get("dtype")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| DataError::Unsupported("Zarr metadata has no dtype".to_owned()))?;
if value.get("compressor").is_some_and(|compressor| !compressor.is_null()) {
return Err(DataError::Unsupported(
"compressed Zarr arrays are not supported".to_owned(),
));
}
let separator = value
.get("dimension_separator")
.and_then(serde_json::Value::as_str)
.unwrap_or(".");
if separator != "." && separator != "/" {
return Err(DataError::Unsupported(
"Zarr dimension_separator must be `.` or `/`".to_owned(),
));
}
if shape.len() != chunks.len() || !matches!(shape.len(), 1 | 2) {
return Err(DataError::Unsupported(
"only 1D and 2D Zarr arrays are supported".to_owned(),
));
}
if chunks.iter().any(|chunk| *chunk == 0) {
return Err(DataError::Unsupported(
"Zarr chunks must be greater than zero".to_owned(),
));
}
let elements = shape
.iter()
.try_fold(1u64, |total, dimension| total.checked_mul(*dimension))
.ok_or_else(|| DataError::Unsupported("Zarr shape overflows".to_owned()))?;
if elements > MAX_ZARR_ELEMENTS {
return Err(DataError::Unsupported(format!(
"Zarr array has {elements} elements; the limit is {MAX_ZARR_ELEMENTS}"
)));
}
let chunk_count = chunks
.iter()
.zip(&shape)
.try_fold(1u64, |total, (chunk, dimension)| {
total.checked_mul(dimension.div_ceil(*chunk))
})
.ok_or_else(|| DataError::Unsupported("Zarr chunk count overflows".to_owned()))?;
if chunk_count > MAX_ZARR_CHUNKS {
return Err(DataError::Unsupported(format!(
"Zarr array has {chunk_count} chunks; the limit is {MAX_ZARR_CHUNKS}"
)));
}
let root = std::fs::canonicalize(path).map_err(|error| DataError::Connector(error.to_string()))?;
let fill = value
.get("fill_value")
.and_then(serde_json::Value::as_f64)
.unwrap_or(f64::NAN);
let width_bytes = match dtype {
"<f8" | "<i8" => 8,
"<f4" | "<i4" => 4,
other => {
return Err(DataError::Unsupported(format!("unsupported Zarr dtype `{other}`")));
}
};
let mut values = vec![fill; elements as usize];
let width = shape.last().copied().unwrap_or(1) as usize;
let chunk_width = chunks.last().copied().unwrap_or(1) as usize;
let rows = shape.first().copied().unwrap_or(1) as usize;
let chunk_rows = chunks.first().copied().unwrap_or(1) as usize;
let chunks_x = width.div_ceil(chunk_width);
let chunks_y = if shape.len() == 1 { 1 } else { rows.div_ceil(chunk_rows) };
for chunk_y in 0..chunks_y {
for chunk_x in 0..chunks_x {
let key = if shape.len() == 1 {
chunk_x.to_string()
} else {
format!("{chunk_y}{separator}{chunk_x}")
};
let Some(bytes) = read_chunk(&root, &key) else {
continue;
};
let start_x = chunk_x * chunk_width;
let start_y = chunk_y * chunk_rows;
let chunk_cols = chunk_width.min(width.saturating_sub(start_x));
let chunk_lines = if shape.len() == 1 {
1
} else {
chunk_rows.min(rows.saturating_sub(start_y))
};
for line in 0..chunk_lines {
for column in 0..chunk_cols {
let offset = (line * chunk_width + column) * width_bytes;
let Some(bytes) = bytes.get(offset..offset + width_bytes) else {
continue;
};
let value = match dtype {
"<f8" => f64::from_le_bytes(bytes.try_into().unwrap_or([0; 8])),
"<f4" => f64::from(f32::from_le_bytes(bytes.try_into().unwrap_or([0; 4]))),
"<i8" => i64::from_le_bytes(bytes.try_into().unwrap_or([0; 8])) as f64,
"<i4" => i32::from_le_bytes(bytes.try_into().unwrap_or([0; 4])) as f64,
other => {
return Err(DataError::Unsupported(format!("unsupported Zarr dtype `{other}`")));
}
};
let row = start_y + line;
let column = start_x + column;
let index = if shape.len() == 1 { column } else { row * width + column };
if let Some(slot) = values.get_mut(index) {
*slot = value;
}
}
}
}
}
Ok(Dataset::from_columns(columns_from_flat("zarr", &shape, values)?))
}
#[cfg(feature = "threads")]
fn read_text(path: &Path) -> Result<String, DataError> {
let bytes = read_limited(path)?;
if bytes.len() as u64 > MAX_ZARR_METADATA_BYTES {
return Err(DataError::Connector("Zarr metadata is too large".to_owned()));
}
String::from_utf8(bytes).map_err(|error| DataError::Connector(error.to_string()))
}
#[cfg(feature = "threads")]
fn read_chunk(root: &Path, key: &str) -> Option<Vec<u8>> {
let candidate = root.join(key);
let path = std::fs::canonicalize(candidate).ok()?;
if !path.starts_with(root) || !path.is_file() {
return None;
}
let metadata = std::fs::metadata(&path).ok()?;
if metadata.len() > MAX_ZARR_CHUNK_BYTES {
return None;
}
read_limited(path).ok()
}
fn columns_from_flat(name: &str, shape: &[u64], values: Vec<f64>) -> Result<Vec<Column>, DataError> {
match shape {
[_rows] => Ok(vec![Column::floats(name, values)]),
[rows, width] => {
let rows = *rows as usize;
let width = *width as usize;
if values.len() != rows * width {
return Err(DataError::Connector(format!("{name}: shape does not match the data")));
}
Ok((0..width)
.map(|column| {
let values = (0..rows)
.map(|row| values.get(row * width + column).copied().unwrap_or(f64::NAN))
.collect::<Vec<_>>();
Column::floats(format!("{name}[{column}]"), values)
})
.collect())
}
_ => Err(DataError::Unsupported(format!(
"dataset `{name}` has rank {}; only 1D and 2D are supported",
shape.len()
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flat_blocks_become_one_or_many_columns() {
let one = columns_from_flat("v", &[3], vec![1.0, 2.0, 3.0]).expect("1d");
assert_eq!(one.len(), 1);
let two = columns_from_flat("m", &[2, 3], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).expect("2d");
assert_eq!(two.len(), 3);
assert_eq!(two[1].name, "m[1]");
assert!(columns_from_flat("bad", &[2], vec![]).is_ok());
assert!(columns_from_flat("bad", &[1, 2, 3], vec![1.0]).is_err());
}
#[cfg(all(feature = "zarr", feature = "threads", not(target_family = "wasm")))]
#[test]
fn zarr_metadata_rejects_separator_traversal_zero_chunks_and_overflow() {
use std::path::PathBuf;
let root = std::env::temp_dir().join(format!("crisol-zarr-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("temp zarr");
let write = |shape: &str, chunks: &str, separator: &str| {
std::fs::write(
root.join(".zarray"),
format!(
r#"{{"dtype":"<f8","shape":{shape},"chunks":{chunks},"compressor":null,"fill_value":0,"dimension_separator":"{separator}"}}"#
),
)
.expect("metadata");
};
write("[2]", "[1]", "../outside");
assert!(read_zarr(&root).is_err(), "traversal separator must be rejected");
write("[2]", "[0]", ".");
assert!(read_zarr(&root).is_err(), "zero chunks must be rejected");
write("[18446744073709551615]", "[1]", ".");
assert!(read_zarr(&root).is_err(), "shape overflow must be rejected");
let _ = std::fs::remove_dir_all(PathBuf::from(root));
}
}