"""HDF5 variable-length storage accounting. Original code: CC0-1.0.""" import argparse import csv import hashlib import io import json import platform import sys import zlib from datetime import datetime, timezone from pathlib import Path import h5py import numpy as np LAYOUTS = ("vlen", "fixed", "offsets") MODES = ("repeated", "hash-text") def require(condition, message): if not condition: raise ValueError(message) def digest(records): value = hashlib.sha256() for record in records: value.update(len(record).to_bytes(8, "little")) value.update(record) return value.hexdigest() def fixture(count, maximum, mode): require(count > 0 and maximum >= 4 and maximum % 4 == 0, "invalid fixture dimensions") require(mode in MODES, "unknown content mode") values = [] for index in range(count): length = (maximum // 4, maximum // 2, maximum)[index % 3] if mode == "repeated": value = b"A" * length else: # Independent deterministic hexadecimal blocks, not a random population. value = b"".join( hashlib.sha256(f"{index}:{block}".encode("ascii")).hexdigest().encode("ascii") for block in range((length + 63) // 64) )[:length] values.append(value) return values def encode_fixed(records, width): require(width > 0, "invalid fixed width") require(all(b"\0" not in item and len(item) <= width for item in records), "fixed-width conversion would lose bytes") return np.asarray(records, dtype=f"S{width}") def decode_offsets(offsets, payload): points = [int(item) for item in offsets] require(len(points) >= 2 and points[0] == 0 and points[-1] == len(payload), "invalid offset endpoints") require(all(a <= b for a, b in zip(points, points[1:])), "nonmonotonic offsets") return [payload[a:b] for a, b in zip(points, points[1:])] def measure(records, layout, compressed, width): require(layout in LAYOUTS, "unknown layout") require(records and all(isinstance(item, bytes) and b"\0" not in item for item in records), "fixture requires non-NUL byte strings") options = {"compression": "gzip", "compression_opts": 6} if compressed else {} buffer = io.BytesIO() with h5py.File(buffer, "w", libver=("v110", "v110")) as handle: if layout == "vlen": ds = handle.create_dataset("strings", (len(records),), chunks=(64,), dtype=h5py.string_dtype("ascii"), track_times=False, **options) ds[:] = records elif layout == "fixed": handle.create_dataset("strings", data=encode_fixed(records, width), chunks=(min(64, len(records)),), track_times=False, **options) else: offsets = np.asarray([0] + list(np.cumsum([len(x) for x in records])), dtype="