wbhdf 0.1.0

Scoped pure-Rust HDF container reader for Whitebox Next Gen
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
use crate::btree::{
    lookup_chunk_address, read_chunk_payload_in_file, read_chunked_storage_records_bounded_in_file,
    ChunkIndex,
};
use crate::datatypes::{
    decode_f32_slice, decode_f64_slice, decode_i16_slice, decode_u16_slice, Endianness,
};
use crate::error::{WbhdfError, WbhdfResult};
use crate::filters::decompress_zlib;
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

/// Minimal dataset descriptor used during early scaffolding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DatasetDescriptor {
    pub path: String,
}

/// Dataset-level chunk locator wiring B-tree lookup into dataset reads.
#[derive(Debug, Clone)]
pub struct DatasetChunkLocator {
    descriptor: DatasetDescriptor,
    chunk_index: ChunkIndex,
}

#[derive(Debug, Clone, PartialEq)]
pub struct FillMappedF32 {
    pub values: Vec<f32>,
    pub nodata_value: f32,
    pub valid_count: usize,
    pub nodata_count: usize,
}

/// Resolves a dataset descriptor from a canonical dataset path.
pub fn resolve_dataset(path: &str) -> WbhdfResult<DatasetDescriptor> {
    if !path.starts_with('/') {
        return Err(WbhdfError::InvalidInput(
            "dataset path must start with '/'".to_string(),
        ));
    }

    Ok(DatasetDescriptor {
        path: path.to_string(),
    })
}

/// Resolves a dataset descriptor and verifies that the path is discoverable in a container file.
pub fn resolve_dataset_in_file(container_path: &Path, dataset_path: &str) -> WbhdfResult<DatasetDescriptor> {
    let descriptor = resolve_dataset(dataset_path)?;
    let bytes = fs::read(container_path)?;

    if bytes_contain_marker(&bytes, &descriptor.path)
        || path_components_are_discoverable(&bytes, &descriptor.path)
    {
        Ok(descriptor)
    } else {
        Err(WbhdfError::DatasetPathNotFound(descriptor.path))
    }
}

/// Reads a contiguous f32 window directly from a container file at a known byte offset.
pub fn read_contiguous_f32_window_in_file(
    container_path: &Path,
    byte_offset: u64,
    element_count: usize,
    endianness: Endianness,
) -> WbhdfResult<Vec<f32>> {
    let byte_len = element_count.checked_mul(4).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "contiguous f32 window size overflow: element_count={element_count}"
        ))
    })?;

    let start = usize::try_from(byte_offset).map_err(|_| {
        WbhdfError::InvalidInput(format!(
            "contiguous f32 window offset does not fit usize: offset={byte_offset}"
        ))
    })?;
    let end = start.checked_add(byte_len).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "contiguous f32 window end overflow: offset={byte_offset}, elements={element_count}"
        ))
    })?;

    let bytes = fs::read(container_path)?;
    if end > bytes.len() {
        return Err(WbhdfError::InvalidInput(format!(
            "contiguous f32 window out of bounds: offset={byte_offset}, elements={element_count}, file_size={}",
            bytes.len()
        )));
    }

    decode_f32_slice(&bytes[start..end], endianness)
        .map_err(|err| WbhdfError::InvalidInput(format!("contiguous f32 decode failed: {err}")))
}

/// Reads a contiguous f64 window directly from a container file at a known byte offset.
pub fn read_contiguous_f64_window_in_file(
    container_path: &Path,
    byte_offset: u64,
    element_count: usize,
    endianness: Endianness,
) -> WbhdfResult<Vec<f64>> {
    let byte_len = element_count.checked_mul(8).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "contiguous f64 window size overflow: element_count={element_count}"
        ))
    })?;

    let start = usize::try_from(byte_offset).map_err(|_| {
        WbhdfError::InvalidInput(format!(
            "contiguous f64 window offset does not fit usize: offset={byte_offset}"
        ))
    })?;
    let end = start.checked_add(byte_len).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "contiguous f64 window end overflow: offset={byte_offset}, elements={element_count}"
        ))
    })?;

    let bytes = fs::read(container_path)?;
    if end > bytes.len() {
        return Err(WbhdfError::InvalidInput(format!(
            "contiguous f64 window out of bounds: offset={byte_offset}, elements={element_count}, file_size={}",
            bytes.len()
        )));
    }

    decode_f64_slice(&bytes[start..end], endianness)
        .map_err(|err| WbhdfError::InvalidInput(format!("contiguous f64 decode failed: {err}")))
}

/// Decodes a bounded i16 prefix from a chunk selected by row offset in a chunked HDF5 dataset.
///
/// This helper traverses a v1 chunk-index B-tree at `chunk_index_address`, selects the first chunk
/// whose `row_dimension_index` offset equals `row_offset`, inflates the chunk payload using zlib,
/// and decodes i16 values using the supplied endianness.
pub fn decode_chunked_i16_row_prefix_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_offset: u64,
    max_values: usize,
    endianness: Endianness,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<i16>> {
    if num_dimensions == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked i16 row-prefix decode requires num_dimensions >= 1".to_string(),
        ));
    }
    if row_dimension_index >= num_dimensions {
        return Err(WbhdfError::InvalidInput(format!(
            "row_dimension_index out of bounds: index={row_dimension_index}, num_dimensions={num_dimensions}"
        )));
    }
    if max_values == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked i16 row-prefix decode requires max_values >= 1".to_string(),
        ));
    }

    let records = read_chunked_storage_records_bounded_in_file(
        container_path,
        chunk_index_address,
        num_dimensions,
        max_leaf_nodes,
        max_records,
    )?;

    let Some(record) = records
        .iter()
        .find(|record| record.chunk_offsets[row_dimension_index] == row_offset)
    else {
        return Err(WbhdfError::InvalidChunk {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("row_dim={row_dimension_index}, row_offset={row_offset}")),
            file_offset: chunk_index_address,
            detail: "no chunk record matched requested row offset".to_string(),
        });
    };

    let compressed = read_chunk_payload_in_file(container_path, record.chunk_address, record.chunk_size)?;
    let decompressed = decompress_zlib(&compressed).map_err(|err| match err {
        WbhdfError::UnsupportedFilter(detail) => WbhdfError::FilterFailure {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
            file_offset: record.chunk_address,
            filter: "deflate/zlib".to_string(),
            detail,
        },
        other => other,
    })?;

    let mut values = decode_i16_slice(&decompressed, endianness).map_err(|detail| WbhdfError::InvalidChunk {
        dataset_path: dataset_path.to_string(),
        chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
        file_offset: record.chunk_address,
        detail: format!("chunk i16 decode failed: {detail}"),
    })?;

    if values.len() > max_values {
        values.truncate(max_values);
    }
    Ok(values)
}

/// Decodes a bounded row-major 2D i16 window from a chunked HDF5 dataset.
///
/// This helper currently targets products where each chunk resolves to one logical row of i16
/// values (e.g. VNP13 NDVI/EVI/EVI2). It composes row slices by repeatedly resolving row chunks
/// and extracting `[col_start, col_start + col_count)` from each decoded row.
pub fn decode_chunked_i16_row_major_window_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_start: u64,
    row_count: usize,
    col_start: usize,
    col_count: usize,
    row_width: usize,
    endianness: Endianness,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<i16>> {
    if row_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked i16 row-major window decode requires row_count >= 1".to_string(),
        ));
    }
    if col_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked i16 row-major window decode requires col_count >= 1".to_string(),
        ));
    }
    if row_width == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked i16 row-major window decode requires row_width >= 1".to_string(),
        ));
    }
    let col_end = col_start.checked_add(col_count).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked i16 row-major window column end overflow: col_start={col_start}, col_count={col_count}"
        ))
    })?;
    if col_end > row_width {
        return Err(WbhdfError::InvalidInput(format!(
            "chunked i16 row-major window exceeds row width: col_start={col_start}, col_count={col_count}, row_width={row_width}"
        )));
    }

    let mut out = Vec::<i16>::with_capacity(row_count.saturating_mul(col_count));
    for row_delta in 0..row_count {
        let row_offset = row_start
            .checked_add(row_delta as u64)
            .ok_or_else(|| WbhdfError::InvalidInput("row offset overflow".to_string()))?;

        let row_values = decode_chunked_i16_row_prefix_in_file(
            container_path,
            dataset_path,
            chunk_index_address,
            num_dimensions,
            row_dimension_index,
            row_offset,
            row_width,
            endianness,
            max_leaf_nodes,
            max_records,
        )?;

        if row_values.len() < col_end {
            return Err(WbhdfError::InvalidChunk {
                dataset_path: dataset_path.to_string(),
                chunk_coordinate: Some(format!("row_dim={row_dimension_index}, row_offset={row_offset}")),
                file_offset: chunk_index_address,
                detail: format!(
                    "decoded row too short for requested window: decoded_len={}, col_end={col_end}",
                    row_values.len()
                ),
            });
        }

        out.extend_from_slice(&row_values[col_start..col_end]);
    }

    Ok(out)
}

/// Decodes a bounded u16 prefix from a chunk selected by row offset in a chunked HDF5 dataset.
pub fn decode_chunked_u16_row_prefix_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_offset: u64,
    max_values: usize,
    endianness: Endianness,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<u16>> {
    if num_dimensions == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u16 row-prefix decode requires num_dimensions >= 1".to_string(),
        ));
    }
    if row_dimension_index >= num_dimensions {
        return Err(WbhdfError::InvalidInput(format!(
            "row_dimension_index out of bounds: index={row_dimension_index}, num_dimensions={num_dimensions}"
        )));
    }
    if max_values == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u16 row-prefix decode requires max_values >= 1".to_string(),
        ));
    }

    let records = read_chunked_storage_records_bounded_in_file(
        container_path,
        chunk_index_address,
        num_dimensions,
        max_leaf_nodes,
        max_records,
    )?;

    let Some(record) = records
        .iter()
        .find(|record| record.chunk_offsets[row_dimension_index] == row_offset)
    else {
        return Err(WbhdfError::InvalidChunk {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("row_dim={row_dimension_index}, row_offset={row_offset}")),
            file_offset: chunk_index_address,
            detail: "no chunk record matched requested row offset".to_string(),
        });
    };

    let compressed = read_chunk_payload_in_file(container_path, record.chunk_address, record.chunk_size)?;
    let decompressed = decompress_zlib(&compressed).map_err(|err| match err {
        WbhdfError::UnsupportedFilter(detail) => WbhdfError::FilterFailure {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
            file_offset: record.chunk_address,
            filter: "deflate/zlib".to_string(),
            detail,
        },
        other => other,
    })?;

    let mut values = decode_u16_slice(&decompressed, endianness).map_err(|detail| WbhdfError::InvalidChunk {
        dataset_path: dataset_path.to_string(),
        chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
        file_offset: record.chunk_address,
        detail: format!("chunk u16 decode failed: {detail}"),
    })?;

    if values.len() > max_values {
        values.truncate(max_values);
    }
    Ok(values)
}

/// Decodes a bounded row-major 2D u16 window from a chunked HDF5 dataset.
pub fn decode_chunked_u16_row_major_window_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_start: u64,
    row_count: usize,
    col_start: usize,
    col_count: usize,
    row_width: usize,
    chunk_row_height: usize,
    endianness: Endianness,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<u16>> {
    if row_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u16 row-major window decode requires row_count >= 1".to_string(),
        ));
    }
    if col_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u16 row-major window decode requires col_count >= 1".to_string(),
        ));
    }
    if row_width == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u16 row-major window decode requires row_width >= 1".to_string(),
        ));
    }
    if chunk_row_height == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u16 row-major window decode requires chunk_row_height >= 1".to_string(),
        ));
    }
    let col_end = col_start.checked_add(col_count).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked u16 row-major window column end overflow: col_start={col_start}, col_count={col_count}"
        ))
    })?;
    if col_end > row_width {
        return Err(WbhdfError::InvalidInput(format!(
            "chunked u16 row-major window exceeds row width: col_start={col_start}, col_count={col_count}, row_width={row_width}"
        )));
    }

    let chunk_values = row_width.checked_mul(chunk_row_height).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked u16 row-major window chunk value count overflow: row_width={row_width}, chunk_row_height={chunk_row_height}"
        ))
    })?;

    let mut chunk_cache = BTreeMap::<u64, Vec<u16>>::new();
    let mut out = Vec::<u16>::with_capacity(row_count.saturating_mul(col_count));
    for row_delta in 0..row_count {
        let absolute_row = row_start
            .checked_add(row_delta as u64)
            .ok_or_else(|| WbhdfError::InvalidInput("row offset overflow".to_string()))?;

        let chunk_row_base = (absolute_row / chunk_row_height as u64) * chunk_row_height as u64;
        let chunk_rows = if let Some(values) = chunk_cache.get(&chunk_row_base) {
            values
        } else {
            let values = decode_chunked_u16_row_prefix_in_file(
                container_path,
                dataset_path,
                chunk_index_address,
                num_dimensions,
                row_dimension_index,
                chunk_row_base,
                chunk_values,
                endianness,
                max_leaf_nodes,
                max_records,
            )?;
            chunk_cache.insert(chunk_row_base, values);
            chunk_cache
                .get(&chunk_row_base)
                .expect("inserted chunk row should be retrievable")
        };

        let local_row = (absolute_row - chunk_row_base) as usize;
        let row_value_start = local_row.checked_mul(row_width).ok_or_else(|| {
            WbhdfError::InvalidInput(format!(
                "chunked u16 row-major window row start overflow: local_row={local_row}, row_width={row_width}"
            ))
        })?;
        let row_value_end = row_value_start.checked_add(row_width).ok_or_else(|| {
            WbhdfError::InvalidInput(format!(
                "chunked u16 row-major window row end overflow: row_start={row_value_start}, row_width={row_width}"
            ))
        })?;

        if chunk_rows.len() < row_value_end {
            return Err(WbhdfError::InvalidChunk {
                dataset_path: dataset_path.to_string(),
                chunk_coordinate: Some(format!(
                    "row_dim={row_dimension_index}, chunk_row_base={chunk_row_base}, absolute_row={absolute_row}"
                )),
                file_offset: chunk_index_address,
                detail: format!(
                    "decoded chunk too short for requested row: decoded_len={}, required_end={row_value_end}",
                    chunk_rows.len()
                ),
            });
        }

        let row_slice = &chunk_rows[row_value_start..row_value_end];
        out.extend_from_slice(&row_slice[col_start..col_end]);
    }

    Ok(out)
}

/// Decodes a bounded u8 prefix from a chunk selected by row offset in a chunked HDF5 dataset.
pub fn decode_chunked_u8_row_prefix_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_offset: u64,
    max_values: usize,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<u8>> {
    if num_dimensions == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u8 row-prefix decode requires num_dimensions >= 1".to_string(),
        ));
    }
    if row_dimension_index >= num_dimensions {
        return Err(WbhdfError::InvalidInput(format!(
            "row_dimension_index out of bounds: index={row_dimension_index}, num_dimensions={num_dimensions}"
        )));
    }
    if max_values == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u8 row-prefix decode requires max_values >= 1".to_string(),
        ));
    }

    let records = read_chunked_storage_records_bounded_in_file(
        container_path,
        chunk_index_address,
        num_dimensions,
        max_leaf_nodes,
        max_records,
    )?;

    let Some(record) = records
        .iter()
        .find(|record| record.chunk_offsets[row_dimension_index] == row_offset)
    else {
        return Err(WbhdfError::InvalidChunk {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("row_dim={row_dimension_index}, row_offset={row_offset}")),
            file_offset: chunk_index_address,
            detail: "no chunk record matched requested row offset".to_string(),
        });
    };

    let compressed = read_chunk_payload_in_file(container_path, record.chunk_address, record.chunk_size)?;
    let mut decompressed = decompress_zlib(&compressed).map_err(|err| match err {
        WbhdfError::UnsupportedFilter(detail) => WbhdfError::FilterFailure {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
            file_offset: record.chunk_address,
            filter: "deflate/zlib".to_string(),
            detail,
        },
        other => other,
    })?;

    if decompressed.len() > max_values {
        decompressed.truncate(max_values);
    }
    Ok(decompressed)
}

/// Decodes a bounded row-major 2D u8 window from a chunked HDF5 dataset.
pub fn decode_chunked_u8_row_major_window_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_start: u64,
    row_count: usize,
    col_start: usize,
    col_count: usize,
    row_width: usize,
    chunk_row_height: usize,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<u8>> {
    if row_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u8 row-major window decode requires row_count >= 1".to_string(),
        ));
    }
    if col_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u8 row-major window decode requires col_count >= 1".to_string(),
        ));
    }
    if row_width == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u8 row-major window decode requires row_width >= 1".to_string(),
        ));
    }
    if chunk_row_height == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked u8 row-major window decode requires chunk_row_height >= 1".to_string(),
        ));
    }
    let col_end = col_start.checked_add(col_count).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked u8 row-major window column end overflow: col_start={col_start}, col_count={col_count}"
        ))
    })?;
    if col_end > row_width {
        return Err(WbhdfError::InvalidInput(format!(
            "chunked u8 row-major window exceeds row width: col_start={col_start}, col_count={col_count}, row_width={row_width}"
        )));
    }

    let chunk_values = row_width.checked_mul(chunk_row_height).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked u8 row-major window chunk value count overflow: row_width={row_width}, chunk_row_height={chunk_row_height}"
        ))
    })?;

    let mut chunk_cache = BTreeMap::<u64, Vec<u8>>::new();
    let mut out = Vec::<u8>::with_capacity(row_count.saturating_mul(col_count));
    for row_delta in 0..row_count {
        let absolute_row = row_start
            .checked_add(row_delta as u64)
            .ok_or_else(|| WbhdfError::InvalidInput("row offset overflow".to_string()))?;

        let chunk_row_base = (absolute_row / chunk_row_height as u64) * chunk_row_height as u64;
        let chunk_rows = if let Some(values) = chunk_cache.get(&chunk_row_base) {
            values
        } else {
            let values = decode_chunked_u8_row_prefix_in_file(
                container_path,
                dataset_path,
                chunk_index_address,
                num_dimensions,
                row_dimension_index,
                chunk_row_base,
                chunk_values,
                max_leaf_nodes,
                max_records,
            )?;
            chunk_cache.insert(chunk_row_base, values);
            chunk_cache
                .get(&chunk_row_base)
                .expect("inserted chunk row should be retrievable")
        };

        let local_row = (absolute_row - chunk_row_base) as usize;
        let row_value_start = local_row.checked_mul(row_width).ok_or_else(|| {
            WbhdfError::InvalidInput(format!(
                "chunked u8 row-major window row start overflow: local_row={local_row}, row_width={row_width}"
            ))
        })?;
        let row_value_end = row_value_start.checked_add(row_width).ok_or_else(|| {
            WbhdfError::InvalidInput(format!(
                "chunked u8 row-major window row end overflow: row_start={row_value_start}, row_width={row_width}"
            ))
        })?;

        if chunk_rows.len() < row_value_end {
            return Err(WbhdfError::InvalidChunk {
                dataset_path: dataset_path.to_string(),
                chunk_coordinate: Some(format!(
                    "row_dim={row_dimension_index}, chunk_row_base={chunk_row_base}, absolute_row={absolute_row}"
                )),
                file_offset: chunk_index_address,
                detail: format!(
                    "decoded chunk too short for requested row: decoded_len={}, required_end={row_value_end}",
                    chunk_rows.len()
                ),
            });
        }

        let row_slice = &chunk_rows[row_value_start..row_value_end];
        out.extend_from_slice(&row_slice[col_start..col_end]);
    }

    Ok(out)
}

/// Decodes a bounded f32 prefix from a chunk selected by row offset in a chunked HDF5 dataset.
pub fn decode_chunked_f32_row_prefix_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_offset: u64,
    max_values: usize,
    endianness: Endianness,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<f32>> {
    if num_dimensions == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked f32 row-prefix decode requires num_dimensions >= 1".to_string(),
        ));
    }
    if row_dimension_index >= num_dimensions {
        return Err(WbhdfError::InvalidInput(format!(
            "row_dimension_index out of bounds: index={row_dimension_index}, num_dimensions={num_dimensions}"
        )));
    }
    if max_values == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked f32 row-prefix decode requires max_values >= 1".to_string(),
        ));
    }

    let records = read_chunked_storage_records_bounded_in_file(
        container_path,
        chunk_index_address,
        num_dimensions,
        max_leaf_nodes,
        max_records,
    )?;

    let Some(record) = records
        .iter()
        .find(|record| record.chunk_offsets[row_dimension_index] == row_offset)
    else {
        return Err(WbhdfError::InvalidChunk {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("row_dim={row_dimension_index}, row_offset={row_offset}")),
            file_offset: chunk_index_address,
            detail: "no chunk record matched requested row offset".to_string(),
        });
    };

    let compressed = read_chunk_payload_in_file(container_path, record.chunk_address, record.chunk_size)?;
    let decompressed = decompress_zlib(&compressed).map_err(|err| match err {
        WbhdfError::UnsupportedFilter(detail) => WbhdfError::FilterFailure {
            dataset_path: dataset_path.to_string(),
            chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
            file_offset: record.chunk_address,
            filter: "deflate/zlib".to_string(),
            detail,
        },
        other => other,
    })?;

    let mut values = decode_f32_slice(&decompressed, endianness).map_err(|detail| WbhdfError::InvalidChunk {
        dataset_path: dataset_path.to_string(),
        chunk_coordinate: Some(format!("{:?}", record.chunk_offsets)),
        file_offset: record.chunk_address,
        detail: format!("chunk f32 decode failed: {detail}"),
    })?;

    if values.len() > max_values {
        values.truncate(max_values);
    }
    Ok(values)
}

/// Decodes a bounded row-major 2D f32 window from a chunked HDF5 dataset.
pub fn decode_chunked_f32_row_major_window_in_file(
    container_path: &Path,
    dataset_path: &str,
    chunk_index_address: u64,
    num_dimensions: usize,
    row_dimension_index: usize,
    row_start: u64,
    row_count: usize,
    col_start: usize,
    col_count: usize,
    row_width: usize,
    chunk_row_height: usize,
    endianness: Endianness,
    max_leaf_nodes: usize,
    max_records: usize,
) -> WbhdfResult<Vec<f32>> {
    if row_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked f32 row-major window decode requires row_count >= 1".to_string(),
        ));
    }
    if col_count == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked f32 row-major window decode requires col_count >= 1".to_string(),
        ));
    }
    if row_width == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked f32 row-major window decode requires row_width >= 1".to_string(),
        ));
    }
    if chunk_row_height == 0 {
        return Err(WbhdfError::InvalidInput(
            "chunked f32 row-major window decode requires chunk_row_height >= 1".to_string(),
        ));
    }
    let col_end = col_start.checked_add(col_count).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked f32 row-major window column end overflow: col_start={col_start}, col_count={col_count}"
        ))
    })?;
    if col_end > row_width {
        return Err(WbhdfError::InvalidInput(format!(
            "chunked f32 row-major window exceeds row width: col_start={col_start}, col_count={col_count}, row_width={row_width}"
        )));
    }

    let chunk_values = row_width.checked_mul(chunk_row_height).ok_or_else(|| {
        WbhdfError::InvalidInput(format!(
            "chunked f32 row-major window chunk value count overflow: row_width={row_width}, chunk_row_height={chunk_row_height}"
        ))
    })?;

    let mut chunk_cache = BTreeMap::<u64, Vec<f32>>::new();
    let mut out = Vec::<f32>::with_capacity(row_count.saturating_mul(col_count));
    for row_delta in 0..row_count {
        let absolute_row = row_start
            .checked_add(row_delta as u64)
            .ok_or_else(|| WbhdfError::InvalidInput("row offset overflow".to_string()))?;

        let chunk_row_base = (absolute_row / chunk_row_height as u64) * chunk_row_height as u64;
        let chunk_rows = if let Some(values) = chunk_cache.get(&chunk_row_base) {
            values
        } else {
            let values = decode_chunked_f32_row_prefix_in_file(
                container_path,
                dataset_path,
                chunk_index_address,
                num_dimensions,
                row_dimension_index,
                chunk_row_base,
                chunk_values,
                endianness,
                max_leaf_nodes,
                max_records,
            )?;
            chunk_cache.insert(chunk_row_base, values);
            chunk_cache
                .get(&chunk_row_base)
                .expect("inserted chunk row should be retrievable")
        };

        let local_row = (absolute_row - chunk_row_base) as usize;
        let row_value_start = local_row.checked_mul(row_width).ok_or_else(|| {
            WbhdfError::InvalidInput(format!(
                "chunked f32 row-major window row start overflow: local_row={local_row}, row_width={row_width}"
            ))
        })?;
        let row_value_end = row_value_start.checked_add(row_width).ok_or_else(|| {
            WbhdfError::InvalidInput(format!(
                "chunked f32 row-major window row end overflow: row_start={row_value_start}, row_width={row_width}"
            ))
        })?;

        if chunk_rows.len() < row_value_end {
            return Err(WbhdfError::InvalidChunk {
                dataset_path: dataset_path.to_string(),
                chunk_coordinate: Some(format!(
                    "row_dim={row_dimension_index}, chunk_row_base={chunk_row_base}, absolute_row={absolute_row}"
                )),
                file_offset: chunk_index_address,
                detail: format!(
                    "decoded chunk too short for requested row: decoded_len={}, required_end={row_value_end}",
                    chunk_rows.len()
                ),
            });
        }

        let row_slice = &chunk_rows[row_value_start..row_value_end];
        out.extend_from_slice(&row_slice[col_start..col_end]);
    }

    Ok(out)
}

fn bytes_contain_marker(bytes: &[u8], marker: &str) -> bool {
    bytes
        .windows(marker.len())
        .any(|window| window == marker.as_bytes())
}

fn path_components_are_discoverable(bytes: &[u8], dataset_path: &str) -> bool {
    dataset_path
        .split('/')
        .filter(|component| !component.is_empty())
        .all(|component| bytes_contain_marker(bytes, component))
}

impl DatasetChunkLocator {
    /// Constructs a locator from known key -> chunk address mappings.
    pub fn with_known_addresses(
        dataset_path: &str,
        key_to_address: &[(u64, u64)],
    ) -> WbhdfResult<Self> {
        let descriptor = resolve_dataset(dataset_path)?;
        let mut chunk_index = ChunkIndex::new(&descriptor.path);

        for (key, address) in key_to_address {
            chunk_index.insert(*key, *address);
        }

        Ok(Self {
            descriptor,
            chunk_index,
        })
    }

    /// Locates the chunk address for the supplied dataset coordinates.
    pub fn locate_chunk_address(&self, coords: &[u64]) -> WbhdfResult<u64> {
        lookup_chunk_address(&self.chunk_index, &self.descriptor.path, coords)
    }

    /// Returns the dataset path bound to this locator.
    pub fn dataset_path(&self) -> &str {
        &self.descriptor.path
    }
}

/// Applies deterministic fill-value to nodata mapping for f32 payloads.
pub fn apply_fill_value_mapping_f32(
    values: &[f32],
    fill_value: Option<f32>,
    nodata_value: f32,
) -> FillMappedF32 {
    let mut mapped = Vec::with_capacity(values.len());
    let mut valid_count = 0usize;
    let mut nodata_count = 0usize;

    match fill_value {
        Some(fill) => {
            let fill_bits = fill.to_bits();
            for value in values {
                if value.to_bits() == fill_bits {
                    mapped.push(nodata_value);
                    nodata_count += 1;
                } else {
                    mapped.push(*value);
                    valid_count += 1;
                }
            }
        }
        None => {
            mapped.extend_from_slice(values);
            valid_count = values.len();
        }
    }

    FillMappedF32 {
        values: mapped,
        nodata_value,
        valid_count,
        nodata_count,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        apply_fill_value_mapping_f32, read_contiguous_f32_window_in_file,
        read_contiguous_f64_window_in_file, resolve_dataset_in_file, DatasetChunkLocator,
    };
    use crate::datatypes::Endianness;
    use std::fs;

    #[test]
    fn locator_returns_known_addresses() {
        let locator = DatasetChunkLocator::with_known_addresses(
            "/GEDI04_B/BEAM0000/rh100",
            &[(0, 4000), (1, 4500), (2, 5000)],
        )
        .expect("locator should construct");

        assert_eq!(locator.dataset_path(), "/GEDI04_B/BEAM0000/rh100");
        assert_eq!(locator.locate_chunk_address(&[0]).unwrap(), 4000);
        assert_eq!(locator.locate_chunk_address(&[2]).unwrap(), 5000);
    }

    #[test]
    fn locator_reports_missing_known_key() {
        let locator = DatasetChunkLocator::with_known_addresses(
            "/GEDI04_B/BEAM0000/rh100",
            &[(3, 7000)],
        )
        .expect("locator should construct");

        let err = locator.locate_chunk_address(&[1]).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("chunk address not found"));
    }

    #[test]
    fn resolve_dataset_in_file_finds_dataset_marker() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-dataset-marker-test.h5");
        fs::write(&file_path, b"prefix /gt1l/heights/h_canopy suffix").unwrap();

        let descriptor = resolve_dataset_in_file(&file_path, "/gt1l/heights/h_canopy").unwrap();
        assert_eq!(descriptor.path, "/gt1l/heights/h_canopy");

        let _ = fs::remove_file(file_path);
    }

    #[test]
    fn resolve_dataset_in_file_reports_missing_marker() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-dataset-missing-test.h5");
        fs::write(&file_path, b"prefix /gt1l/heights/other suffix").unwrap();

        let err = resolve_dataset_in_file(&file_path, "/gt1l/heights/h_canopy").unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("dataset path not found"));

        let _ = fs::remove_file(file_path);
    }

    #[test]
    fn resolve_dataset_in_file_accepts_split_path_markers() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-dataset-split-test.h5");
        fs::write(
            &file_path,
            b"gt1l something land_segments something canopy something h_canopy",
        )
        .unwrap();

        let descriptor = resolve_dataset_in_file(&file_path, "/gt1l/land_segments/canopy/h_canopy")
            .unwrap();
        assert_eq!(descriptor.path, "/gt1l/land_segments/canopy/h_canopy");

        let _ = fs::remove_file(file_path);
    }

    #[test]
    fn fill_mapping_replaces_fill_values_and_reports_counts() {
        let mapped = apply_fill_value_mapping_f32(
            &[1.0, f32::MAX, 2.0, f32::MAX],
            Some(f32::MAX),
            -9999.0,
        );

        assert_eq!(mapped.values, vec![1.0, -9999.0, 2.0, -9999.0]);
        assert_eq!(mapped.valid_count, 2);
        assert_eq!(mapped.nodata_count, 2);
    }

    #[test]
    fn fill_mapping_without_fill_definition_keeps_values_valid() {
        let mapped = apply_fill_value_mapping_f32(&[1.0, 2.0, 3.0], None, -9999.0);

        assert_eq!(mapped.values, vec![1.0, 2.0, 3.0]);
        assert_eq!(mapped.valid_count, 3);
        assert_eq!(mapped.nodata_count, 0);
    }

    #[test]
    fn read_contiguous_f32_window_decodes_little_endian_values() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-contiguous-f32-window-test.bin");
        fs::write(
            &file_path,
            [
                0u8, 0, 128, 63, // 1.0
                0, 0, 0, 64, // 2.0
                0, 0, 64, 64, // 3.0
            ],
        )
        .unwrap();

        let values =
            read_contiguous_f32_window_in_file(&file_path, 4, 2, Endianness::Little).unwrap();
        assert_eq!(values, vec![2.0, 3.0]);

        let _ = fs::remove_file(file_path);
    }

    #[test]
    fn read_contiguous_f32_window_reports_bounds_errors() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-contiguous-f32-window-bounds-test.bin");
        fs::write(&file_path, [0u8, 0, 128, 63]).unwrap();

        let err =
            read_contiguous_f32_window_in_file(&file_path, 4, 1, Endianness::Little).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("out of bounds"));

        let _ = fs::remove_file(file_path);
    }

    #[test]
    fn read_contiguous_f64_window_decodes_little_endian_values() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-contiguous-f64-window-test.bin");
        fs::write(
            &file_path,
            [
                0u8, 0, 0, 0, 0, 0, 240, 63, // 1.0
                0, 0, 0, 0, 0, 0, 0, 64, // 2.0
                0, 0, 0, 0, 0, 0, 8, 64, // 3.0
            ],
        )
        .unwrap();

        let values =
            read_contiguous_f64_window_in_file(&file_path, 8, 2, Endianness::Little).unwrap();
        assert_eq!(values, vec![2.0, 3.0]);

        let _ = fs::remove_file(file_path);
    }

    #[test]
    fn read_contiguous_f64_window_reports_bounds_errors() {
        let temp_dir = std::env::temp_dir();
        let file_path = temp_dir.join("wbhdf-contiguous-f64-window-bounds-test.bin");
        fs::write(&file_path, [0u8, 0, 0, 0, 0, 0, 240, 63]).unwrap();

        let err =
            read_contiguous_f64_window_in_file(&file_path, 8, 1, Endianness::Little).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("out of bounds"));

        let _ = fs::remove_file(file_path);
    }
}