moon-nrrd

    Pure MoonBit NRRD read-write library: NRRD0005 header parse, data decode, symmetric serialization (10 numeric types incl. int64/uint64 lossless, raw LE/BE + ASCII, attached/detached/LIST), crop/slice data ops with spatial metadata updates

    nrrd
    nhdr
    scientific
    imaging
    voxel
    grid
    teem
    parse
    encode
    Download zip
    Version
    0.3.0
    License
    Apache-2.0
    Last updated
    5 hours ago
    Downloads
    35

    #moon-nrrd

    Pure MoonBit NRRD read-write library. Parses NRRD0005 headers and decodes data payloads, and symmetrically serializes headers with encoded payloads. Values ≤32-bit are exchanged as Double in file linear order (sizes[0] = fastest axis); 64-bit integers use native Int64 / UInt64 (no Double intermediary). The core layer performs no file IO — assembly APIs return bytes and strings only.

    #Current scope (v0.2)

    • Types: int8 / uint8 / int16 / uint16 / int32 / uint32 / float / double via Double carrier; int64 / uint64 via native decode_int64 / decode_uint64 / encode_int64 / encode_uint64 (raw LE/BE + ascii, lossless round-trip verified for 2^53+1, INT64_MIN/MAX, UINT64_MAX)
    • Encodings: raw (little/big endian), ascii; attached / detached / LIST multi-file data files
    • Read: strict magic line match (NRRD0005 only); standard fields normalized by alias/case and unique (duplicates rejected); key:=value custom keys follow the spec (last value wins)
    • LIST multi-file: data file: LIST [subdim] — per-chunk validation (raw byte count / ascii token count), boundary-safe concatenation, missing file and size mismatch rejection
    • Write: format_header / encode_data / assemble_attached / assemble_detached (no IO, symmetric attached/detached output, NRRD0005); format_keyval_line provides spec-escaped key:=value tooling
    • Data ops: crop_data / crop_meta (dimension-preserving crop with real value subset, space origin shifted) and slice_data / slice_meta (dimension-reducing slice with real value subset), both updating spatial metadata consistently (Double-carrier values; 64-bit data ops planned)
    • Write strings are ASCII-only (v1 contract): non-ASCII code points are rejected with NrrdError, never silently truncated (prevents header injection)
    • float32 semantics: stored value is the nearest binary32 (ties-to-even); ASCII special-value detection applies to the narrowed stored value (negative underflow like -1.0e-50 emits "-0.0", not "0")

    #Verified scope quick reference

    Use the installed MoonBit toolchain. Run from the repository root:

    # 1. LIST sharding reassembly (raw + ascii, 12/12) # default subdim, explicit subdim, slabs, missing file, # wrong chunk size/count, no-trailing-newline boundary moon test --target js list_test.mbt # 2. int64/uint64 lossless round-trip (20/20) # raw LE/BE + ascii; 2^53+1, INT64_MIN, INT64_MAX, UINT64_MAX moon test --target js int64_test.mbt

    Full suite: moon test --target js (281/281); moon test --target wasm (281/281); moon check --deny-warn clean.

    #Planned (not yet implemented)

    • world-coordinate API (world = origin + Σ idx·dir)
    • 64-bit integer data ops (crop_data / slice_data on Int64/UInt64 arrays)
    • LIST / format-sequence multi-file writing
    • unknown-field and key:=value round-trip preservation

    #Known limitations

    • ASCII float32 decimal parsing is decimal → binary32 direct correct rounding (nearest, ties-to-even, single final rounding — no binary64 intermediate step); correctly rounded for all decimal tokens up to 64 bytes
    • ASCII numeric token length capped at 64 bytes (implementation limit, not spec)
    • Compression (hex/gzip/bzip2/block), format-sequence multi-file, and line/byte skip are explicitly rejected (planned for stage B)
    • NaN payload/signaling bits are not preserved (semantic nan==nan only)

    #Usage

    // Parse a header + data from bytes
    let hdr = @moon-nrrd.parse_header(buf)?
    let data = @moon-nrrd.decode_data(buf, hdr)?

    // Serialize
    let header_str = @moon-nrrd.format_header(hdr)?
    let payload = @moon-nrrd.encode_data(data, hdr)?
    let attached = @moon-nrrd.assemble_attached(hdr, payload)?

    #License

    Apache-2.0

    #Reference

    NrrdError

    pub(all) suberror NrrdError {
    NrrdError(String)
    }
    Errors from NRRD header parsing and data decoding.

    NrrdData

    pub(all) struct NrrdData {
    header : NrrdHeader
    values : Array[Double]
    }
    Dataset = header + values in file linear order.

    NrrdHeader

    pub(all) struct NrrdHeader {
    dimension : Int
    sizes : Array[Int]
    type_name : String
    encoding : String
    endian : String?
    data_file : String?
    space : String?
    space_dimension : Int?
    space_origin : Array[Double]?
    space_directions : Array[Array[Double]?]
    space_units : Array[String]?
    labels : Array[String]?
    kinds : Array[String]?
    content : String?
    line_skip : Int
    byte_skip : Int
    list_filenames : Array[String]?
    data_file_subdim : Int?
    }

    ascii_to_bytes

    fn ascii_to_bytes(s : String) -> Bytes raise NrrdError
    UTF-16 traversal (missing code units raise instead).

    assemble_attached

    fn assemble_attached(h : NrrdHeader, values : Array[Double], budget? : Int) -> Bytes raise NrrdError
    No file IO — the caller decides the file name and writes bytes.

    assemble_detached

    fn assemble_detached(h : NrrdHeader, values : Array[Double], budget? : Int) -> (Bytes, Bytes) raise NrrdError
    with the terminating blank line, like an attached header.

    bytes_to_ascii

    fn bytes_to_ascii(b : Bytes) -> String
    real file bytes; NRRD headers are ASCII by specification.)

    crop_data

    fn crop_data(d : NrrdData, start : Array[Int], size : Array[Int], budget? : Int) -> NrrdData raise NrrdError
    The input NrrdData and its arrays are never mutated.

    crop_meta

    fn crop_meta(h : NrrdHeader, start : Array[Int], size : Array[Int]) -> NrrdHeader raise NrrdError
    basic fields and are NOT modified by crop.

    decode_data

    fn decode_data(data : Bytes, header : NrrdHeader, budget? : Int) -> Array[Double] raise NrrdError
    illegality judgment (see README.md).

    decode_int64

    fn decode_int64(data : Bytes, header : NrrdHeader, budget? : Int) -> Array[Int64] raise NrrdError
    Supports raw (little/big endian) and ascii encodings.

    decode_uint64

    fn decode_uint64(data : Bytes, header : NrrdHeader, budget? : Int) -> Array[UInt64] raise NrrdError
    Supports raw (little/big endian) and ascii encodings.

    encode_data

    fn encode_data(values : Array[Double], header : NrrdHeader, budget? : Int) -> Bytes raise NrrdError
    out-of-range values (G2 v2 §7.1).

    encode_int64

    fn encode_int64(values : Array[Int64], header : NrrdHeader, budget? : Int) -> Bytes raise NrrdError
    Supports raw (little/big endian) and ascii.

    encode_uint64

    fn encode_uint64(values : Array[UInt64], header : NrrdHeader, budget? : Int) -> Bytes raise NrrdError
    Supports raw (little/big endian) and ascii.

    format_directions

    fn format_directions(rows : Array[Array[Double]?]) -> String
    space directions rows joined with " | "; none for non-spatial axes.

    format_double_list

    fn format_double_list(ds : Array[Double]) -> String

    format_float

    fn format_float(d : Double) -> String
    Print a float-typed value: "nan" / "+inf" / "-inf" / "1000.0" / "1.5".

    format_header

    fn format_header(h : NrrdHeader) -> String raise NrrdError
    replayed here.

    format_int_value

    fn format_int_value(d : Double) -> String
    Print an integer-typed value without decimal point ("1000").

    format_keyval_line

    fn format_keyval_line(key : String, value : String) -> String raise NrrdError
    library is unsupported (see module doc).

    format_opt

    fn format_opt(v : String?, none_marker? : String) -> String

    format_string_list

    fn format_string_list(ss : Array[String]) -> String

    is_list_header

    fn is_list_header(h : NrrdHeader) -> Bool
    True when the header uses the LIST form of data file.

    list_subdim

    fn list_subdim(h : NrrdHeader) -> Int
    Effective subdim: explicit data_file_subdim or default D-1.

    list_values_per_file

    fn list_values_per_file(h : NrrdHeader, nfiles : Int) -> Int raise NrrdError
    values per file = total / nfiles.

    normalize_encoding

    fn normalize_encoding(e : String) -> String raise NrrdError
    Normalize an encoding descriptor to its canonical short name.

    normalize_type

    fn normalize_type(t : String) -> String raise NrrdError
    Normalize a type descriptor to its canonical short name.

    nrrd_item_size

    fn nrrd_item_size(t : String) -> Int raise NrrdError
    so the reassembly layer can pre-check chunk sizes.

    parse_header

    fn parse_header(text : String) -> NrrdHeader raise NrrdError
    any field: desc line after it is rejected.

    parse_uint64_str

    fn parse_uint64_str(s : String) -> UInt64?
    leading '+'. Returns None for empty/invalid input.

    reassemble_list_data

    fn reassemble_list_data(chunks : Array[Bytes], h : NrrdHeader) -> Bytes raise NrrdError
    or any layout error.

    slice_data

    fn slice_data(d : NrrdData, axis : Int, index : Int, budget? : Int) -> NrrdData raise NrrdError
    The input NrrdData and its arrays are never mutated.

    slice_meta

    fn slice_meta(h : NrrdHeader, axis : Int, index : Int) -> NrrdHeader raise NrrdError
    index · direction[axis]; a none direction does not move origin.

    split_header_body

    fn split_header_body(data : Bytes) -> (Bytes, Bytes) raise NrrdError
    time when the body is empty but values are expected.

    validate_header

    fn validate_header(h : NrrdHeader) -> Unit raise NrrdError
    policy for incomplete spatial info — decision C).