read chunked datasets straight into the typed output

read_f32/read_f64/read_i32/read_i64/read_u64 of a chunked dataset that
stores exactly that type in native byte order now decode every chunk
straight into the Vec<T> they return (data_read::read_chunked_native),
on File (through its chunk cache), MmapFile and LazyFile. Before, the
chunks went into a byte buffer that read_as_* then copied into a second,
typed one: two dataset-sized allocations and a full extra copy per read.
The output is zeroed pages from the allocator, backed by transparent
huge pages when large, like the byte reader's. Other types and byte
orders, and datasets with no storage or external data, keep converting
through the byte readers; unallocated chunks read as the fill value as
before.

tests/chunked_read_paths_interop.rs checks every chunked read path
(File twice, so cached; from_bytes; MmapFile; LazyFile; small, strided
and point selections; with and without the parallel feature) against
h5py for 1-8 byte integers and 2-8 byte floats in both byte orders,
through deflate, shuffle, Fletcher32, LZF, SZIP and Blosc, with partial
edge chunks, sparse datasets with default and non-default fill values,
and datasets larger than the chunk cache. A filter this build lacks must
be an error (or, when an optional filter declined every chunk, the right
data).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
osobh
2026-09-26 10:18:29 -05:00
co-authored by Claude Opus 5.5
parent f0db817678
commit 9e9b849dd7
5 changed files with 602 additions and 0 deletions
+114
View File
@@ -756,6 +756,120 @@ pub fn read_selection_native<T: NativeElement>(
crate::gather::gather::<T>(raw, dims, elem_size, selection).map(Some)
}
/// The bytes of a slice of [`NativeElement`]s.
#[cfg(feature = "std")]
fn bytes_of_mut<T: NativeElement>(values: &mut [T]) -> &mut [u8] {
// SAFETY: `T: NativeElement` has no padding and every bit pattern is a
// valid value, so its storage may be viewed, and written, as bytes; the
// byte slice covers exactly the values' storage and borrows it
// exclusively for its lifetime.
unsafe {
core::slice::from_raw_parts_mut(
values.as_mut_ptr().cast::<u8>(),
core::mem::size_of_val(values),
)
}
}
/// `count` zeroed values of `T`, from zeroed pages where the allocator can
/// (see [`crate::chunked_read::alloc_output`]) and backed by huge pages when
/// large. A size taken from the file surfaces as an error, not an abort.
#[cfg(feature = "std")]
fn alloc_zeroed_values<T: NativeElement>(count: usize) -> Result<Vec<T>, FormatError> {
if count == 0 || core::mem::size_of::<T>() == 0 {
return Ok(Vec::new());
}
let failed = || {
FormatError::Overflow(format!(
"cannot allocate {count} values of {} bytes for dataset output",
core::mem::size_of::<T>()
))
};
let layout = core::alloc::Layout::array::<T>(count).map_err(|_| failed())?;
// SAFETY: `layout` has non-zero size (count > 0, T not zero-sized).
let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
if ptr.is_null() {
return Err(failed());
}
crate::bulk_alloc::advise_huge_pages(ptr, layout.size());
// SAFETY: allocated by the global allocator with the layout of
// `[T; count]`, which is what `Vec<T>` with capacity `count` frees; all
// bytes are zero, a valid `T` (`NativeElement`: any bit pattern is).
Ok(unsafe { Vec::from_raw_parts(ptr.cast::<T>(), count, count) })
}
/// Read a whole chunked dataset that stores `T` natively
/// ([`NativeElement::is_native`]) straight into a `Vec<T>`: each chunk is
/// decoded and copied to its place in the typed output, with no byte buffer
/// to convert from afterwards. Unallocated chunks read as the dataset's fill
/// value, as [`crate::fill_value::read_full_with_fill`] makes them.
///
/// `Ok(None)` when this does not apply — the datatype is not `T`'s native
/// representation (another type, another byte order: the caller converts
/// through the byte readers and the `read_as_*` functions), the layout is
/// not chunked, no storage is allocated, or the data lives in external
/// files. `cache` is the file's chunk cache, used as
/// [`crate::chunked_read::read_chunked_data_cached`] uses it.
#[cfg(feature = "std")]
#[allow(clippy::too_many_arguments)]
pub fn read_chunked_native<T: NativeElement>(
messages: &[crate::object_header::HeaderMessage],
file_data: &[u8],
layout: &DataLayout,
dataspace: &Dataspace,
datatype: &Datatype,
pipeline: Option<&FilterPipeline>,
offset_size: u8,
length_size: u8,
cache: Option<&ChunkCache>,
) -> Result<Option<Vec<T>>, FormatError> {
use crate::fill_value;
use crate::message_type::MessageType;
if !T::is_native(datatype)
|| !matches!(layout, DataLayout::Chunked { .. })
|| !fill_value::has_storage(layout)
|| messages
.iter()
.any(|m| m.msg_type == MessageType::ExternalDataFiles)
{
return Ok(None);
}
let size = core::mem::size_of::<T>();
let mut values = crate::chunked_read::read_chunked_full(
file_data,
layout,
dataspace,
datatype,
pipeline,
offset_size,
length_size,
cache,
|total_bytes| {
if !total_bytes.is_multiple_of(size) {
return Err(FormatError::DataSizeMismatch {
expected: total_bytes.next_multiple_of(size),
actual: total_bytes,
});
}
alloc_zeroed_values::<T>(total_bytes / size)
},
|values| bytes_of_mut(values),
)?;
let fill = fill_value::dataset_fill_value_in(file_data, messages, offset_size, length_size)?;
fill_value::apply_to_unallocated_chunks(
bytes_of_mut(&mut values),
file_data,
layout,
dataspace,
size,
fill.as_deref(),
offset_size,
length_size,
)?;
Ok(Some(values))
}
/// Convert raw bytes to `f64` values.
pub fn read_as_f64(raw: &[u8], datatype: &Datatype) -> Result<Vec<f64>, FormatError> {
// Array datatypes read as a flat sequence of their base elements, and