lerc-reader 0.5.0

Pure-Rust decoder for the LERC raster compression format
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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]

//! Pure-Rust LERC decoder.
//!
//! The public API distinguishes strict single-blob entry points from
//! concatenated-band helpers:
//!
//! - inspect a single blob with [`get_blob_info`]
//! - inspect only the first blob with [`inspect_first`]
//! - pass an explicit shared or external mask with the `*_with_mask` single-blob variants
//! - count concatenated blobs with [`get_band_count`]
//! - decode a single blob with [`decode`]
//! - decode only the first blob with [`decode_first`]
//! - decode concatenated band sets with [`decode_band_set`]
//! - seed a first-band external mask with the band-set `*_with_mask` variants
//! - decode promoted `f64` buffers with [`decode_to_f64`]
//! - decode only the first promoted `f64` blob with [`decode_first_to_f64`]
//! - decode directly into `ndarray::ArrayD` with the default `ndarray` feature

mod allocation;
mod bitstuff;
mod huffman;
mod io;
mod lerc1;
mod lerc2;
mod materialize;
mod pixel;
mod stream;
mod types;

#[cfg(test)]
mod test_support;
#[cfg(test)]
mod tests;

use lerc_core::{BandLayout, BandSetInfo, BlobInfo, DataType, Error, Result};
use materialize::BandSink;
#[cfg(feature = "rayon")]
use materialize::{copy_band_values_into_slice, PixelDataWriter};
#[cfg(feature = "ndarray")]
use ndarray::ArrayD;
#[cfg(feature = "rayon")]
use rayon::prelude::*;

use crate::allocation::default_vec;
use crate::pixel::Sample;
#[cfg(feature = "ndarray")]
pub use crate::types::NdArrayElement;
pub use crate::types::{BandElement, BandElementKind, Decoded, DecodedBandSet, DecodedF64};

/// Controls optional work performed while inspecting a blob.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct InspectOptions {
    /// Whether Lerc1 blocks are decoded far enough to compute their exact value range.
    pub compute_value_range: bool,
}

impl InspectOptions {
    /// Creates options that preserve the exact-range behavior of [`inspect_first`].
    pub const fn new() -> Self {
        Self {
            compute_value_range: true,
        }
    }

    /// Enables or disables exact Lerc1 value-range computation.
    pub const fn with_compute_value_range(mut self, compute_value_range: bool) -> Self {
        self.compute_value_range = compute_value_range;
        self
    }
}

impl Default for InspectOptions {
    fn default() -> Self {
        Self::new()
    }
}

macro_rules! dispatch_band_element {
    ($target:ty, |$concrete:ident| $body:block) => {
        match <$target as BandElement>::KIND {
            BandElementKind::I8 => {
                type $concrete = i8;
                $body
            }
            BandElementKind::U8 => {
                type $concrete = u8;
                $body
            }
            BandElementKind::I16 => {
                type $concrete = i16;
                $body
            }
            BandElementKind::U16 => {
                type $concrete = u16;
                $body
            }
            BandElementKind::I32 => {
                type $concrete = i32;
                $body
            }
            BandElementKind::U32 => {
                type $concrete = u32;
                $body
            }
            BandElementKind::F32 => {
                type $concrete = f32;
                $body
            }
            BandElementKind::F64 => {
                type $concrete = f64;
                $body
            }
        }
    };
}

/// Inspects the first blob and computes exact Lerc1 value ranges.
///
/// # Errors
/// Returns an error when the first blob is malformed or unsupported.
pub fn inspect_first(blob: &[u8]) -> Result<BlobInfo> {
    inspect_first_with_options(blob, InspectOptions::default())
}

/// Inspects the first blob with configurable Lerc1 range computation.
///
/// # Errors
/// Returns an error when the first blob is malformed or unsupported.
pub fn inspect_first_with_options(blob: &[u8], options: InspectOptions) -> Result<BlobInfo> {
    if lerc1::is_lerc1(blob) {
        return lerc1::inspect_with_mask_options(blob, None, options.compute_value_range)
            .map(|(info, _)| info);
    }
    if lerc2::is_lerc2(blob) {
        return lerc2::inspect(blob, None);
    }
    Err(Error::InvalidMagic)
}

/// Inspects the first blob using `mask` when it omits its own validity mask.
///
/// # Errors
/// Returns an error for malformed input or a mismatched external mask.
pub fn inspect_first_with_mask(blob: &[u8], mask: &[u8]) -> Result<BlobInfo> {
    let (info, _) = inspect_first_mask_with_info(blob, Some(mask), Some(mask))?;
    Ok(info)
}

/// Strictly inspects one blob and rejects trailing bytes.
///
/// # Errors
/// Returns an error for malformed input or any trailing data.
pub fn get_blob_info(blob: &[u8]) -> Result<BlobInfo> {
    let info = inspect_first(blob)?;
    ensure_single_blob_consumed(blob.len(), info.blob_size, "get_blob_info", "inspect_first")?;
    Ok(info)
}

/// Strictly inspects one externally masked blob and rejects trailing bytes.
///
/// # Errors
/// Returns an error for malformed input, a mismatched mask, or trailing data.
pub fn get_blob_info_with_mask(blob: &[u8], mask: &[u8]) -> Result<BlobInfo> {
    let info = inspect_first_with_mask(blob, mask)?;
    ensure_single_blob_consumed(
        blob.len(),
        info.blob_size,
        "get_blob_info_with_mask",
        "inspect_first_with_mask",
    )?;
    Ok(info)
}

/// Counts validated blobs in a concatenated band payload.
///
/// # Errors
/// Returns an error if any blob boundary, header, or inherited mask is invalid.
pub fn get_band_count(blob: &[u8]) -> Result<usize> {
    let mut offset = 0usize;
    let mut count = 0usize;
    let mut lerc1_mask: Option<Vec<u8>> = None;
    let mut lerc2_mask: Option<Vec<u8>> = None;
    let mut declared_band_count: Option<usize> = None;

    while offset < blob.len() {
        if declared_band_count == Some(count) {
            return Err(Error::invalid_blob(
                "Lerc2 v6 remaining-band count is smaller than the payload",
            ));
        }
        let slice = &blob[offset..];
        let info = if lerc1::is_lerc1(slice) {
            let parsed = lerc1::parse(slice, lerc1_mask.as_deref())?;
            lerc1_mask = parsed.mask;
            lerc2_mask = None;
            parsed.info
        } else if lerc2::is_lerc2(slice) {
            let (info, mask) = lerc2::inspect_with_mask(slice, lerc2_mask.as_deref())?;
            lerc2_mask = mask;
            lerc1_mask = None;
            info
        } else {
            return Err(Error::InvalidMagic);
        };

        if matches!(info.version, lerc_core::Version::Lerc2(version) if version >= 6) {
            let declared = count
                .checked_add(1)
                .and_then(|count| count.checked_add(info.remaining_band_count as usize))
                .ok_or(Error::SizeOverflow("declared Lerc2 band count"))?;
            if declared_band_count.is_some_and(|previous| previous != declared) {
                return Err(Error::invalid_blob(
                    "Lerc2 v6 headers disagree about the remaining-band count",
                ));
            }
            declared_band_count = Some(declared);
        }

        offset = checked_next_offset(offset, info.blob_size, blob.len())?;
        count += 1;
    }

    if declared_band_count.is_some_and(|declared| declared != count) {
        return Err(Error::invalid_blob(
            "Lerc2 v6 remaining-band count exceeds the payload",
        ));
    }
    Ok(count)
}

/// Decodes the first blob and permits trailing bytes.
///
/// # Errors
/// Returns an error when the first blob is malformed or unsupported.
pub fn decode_first(blob: &[u8]) -> Result<Decoded> {
    decode_first_with_masks(blob, None, None)
}

/// Decodes the first blob with an initial external mask and permits trailing bytes.
///
/// # Errors
/// Returns an error for malformed input or a mismatched mask.
pub fn decode_first_with_mask(blob: &[u8], mask: &[u8]) -> Result<Decoded> {
    decode_first_with_masks(blob, Some(mask), Some(mask))
}

/// Strictly decodes exactly one blob into its native sample type.
///
/// # Errors
/// Returns an error for malformed input, unsupported features, or trailing bytes.
pub fn decode(blob: &[u8]) -> Result<Decoded> {
    let decoded = decode_first(blob)?;
    ensure_single_blob_consumed(blob.len(), decoded.info.blob_size, "decode", "decode_first")?;
    Ok(decoded)
}

/// Strictly decodes one blob with an initial external mask.
///
/// # Errors
/// Returns an error for malformed input, a mismatched mask, or trailing bytes.
pub fn decode_with_mask(blob: &[u8], mask: &[u8]) -> Result<Decoded> {
    let decoded = decode_first_with_mask(blob, mask)?;
    ensure_single_blob_consumed(
        blob.len(),
        decoded.info.blob_size,
        "decode_with_mask",
        "decode_first_with_mask",
    )?;
    Ok(decoded)
}

/// Reads and decodes exactly one blob, leaving subsequent stream bytes unread.
///
/// # Errors
/// Returns an error for I/O failure, truncation, or invalid encoded data.
pub fn decode_from_reader<R: std::io::Read + ?Sized>(reader: &mut R) -> Result<Decoded> {
    let blob = read_required_stream_blob(reader, None)?;
    decode(&blob)
}

/// Reads and decodes one blob with an initial external mask.
///
/// # Errors
/// Returns an error for I/O failure, truncation, invalid data, or a mismatched mask.
pub fn decode_from_reader_with_mask<R: std::io::Read + ?Sized>(
    reader: &mut R,
    mask: &[u8],
) -> Result<Decoded> {
    let blob = read_required_stream_blob(reader, Some(mask))?;
    decode_with_mask(&blob, mask)
}

/// Decodes every concatenated blob as a native-typed band set.
///
/// # Errors
/// Returns an error if any band is invalid or band shapes disagree.
pub fn decode_band_set(blob: &[u8]) -> Result<DecodedBandSet> {
    decode_band_set_with_lerc2_mask(blob, None)
}

/// Decodes a band set, seeding the first blob with an external mask.
///
/// # Errors
/// Returns an error for invalid blobs, masks, or mismatched band shapes.
pub fn decode_band_set_with_mask(blob: &[u8], mask: &[u8]) -> Result<DecodedBandSet> {
    decode_band_set_with_lerc2_mask(blob, Some(mask))
}

/// Reads concatenated blobs through clean EOF and decodes them as a band set.
///
/// # Errors
/// Returns an error for I/O failure, truncation, invalid blobs, or mismatched shapes.
pub fn decode_band_set_from_reader<R: std::io::Read + ?Sized>(
    reader: &mut R,
) -> Result<DecodedBandSet> {
    decode_band_set_from_reader_impl(reader, None)
}

/// Streams a band set through EOF with an initial external mask.
///
/// # Errors
/// Returns an error for I/O failure, invalid data, masks, or band shapes.
pub fn decode_band_set_from_reader_with_mask<R: std::io::Read + ?Sized>(
    reader: &mut R,
    mask: &[u8],
) -> Result<DecodedBandSet> {
    decode_band_set_from_reader_impl(reader, Some(mask))
}

/// Decodes a band set into a homogeneous vector in the requested layout.
///
/// # Errors
/// Returns an error for invalid input or an incompatible output element type.
pub fn decode_band_set_vec<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
) -> Result<(BandSetInfo, Vec<T>)> {
    decode_band_set_owned(blob, layout, None)
}

/// Decodes an externally masked band set into a homogeneous vector.
///
/// # Errors
/// Returns an error for invalid input, mask mismatch, or incompatible element type.
pub fn decode_band_set_vec_with_mask<T: BandElement>(
    blob: &[u8],
    mask: &[u8],
    layout: BandLayout,
) -> Result<(BandSetInfo, Vec<T>)> {
    decode_band_set_owned(blob, layout, Some(mask))
}

/// Decodes a band set directly into an exactly sized output slice.
///
/// # Errors
/// Returns an error for invalid input, incompatible types, or the wrong output length.
pub fn decode_band_set_into<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
    out: &mut [T],
) -> Result<BandSetInfo> {
    decode_band_set_into_direct(blob, layout, None, out)
}

/// Decodes an externally masked band set directly into an output slice.
///
/// # Errors
/// Returns an error for invalid input, mask mismatch, type mismatch, or wrong length.
pub fn decode_band_set_into_with_mask<T: BandElement>(
    blob: &[u8],
    mask: &[u8],
    layout: BandLayout,
    out: &mut [T],
) -> Result<BandSetInfo> {
    decode_band_set_into_direct(blob, layout, Some(mask), out)
}

#[cfg(feature = "ndarray")]
/// Decodes a band set into an interleaved ndarray.
///
/// # Errors
/// Returns an error for invalid data, incompatible types, or shape construction failure.
pub fn decode_band_set_ndarray<T: BandElement>(blob: &[u8]) -> Result<ArrayD<T>> {
    decode_band_set_ndarray_with_layout(blob, BandLayout::Interleaved)
}

#[cfg(feature = "ndarray")]
/// Decodes an externally masked band set into an interleaved ndarray.
///
/// # Errors
/// Returns an error for invalid data, mask mismatch, type mismatch, or shape failure.
pub fn decode_band_set_ndarray_with_mask<T: BandElement>(
    blob: &[u8],
    mask: &[u8],
) -> Result<ArrayD<T>> {
    decode_band_set_ndarray_with_layout_and_mask(blob, BandLayout::Interleaved, mask)
}

#[cfg(feature = "ndarray")]
/// Decodes a band set into an ndarray using `layout`.
///
/// # Errors
/// Returns an error for invalid data, incompatible types, or shape failure.
pub fn decode_band_set_ndarray_with_layout<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
) -> Result<ArrayD<T>> {
    decode_band_set_ndarray_with_layout_impl(blob, layout, None)
}

#[cfg(feature = "ndarray")]
/// Decodes an externally masked band set into an ndarray using `layout`.
///
/// # Errors
/// Returns an error for invalid data, masks, types, or shape construction.
pub fn decode_band_set_ndarray_with_layout_and_mask<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
    mask: &[u8],
) -> Result<ArrayD<T>> {
    decode_band_set_ndarray_with_layout_impl(blob, layout, Some(mask))
}

#[cfg(feature = "ndarray")]
/// Decodes and promotes a band set into an interleaved `f64` ndarray.
///
/// # Errors
/// Returns an error for invalid data or shape construction failure.
pub fn decode_band_set_ndarray_f64(blob: &[u8]) -> Result<ArrayD<f64>> {
    decode_band_set_ndarray_f64_with_layout(blob, BandLayout::Interleaved)
}

#[cfg(feature = "ndarray")]
/// Decodes and promotes an externally masked band set into an `f64` ndarray.
///
/// # Errors
/// Returns an error for invalid data, mask mismatch, or shape failure.
pub fn decode_band_set_ndarray_f64_with_mask(blob: &[u8], mask: &[u8]) -> Result<ArrayD<f64>> {
    decode_band_set_ndarray_f64_with_layout_and_mask(blob, BandLayout::Interleaved, mask)
}

#[cfg(feature = "ndarray")]
/// Decodes and promotes a band set into an `f64` ndarray using `layout`.
///
/// # Errors
/// Returns an error for invalid data or shape construction failure.
pub fn decode_band_set_ndarray_f64_with_layout(
    blob: &[u8],
    layout: BandLayout,
) -> Result<ArrayD<f64>> {
    decode_band_set_ndarray_f64_with_optional_mask(blob, layout, None)
}

#[cfg(feature = "ndarray")]
/// Decodes and promotes an externally masked band set using `layout`.
///
/// # Errors
/// Returns an error for invalid data, mask mismatch, or shape failure.
pub fn decode_band_set_ndarray_f64_with_layout_and_mask(
    blob: &[u8],
    layout: BandLayout,
    mask: &[u8],
) -> Result<ArrayD<f64>> {
    decode_band_set_ndarray_f64_with_optional_mask(blob, layout, Some(mask))
}

#[cfg(feature = "ndarray")]
/// Returns decoded band masks as an ndarray without decoding pixel values.
///
/// # Errors
/// Returns an error for invalid blobs, inconsistent masks, or shape failure.
pub fn decode_band_mask_ndarray(blob: &[u8]) -> Result<Option<ArrayD<u8>>> {
    let (info, band_masks) = inspect_band_masks(blob, None)?;
    crate::types::band_masks_into_ndarray(info, band_masks)
}

#[cfg(feature = "ndarray")]
/// Returns band masks seeded by an external mask as an ndarray.
///
/// # Errors
/// Returns an error for invalid blobs, masks, or shape construction.
pub fn decode_band_mask_ndarray_with_mask(blob: &[u8], mask: &[u8]) -> Result<Option<ArrayD<u8>>> {
    let (info, band_masks) = inspect_band_masks(blob, Some(mask))?;
    crate::types::band_masks_into_ndarray(info, band_masks)
}

fn decode_band_set_with_lerc2_mask(
    blob: &[u8],
    initial_mask: Option<&[u8]>,
) -> Result<DecodedBandSet> {
    let mut offset = 0usize;
    let mut bands = Vec::new();
    let mut infos = Vec::new();
    let mut band_masks = Vec::new();
    let mut lerc1_mask = initial_mask.map(<[u8]>::to_vec);
    let mut lerc2_mask = initial_mask.map(<[u8]>::to_vec);

    while offset < blob.len() {
        let decoded = decode_first_with_masks(
            &blob[offset..],
            lerc1_mask.as_deref(),
            lerc2_mask.as_deref(),
        )?;

        if lerc1::is_lerc1(&blob[offset..]) {
            lerc1_mask = decoded.mask.clone();
            lerc2_mask = None;
        } else {
            lerc2_mask = decoded.mask.clone();
            lerc1_mask = None;
        }

        offset = checked_next_offset(offset, decoded.info.blob_size, blob.len())?;
        infos.push(decoded.info);
        bands.push(decoded.pixels);
        band_masks.push(decoded.mask);
    }

    DecodedBandSet::new(BandSetInfo::new(infos)?, bands, band_masks)
}

#[cfg(feature = "ndarray")]
fn decode_band_set_ndarray_with_layout_impl<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
) -> Result<ArrayD<T>> {
    let (info, values) = decode_band_set_owned(blob, layout, initial_mask)?;
    let shape = info.ndarray_shape_for_layout(layout);
    ArrayD::from_shape_vec(ndarray::IxDyn(&shape), values).map_err(|e| {
        Error::invalid_blob(format!(
            "failed to build ndarray from decoded band set: {e}"
        ))
    })
}

#[cfg(feature = "ndarray")]
fn decode_band_set_ndarray_f64_with_optional_mask(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
) -> Result<ArrayD<f64>> {
    let band_info = decode_band_set_to_f64_info(blob, layout, initial_mask)?;
    let shape = band_info.0.ndarray_shape_for_layout(layout);
    ArrayD::from_shape_vec(ndarray::IxDyn(&shape), band_info.1).map_err(|e| {
        Error::invalid_blob(format!(
            "failed to build ndarray from decoded band set: {e}"
        ))
    })
}

/// Strictly decodes one blob and promotes every sample to `f64`.
///
/// # Errors
/// Returns an error for malformed data, unsupported features, or trailing bytes.
pub fn decode_to_f64(blob: &[u8]) -> Result<DecodedF64> {
    let decoded = decode_first_to_f64(blob)?;
    ensure_single_blob_consumed(
        blob.len(),
        decoded.info.blob_size,
        "decode_to_f64",
        "decode_first_to_f64",
    )?;
    Ok(decoded)
}

/// Strictly decodes one externally masked blob as promoted `f64` samples.
///
/// # Errors
/// Returns an error for invalid input, mask mismatch, or trailing bytes.
pub fn decode_to_f64_with_mask(blob: &[u8], mask: &[u8]) -> Result<DecodedF64> {
    let decoded = decode_first_to_f64_with_mask(blob, mask)?;
    ensure_single_blob_consumed(
        blob.len(),
        decoded.info.blob_size,
        "decode_to_f64_with_mask",
        "decode_first_to_f64_with_mask",
    )?;
    Ok(decoded)
}

/// Reads and decodes one blob as `f64`, leaving later stream bytes unread.
///
/// # Errors
/// Returns an error for I/O failure, truncation, or invalid data.
pub fn decode_to_f64_from_reader<R: std::io::Read + ?Sized>(reader: &mut R) -> Result<DecodedF64> {
    let blob = read_required_stream_blob(reader, None)?;
    decode_to_f64(&blob)
}

/// Reads and decodes one externally masked blob as `f64`.
///
/// # Errors
/// Returns an error for I/O failure, invalid data, or mask mismatch.
pub fn decode_to_f64_from_reader_with_mask<R: std::io::Read + ?Sized>(
    reader: &mut R,
    mask: &[u8],
) -> Result<DecodedF64> {
    let blob = read_required_stream_blob(reader, Some(mask))?;
    decode_to_f64_with_mask(&blob, mask)
}

/// Decodes the first blob as promoted `f64` samples and permits trailing bytes.
///
/// # Errors
/// Returns an error when the first blob is malformed or unsupported.
pub fn decode_first_to_f64(blob: &[u8]) -> Result<DecodedF64> {
    decode_first_f64(blob)
}

/// Decodes the first externally masked blob as `f64` and permits trailing bytes.
///
/// # Errors
/// Returns an error for invalid data or a mismatched mask.
pub fn decode_first_to_f64_with_mask(blob: &[u8], mask: &[u8]) -> Result<DecodedF64> {
    decode_first_f64_with_masks(blob, Some(mask), Some(mask))
}

#[cfg(feature = "ndarray")]
/// Strictly decodes one native-typed blob into an ndarray.
///
/// # Errors
/// Returns an error for invalid data, incompatible output type, or shape failure.
pub fn decode_ndarray<T: NdArrayElement>(blob: &[u8]) -> Result<ArrayD<T>> {
    decode(blob)?.into_ndarray()
}

#[cfg(feature = "ndarray")]
/// Strictly decodes one externally masked blob into an ndarray.
///
/// # Errors
/// Returns an error for invalid data, masks, types, or shape construction.
pub fn decode_ndarray_with_mask<T: NdArrayElement>(blob: &[u8], mask: &[u8]) -> Result<ArrayD<T>> {
    decode_with_mask(blob, mask)?.into_ndarray()
}

#[cfg(feature = "ndarray")]
/// Strictly decodes one blob into a promoted `f64` ndarray.
///
/// # Errors
/// Returns an error for invalid data or shape construction failure.
pub fn decode_ndarray_f64(blob: &[u8]) -> Result<ArrayD<f64>> {
    decode_to_f64(blob)?.into_ndarray()
}

#[cfg(feature = "ndarray")]
/// Strictly decodes one externally masked blob into an `f64` ndarray.
///
/// # Errors
/// Returns an error for invalid data, mask mismatch, or shape failure.
pub fn decode_ndarray_f64_with_mask(blob: &[u8], mask: &[u8]) -> Result<ArrayD<f64>> {
    decode_to_f64_with_mask(blob, mask)?.into_ndarray()
}

#[cfg(feature = "ndarray")]
/// Strictly decodes one blob's validity mask as an ndarray.
///
/// # Errors
/// Returns an error for invalid data, trailing bytes, or shape construction.
pub fn decode_mask_ndarray(blob: &[u8]) -> Result<Option<ArrayD<u8>>> {
    let (info, mask) = inspect_first_mask_with_info(blob, None, None)?;
    ensure_single_blob_consumed(
        blob.len(),
        info.blob_size,
        "decode_mask_ndarray",
        "inspect_first",
    )?;
    mask_to_ndarray(&info, mask)
}

#[cfg(feature = "ndarray")]
/// Strictly decodes one blob's externally seeded mask as an ndarray.
///
/// # Errors
/// Returns an error for invalid data, mask mismatch, trailing bytes, or shape failure.
pub fn decode_mask_ndarray_with_mask(blob: &[u8], mask: &[u8]) -> Result<Option<ArrayD<u8>>> {
    let (info, decoded_mask) = inspect_first_mask_with_info(blob, Some(mask), Some(mask))?;
    ensure_single_blob_consumed(
        blob.len(),
        info.blob_size,
        "decode_mask_ndarray_with_mask",
        "inspect_first_with_mask",
    )?;
    mask_to_ndarray(&info, decoded_mask)
}

fn decode_first_with_masks(
    blob: &[u8],
    lerc1_shared_mask: Option<&[u8]>,
    lerc2_shared_mask: Option<&[u8]>,
) -> Result<Decoded> {
    if lerc1::is_lerc1(blob) {
        return lerc1::decode(blob, lerc1_shared_mask);
    }
    if lerc2::is_lerc2(blob) {
        return lerc2::decode(blob, lerc2_shared_mask);
    }
    Err(Error::InvalidMagic)
}

fn inspect_first_mask_with_info(
    blob: &[u8],
    lerc1_shared_mask: Option<&[u8]>,
    lerc2_shared_mask: Option<&[u8]>,
) -> Result<(BlobInfo, Option<Vec<u8>>)> {
    if lerc1::is_lerc1(blob) {
        return lerc1::inspect_mask(blob, lerc1_shared_mask);
    }
    if lerc2::is_lerc2(blob) {
        return lerc2::inspect_with_mask(blob, lerc2_shared_mask);
    }
    Err(Error::InvalidMagic)
}

fn decode_first_f64(blob: &[u8]) -> Result<DecodedF64> {
    decode_first_f64_with_masks(blob, None, None)
}

fn decode_first_f64_with_masks(
    blob: &[u8],
    lerc1_shared_mask: Option<&[u8]>,
    lerc2_shared_mask: Option<&[u8]>,
) -> Result<DecodedF64> {
    if lerc1::is_lerc1(blob) {
        return lerc1::decode_f64(blob, lerc1_shared_mask);
    }
    if lerc2::is_lerc2(blob) {
        return lerc2::decode_f64(blob, lerc2_shared_mask);
    }
    Err(Error::InvalidMagic)
}

fn decode_band_set_owned<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
) -> Result<(BandSetInfo, Vec<T>)> {
    let band_info = scan_band_infos(blob, initial_mask)?;
    decode_band_set_owned_direct(blob, layout, band_info, initial_mask)
}

fn decode_band_set_into_direct<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
    out: &mut [T],
) -> Result<BandSetInfo> {
    dispatch_band_element!(T, |Concrete| {
        decode_band_set_into_impl::<Concrete>(
            blob,
            layout,
            initial_mask,
            cast_slice_mut::<T, Concrete>(out),
        )
    })
}

fn decode_band_set_owned_direct<T: BandElement>(
    blob: &[u8],
    layout: BandLayout,
    band_info: BandSetInfo,
    initial_mask: Option<&[u8]>,
) -> Result<(BandSetInfo, Vec<T>)> {
    dispatch_band_element!(T, |Concrete| {
        decode_band_set_owned_direct_impl::<Concrete>(blob, layout, band_info, initial_mask)
            .map(|(info, values)| (info, cast_vec::<T, Concrete>(values)))
    })
}

fn decode_band_set_into_impl<T: Sample + BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
    out: &mut [T],
) -> Result<BandSetInfo> {
    let band_info = scan_band_infos(blob, initial_mask)?;
    decode_band_set_into_impl_with_info(blob, layout, initial_mask, &band_info, out)
}

fn decode_band_set_into_impl_with_info<T: Sample + BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
    band_info: &BandSetInfo,
    out: &mut [T],
) -> Result<BandSetInfo> {
    validate_band_output_type::<T>(band_info)?;
    #[cfg(feature = "rayon")]
    {
        if band_info.band_count() > 1 {
            return decode_band_set_into_parallel(blob, layout, initial_mask, band_info, out);
        }
    }
    decode_band_set_into_sequential(blob, layout, initial_mask, band_info, out)
}

fn validate_band_output_type<T: BandElement>(band_info: &BandSetInfo) -> Result<()> {
    if T::KIND == BandElementKind::F64 {
        return Ok(());
    }
    let expected = match T::KIND {
        BandElementKind::I8 => DataType::I8,
        BandElementKind::U8 => DataType::U8,
        BandElementKind::I16 => DataType::I16,
        BandElementKind::U16 => DataType::U16,
        BandElementKind::I32 => DataType::I32,
        BandElementKind::U32 => DataType::U32,
        BandElementKind::F32 => DataType::F32,
        BandElementKind::F64 => unreachable!("f64 promotion returned above"),
    };
    if band_info
        .bands()
        .iter()
        .any(|band| band.data_type != expected)
    {
        return Err(Error::InvalidArgument(
            "output element type must match every native band type unless decoding to f64",
        ));
    }
    Ok(())
}

fn decode_band_set_into_sequential<T: Sample + BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
    band_info: &BandSetInfo,
    out: &mut [T],
) -> Result<BandSetInfo> {
    let band_count = band_info.band_count();
    let expected_len = band_info.value_count()?;
    if out.len() != expected_len {
        return Err(Error::InvalidArgument(
            "output slice length does not match decoded band set length",
        ));
    }

    let pixel_count = band_info.first().pixel_count()?;
    let depth = band_info.depth() as usize;
    let mut offset = 0usize;
    let mut band_index = 0usize;
    let mut lerc1_mask = initial_mask.map(<[u8]>::to_vec);
    let mut lerc2_mask = initial_mask.map(<[u8]>::to_vec);
    let mut decoded_infos = Vec::with_capacity(band_count);

    while offset < blob.len() {
        let slice = &blob[offset..];
        let is_lerc1 = lerc1::is_lerc1(slice);
        let mut sink = BandSink::new(out, pixel_count, depth, band_index, band_count, layout);
        let (info, mask) = if is_lerc1 {
            lerc1::decode_into(slice, lerc1_mask.as_deref(), &mut sink)?
        } else if lerc2::is_lerc2(slice) {
            lerc2::decode_into(slice, lerc2_mask.as_deref(), &mut sink)?
        } else {
            return Err(Error::InvalidMagic);
        };

        if is_lerc1 {
            lerc1_mask = mask;
            lerc2_mask = None;
        } else {
            lerc2_mask = mask;
            lerc1_mask = None;
        }

        let blob_size = info.blob_size;
        decoded_infos.push(info);
        offset = checked_next_offset(offset, blob_size, blob.len())?;
        band_index += 1;
    }

    BandSetInfo::new(decoded_infos)
}

#[cfg(feature = "rayon")]
#[derive(Debug, Clone, Copy)]
enum BandFormat {
    Lerc1,
    Lerc2,
}

#[cfg(feature = "rayon")]
#[derive(Debug)]
struct ParallelBand<'a> {
    blob: &'a [u8],
    format: BandFormat,
    inherited_mask: Option<std::sync::Arc<[u8]>>,
}

#[cfg(feature = "rayon")]
fn scan_parallel_bands<'a>(
    blob: &'a [u8],
    initial_mask: Option<&[u8]>,
) -> Result<Vec<ParallelBand<'a>>> {
    use std::sync::Arc;

    let mut offset = 0usize;
    let mut bands = Vec::new();
    let mut lerc1_mask = initial_mask.map(Arc::<[u8]>::from);
    let mut lerc2_mask = initial_mask.map(Arc::<[u8]>::from);

    while offset < blob.len() {
        let slice = &blob[offset..];
        let format = if lerc1::is_lerc1(slice) {
            BandFormat::Lerc1
        } else if lerc2::is_lerc2(slice) {
            BandFormat::Lerc2
        } else {
            return Err(Error::InvalidMagic);
        };
        let inherited_mask = match format {
            BandFormat::Lerc1 => lerc1_mask.clone(),
            BandFormat::Lerc2 => lerc2_mask.clone(),
        };
        let (info, decoded_mask) =
            inspect_first_mask_with_info(slice, lerc1_mask.as_deref(), lerc2_mask.as_deref())?;
        let next = checked_next_offset(offset, info.blob_size, blob.len())?;

        bands.push(ParallelBand {
            blob: &blob[offset..next],
            format,
            inherited_mask,
        });

        match format {
            BandFormat::Lerc1 => {
                lerc1_mask = decoded_mask.map(Arc::from);
                lerc2_mask = None;
            }
            BandFormat::Lerc2 => {
                lerc2_mask = decoded_mask.map(Arc::from);
                lerc1_mask = None;
            }
        }
        offset = next;
    }

    Ok(bands)
}

#[cfg(feature = "rayon")]
fn decode_parallel_band<T: Sample>(
    band: &ParallelBand<'_>,
    out: &mut [T],
    depth: usize,
) -> Result<BlobInfo> {
    let mut writer = PixelDataWriter::new(out, depth);
    let (info, _) = match band.format {
        BandFormat::Lerc1 => {
            lerc1::decode_into(band.blob, band.inherited_mask.as_deref(), &mut writer)?
        }
        BandFormat::Lerc2 => {
            lerc2::decode_into(band.blob, band.inherited_mask.as_deref(), &mut writer)?
        }
    };
    Ok(info)
}

#[cfg(feature = "rayon")]
fn decode_band_set_into_parallel<T: Sample + BandElement>(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
    band_info: &BandSetInfo,
    out: &mut [T],
) -> Result<BandSetInfo> {
    let expected_len = band_info.value_count()?;
    if out.len() != expected_len {
        return Err(Error::InvalidArgument(
            "output slice length does not match decoded band set length",
        ));
    }

    let bands = scan_parallel_bands(blob, initial_mask)?;
    let band_count = band_info.band_count();
    if bands.len() != band_count {
        return Err(Error::Internal(
            "parallel band scan disagrees with decoded band metadata",
        ));
    }
    let pixel_count = band_info.first().pixel_count()?;
    let depth = band_info.depth() as usize;
    let band_len = band_info.first().sample_count()?;

    let infos = match layout {
        BandLayout::Bsq => out
            .par_chunks_mut(band_len)
            .zip(bands.par_iter())
            .map(|(band_out, band)| decode_parallel_band(band, band_out, depth))
            .collect::<Result<Vec<_>>>()?,
        BandLayout::Interleaved => {
            let decoded = bands
                .par_iter()
                .map(|band| {
                    let mut values = default_vec(band_len, "parallel decoded band")?;
                    let info = decode_parallel_band(band, &mut values, depth)?;
                    Ok((info, values))
                })
                .collect::<Result<Vec<_>>>()?;
            let mut infos = Vec::with_capacity(band_count);
            for (band_index, (info, values)) in decoded.into_iter().enumerate() {
                copy_band_values_into_slice(
                    out,
                    &values,
                    pixel_count,
                    depth,
                    band_index,
                    band_count,
                    layout,
                )?;
                infos.push(info);
            }
            infos
        }
    };

    BandSetInfo::new(infos)
}

#[cfg(feature = "ndarray")]
fn decode_band_set_to_f64_info(
    blob: &[u8],
    layout: BandLayout,
    initial_mask: Option<&[u8]>,
) -> Result<(BandSetInfo, Vec<f64>)> {
    let band_info = scan_band_infos(blob, initial_mask)?;
    decode_band_set_owned_direct_impl::<f64>(blob, layout, band_info, initial_mask)
}

#[cfg(feature = "ndarray")]
fn inspect_band_masks(
    blob: &[u8],
    initial_mask: Option<&[u8]>,
) -> Result<(BandSetInfo, Vec<Option<Vec<u8>>>)> {
    let mut offset = 0usize;
    let mut infos = Vec::new();
    let mut band_masks = Vec::new();
    let mut lerc1_mask = initial_mask.map(<[u8]>::to_vec);
    let mut lerc2_mask = initial_mask.map(<[u8]>::to_vec);

    while offset < blob.len() {
        let slice = &blob[offset..];
        let is_lerc1 = lerc1::is_lerc1(slice);
        let (info, mask) =
            inspect_first_mask_with_info(slice, lerc1_mask.as_deref(), lerc2_mask.as_deref())?;

        if is_lerc1 {
            lerc1_mask = mask.clone();
            lerc2_mask = None;
        } else {
            lerc2_mask = mask.clone();
            lerc1_mask = None;
        }

        offset = checked_next_offset(offset, info.blob_size, blob.len())?;
        infos.push(info);
        band_masks.push(mask);
    }

    Ok((BandSetInfo::new(infos)?, band_masks))
}

fn scan_band_infos(blob: &[u8], initial_mask: Option<&[u8]>) -> Result<BandSetInfo> {
    let mut offset = 0usize;
    let mut infos = Vec::new();
    let mut lerc1_mask = initial_mask.map(<[u8]>::to_vec);
    let mut lerc2_mask = initial_mask.map(<[u8]>::to_vec);

    while offset < blob.len() {
        let slice = &blob[offset..];
        let info = if lerc1::is_lerc1(slice) {
            let parsed = lerc1::parse(slice, lerc1_mask.as_deref())?;
            let info = parsed.info;
            lerc1_mask = parsed.mask;
            lerc2_mask = None;
            info
        } else if lerc2::is_lerc2(slice) {
            let (info, mask) = lerc2::inspect_with_mask(slice, lerc2_mask.as_deref())?;
            lerc2_mask = mask;
            lerc1_mask = None;
            info
        } else {
            return Err(Error::InvalidMagic);
        };

        offset = checked_next_offset(offset, info.blob_size, blob.len())?;
        infos.push(info);
    }

    BandSetInfo::new(infos)
}

fn read_required_stream_blob<R: std::io::Read + ?Sized>(
    reader: &mut R,
    lerc1_shared_mask: Option<&[u8]>,
) -> Result<Vec<u8>> {
    stream::read_next_blob(reader, lerc1_shared_mask)?.ok_or(Error::Truncated {
        offset: 0,
        needed: 10,
        available: 0,
    })
}

fn decode_band_set_from_reader_impl<R: std::io::Read + ?Sized>(
    reader: &mut R,
    initial_mask: Option<&[u8]>,
) -> Result<DecodedBandSet> {
    let mut bands = Vec::new();
    let mut infos = Vec::new();
    let mut band_masks = Vec::new();
    let mut lerc1_mask = initial_mask.map(<[u8]>::to_vec);
    let mut lerc2_mask = initial_mask.map(<[u8]>::to_vec);

    while let Some(blob) = stream::read_next_blob(reader, lerc1_mask.as_deref())? {
        let is_lerc1 = lerc1::is_lerc1(&blob);
        let decoded = decode_first_with_masks(&blob, lerc1_mask.as_deref(), lerc2_mask.as_deref())?;

        if is_lerc1 {
            lerc1_mask = decoded.mask.clone();
            lerc2_mask = None;
        } else {
            lerc2_mask = decoded.mask.clone();
            lerc1_mask = None;
        }
        infos.push(decoded.info);
        bands.push(decoded.pixels);
        band_masks.push(decoded.mask);
    }

    DecodedBandSet::new(BandSetInfo::new(infos)?, bands, band_masks)
}

fn ensure_single_blob_consumed(
    blob_len: usize,
    decoded_len: usize,
    strict_api: &str,
    permissive_api: &str,
) -> Result<()> {
    if blob_len == decoded_len {
        return Ok(());
    }
    Err(Error::invalid_blob(format!(
        "{strict_api} only accepts a single LERC blob; found {} trailing bytes, use {permissive_api} for first-blob decoding or decode_band_set for concatenated rasters",
        blob_len - decoded_len
    )))
}

fn checked_next_offset(offset: usize, next_len: usize, total_len: usize) -> Result<usize> {
    let next = offset
        .checked_add(next_len)
        .ok_or(Error::SizeOverflow("concatenated band offset"))?;
    if next <= offset || next > total_len {
        return Err(Error::invalid_blob("invalid concatenated band blob size"));
    }
    Ok(next)
}

#[cfg(feature = "ndarray")]
fn mask_to_ndarray(info: &BlobInfo, mask: Option<Vec<u8>>) -> Result<Option<ArrayD<u8>>> {
    let shape = info.mask_ndarray_shape();
    mask.map(|mask| {
        ArrayD::from_shape_vec(ndarray::IxDyn(&shape), mask).map_err(|e| {
            Error::invalid_blob(format!("failed to build ndarray from decoded mask: {e}"))
        })
    })
    .transpose()
}

fn decode_band_set_owned_direct_impl<T: Sample + BandElement + Copy + Default>(
    blob: &[u8],
    layout: BandLayout,
    band_info: BandSetInfo,
    initial_mask: Option<&[u8]>,
) -> Result<(BandSetInfo, Vec<T>)> {
    let mut values = default_vec(band_info.value_count()?, "decoded band set")?;
    let decoded_info =
        decode_band_set_into_impl_with_info(blob, layout, initial_mask, &band_info, &mut values)?;
    Ok((decoded_info, values))
}

fn cast_slice_mut<T, U>(slice: &mut [T]) -> &mut [U] {
    debug_assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<U>());
    debug_assert_eq!(std::mem::align_of::<T>(), std::mem::align_of::<U>());
    // SAFETY: callers only reach this helper through dispatch_band_element!, where
    // T and U are the same concrete primitive type selected by BandElementKind.
    unsafe { &mut *(slice as *mut [T] as *mut [U]) }
}

fn cast_vec<T, U>(values: Vec<U>) -> Vec<T> {
    debug_assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<U>());
    debug_assert_eq!(std::mem::align_of::<T>(), std::mem::align_of::<U>());
    let len = values.len();
    let cap = values.capacity();
    let ptr = values.as_ptr() as *mut T;
    std::mem::forget(values);
    // SAFETY: callers only reach this helper through dispatch_band_element!, where
    // T and U are the same concrete primitive type. The allocation, length, and
    // capacity therefore remain valid for Vec<T>.
    unsafe { Vec::from_raw_parts(ptr, len, cap) }
}