use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::value::Array;
pub const SUPERBLOCK: usize = 96;
pub const GROUP_HEADER: usize = 40;
pub const HEAP_HEADER: usize = 32;
pub const SNOD_PREFIX: usize = 8;
pub const SNOD_ENTRY: usize = 40;
pub const BTREE_INTERNAL_K: usize = 16;
pub fn align8(n: usize) -> usize {
(n + 7) & !7
}
pub fn btree_size(k: usize) -> usize {
24 + (2 * k + 1) * 8 + (2 * k) * 8
}
pub enum Node<'a> {
Group(Group<'a>),
Dataset(Dataset<'a>),
}
pub struct Group<'a> {
pub children: Vec<(String, Node<'a>)>,
pub leaf_k: usize,
pub header: u64,
pub heap: u64,
pub heap_data: u64,
pub heap_size: usize,
pub btree: u64,
pub snod: u64,
pub name_offsets: Vec<usize>,
pub sentinel: usize,
}
pub struct Dataset<'a> {
pub array: &'a Array,
pub dtype: DType,
pub shape: Vec<usize>,
pub header: u64,
pub header_size: usize,
pub data: u64,
pub data_size: usize,
}
pub fn datatype_size(dt: &DType) -> Result<usize> {
Ok(match dt {
DType::Bool
| DType::I8
| DType::I16
| DType::I32
| DType::I64
| DType::U8
| DType::U16
| DType::U32
| DType::U64 => 12,
DType::F16 | DType::F32 | DType::F64 => 20,
DType::Bytes(_) | DType::Str(_) => 8,
other => {
return Err(Error::unsupported(format!(
"writing `{other:?}` to HDF5; cast to an integer, float or byte-string dtype first"
)))
}
})
}
pub fn dataset_header_size(dt: &DType, rank: usize) -> Result<usize> {
let esz = dt.size().ok_or_else(|| Error::unsupported("variable-size HDF5 dtype"))?;
let dataspace = 8 + 8 * rank;
let datatype = datatype_size(dt)?;
let fill = 2 + 4 + esz;
let layout = 18;
Ok(16 + [dataspace, datatype, fill, layout].iter().map(|s| 8 + align8(*s)).sum::<usize>())
}
pub fn plan_heap(names: &[String]) -> (usize, Vec<usize>, usize) {
let mut offsets = Vec::with_capacity(names.len());
let mut cursor = 8usize;
for n in names {
offsets.push(cursor);
cursor += align8(n.len() + 1);
}
let sentinel = cursor;
cursor += 8; (cursor, offsets, sentinel)
}