grib-reader 0.6.0

GRIB Edition 1 and 2 decoder for weather and climate data
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
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! Pure-Rust GRIB file reader.
//!
//! The current implementation supports the production-critical baseline for both
//! GRIB1 and GRIB2: regular latitude/longitude grids, GRIB2 Lambert conformal
//! and polar stereographic metadata and flat decode, simple packing, GRIB2
//! complex packing with general group splitting, and optional image-backed
//! GRIB2 packing codecs.
//!
//! # Example
//!
//! ```no_run
//! use grib_reader::GribFile;
//!
//! let file = GribFile::open("gfs.grib2")?;
//! println!("messages: {}", file.message_count());
//!
//! for msg in file.messages() {
//!     println!(
//!         "  {} {:?} {:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
//!         msg.parameter_name(),
//!         msg.grid_shape(),
//!         msg.reference_time().year,
//!         msg.reference_time().month,
//!         msg.reference_time().day,
//!         msg.reference_time().hour,
//!         msg.reference_time().minute,
//!         msg.reference_time().second,
//!     );
//! }
//!
//! let data = file.message(0)?.read_data_as_f64()?;
//! println!("shape: {:?}", data.shape());
//! # Ok::<(), grib_reader::Error>(())
//! ```

pub mod data;
pub mod error;
pub mod grib1;
pub mod grid;
pub mod indicator;
pub mod metadata;
pub mod parameter;
pub mod product;
pub mod sections;

pub use data::{
    ComplexPackingParams, DataRepresentation, DecodeSample, ImagePackingParams,
    Jpeg2000PackingParams, PngPackingParams, SimplePackingParams, SpatialDifferencingParams,
};
pub use error::{Error, Result};
pub use grib1::{BinaryDataSection, GridDescription, ProductDefinition as Grib1ProductDefinition};
pub use grid::{GridDefinition, LambertConformalGrid, LatLonGrid, PolarStereographicGrid};
pub use metadata::{ForecastTimeUnit, Parameter, ParameterTableSource, ReferenceTime};
pub use parameter::{
    LocalParameterEntry, LocalParameterTable, OwnedLocalParameterEntry, BUILTIN_LOCAL_PARAMETERS,
    LOCAL_PARAMETER_TABLE_CSV_HEADER,
};
pub use product::{
    AnalysisOrForecastTemplate, EnsembleStatisticalProcessTemplate, FixedSurface, Identification,
    IndividualEnsembleForecastTemplate, ProductDefinition, ProductDefinitionTemplate,
    StatisticalProcessTemplate, StatisticalTimeRange,
};

use std::path::Path;
use std::sync::Arc;

use memmap2::Mmap;
use ndarray::{ArrayD, IxDyn};

use crate::data::{
    bitmap_payload as grib2_bitmap_payload, count_bitmap_present_points, decode_field_into,
    decode_payload_into,
};
use crate::indicator::Indicator;
use crate::parameter::lookup_parameter_with_local_entries;
use crate::sections::{index_fields, FieldSections, SectionRef};

#[cfg(feature = "rayon")]
use rayon::prelude::*;

const GRIB_MAGIC: &[u8; 4] = b"GRIB";
pub const DEFAULT_MAX_DECODED_POINTS: usize = 25_000_000;
pub const DEFAULT_MAX_AXIS_POINTS: usize = 1_000_000;

/// Configuration for opening GRIB data.
#[derive(Debug, Clone, Copy)]
pub struct OpenOptions {
    /// When `true`, the first malformed GRIB candidate aborts opening.
    ///
    /// When `false`, candidate offsets with invalid framing are skipped and
    /// scanning continues. Once a candidate has a valid indicator, message
    /// length, and end marker, any indexing or decoding error is returned.
    pub strict: bool,
    /// Maximum grid points a decoded field may contain.
    ///
    /// This is checked while indexing and before convenience decode methods
    /// allocate their output buffer. `None` disables the decoded-point limit.
    pub max_decoded_points: Option<usize>,
    /// Maximum points a coordinate-axis helper may allocate.
    ///
    /// This applies to latitude, longitude, projected x, and projected y axis
    /// vectors produced through [`Message`] helpers. `None` disables the axis
    /// limit.
    pub max_axis_points: Option<usize>,
}

impl Default for OpenOptions {
    fn default() -> Self {
        Self {
            strict: true,
            max_decoded_points: Some(DEFAULT_MAX_DECODED_POINTS),
            max_axis_points: Some(DEFAULT_MAX_AXIS_POINTS),
        }
    }
}

impl OpenOptions {
    pub fn with_max_decoded_points(mut self, max: usize) -> Self {
        self.max_decoded_points = Some(max);
        self
    }

    pub fn with_max_axis_points(mut self, max: usize) -> Self {
        self.max_axis_points = Some(max);
        self
    }

    pub fn without_decoded_point_limit(mut self) -> Self {
        self.max_decoded_points = None;
        self
    }

    pub fn without_axis_point_limit(mut self) -> Self {
        self.max_axis_points = None;
        self
    }

    pub fn without_limits(mut self) -> Self {
        self.max_decoded_points = None;
        self.max_axis_points = None;
        self
    }
}

/// Caller-supplied GRIB1 predefined bitmap.
///
/// GRIB1 predefined bitmap table references are center-defined, not globally
/// standardized. `bitmap` is the raw bitmap payload: one bit per grid point in
/// GRIB scan order, with `1` meaning present and `0` meaning missing.
#[derive(Debug, Clone, Copy)]
pub struct PredefinedBitmap<'a> {
    pub center_id: u16,
    pub subcenter_id: Option<u16>,
    pub table_reference: u16,
    pub bitmap: &'a [u8],
}

/// A parsed GRIB field.
#[derive(Debug, Clone)]
pub struct MessageMetadata {
    pub edition: u8,
    pub center_id: u16,
    pub subcenter_id: u16,
    pub discipline: Option<u8>,
    pub reference_time: ReferenceTime,
    pub parameter: Parameter,
    pub grid: GridDefinition,
    pub data_representation: DataRepresentation,
    pub forecast_time_unit: Option<u8>,
    pub forecast_time: Option<u32>,
    pub message_offset: u64,
    pub message_length: u64,
    pub field_index_in_message: usize,
    grib1_product: Option<grib1::ProductDefinition>,
    grib2_identification: Option<Identification>,
    grib2_product: Option<ProductDefinition>,
}

/// A GRIB file containing one or more logical fields.
pub struct GribFile {
    data: GribData,
    messages: Vec<MessageIndex>,
    options: OpenOptions,
}

#[derive(Clone)]
struct MessageIndex {
    offset: usize,
    length: usize,
    metadata: MessageMetadata,
    decode_plan: DecodePlan,
}

#[derive(Clone)]
enum DecodePlan {
    Grib1 {
        bitmap: Option<Grib1BitmapSource>,
        data: SectionRef,
    },
    Grib2(FieldSections),
}

#[derive(Clone)]
enum Grib1BitmapSource {
    Explicit(SectionRef),
    Predefined(Arc<[u8]>),
}

enum GribData {
    Mmap(Mmap),
    Bytes(Vec<u8>),
}

impl GribData {
    fn as_bytes(&self) -> &[u8] {
        match self {
            GribData::Mmap(m) => m,
            GribData::Bytes(b) => b,
        }
    }
}

impl GribFile {
    /// Open a GRIB file from disk using memory-mapped I/O.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::open_with_options(path, OpenOptions::default())
    }

    /// Open a GRIB file from disk using explicit decoder options.
    pub fn open_with_options<P: AsRef<Path>>(path: P, options: OpenOptions) -> Result<Self> {
        Self::open_with_local_parameters(path, options, &[])
    }

    /// Open a GRIB file from disk using explicit decoder options and local table entries.
    pub fn open_with_local_parameters<P: AsRef<Path>>(
        path: P,
        options: OpenOptions,
        local_parameters: &[LocalParameterEntry<'_>],
    ) -> Result<Self> {
        Self::open_with_local_parameters_and_grib1_predefined_bitmaps(
            path,
            options,
            local_parameters,
            &[],
        )
    }

    /// Open a GRIB file from disk using caller-supplied GRIB1 predefined bitmaps.
    pub fn open_with_grib1_predefined_bitmaps<P: AsRef<Path>>(
        path: P,
        options: OpenOptions,
        predefined_bitmaps: &[PredefinedBitmap<'_>],
    ) -> Result<Self> {
        Self::open_with_local_parameters_and_grib1_predefined_bitmaps(
            path,
            options,
            &[],
            predefined_bitmaps,
        )
    }

    /// Open a GRIB file from disk using GRIB2 local parameters and GRIB1 predefined bitmaps.
    pub fn open_with_local_parameters_and_grib1_predefined_bitmaps<P: AsRef<Path>>(
        path: P,
        options: OpenOptions,
        local_parameters: &[LocalParameterEntry<'_>],
        predefined_bitmaps: &[PredefinedBitmap<'_>],
    ) -> Result<Self> {
        let file = std::fs::File::open(path.as_ref())
            .map_err(|e| Error::Io(e, path.as_ref().display().to_string()))?;
        let mmap = unsafe { Mmap::map(&file) }
            .map_err(|e| Error::Io(e, path.as_ref().display().to_string()))?;
        Self::from_data(
            GribData::Mmap(mmap),
            options,
            local_parameters,
            predefined_bitmaps,
        )
    }

    /// Open a GRIB file from an owned byte buffer.
    pub fn from_bytes(data: Vec<u8>) -> Result<Self> {
        Self::from_bytes_with_options(data, OpenOptions::default())
    }

    /// Open a GRIB file from an owned byte buffer using explicit decoder options.
    pub fn from_bytes_with_options(data: Vec<u8>, options: OpenOptions) -> Result<Self> {
        Self::from_bytes_with_local_parameters(data, options, &[])
    }

    /// Open a GRIB file from bytes using explicit decoder options and local table entries.
    pub fn from_bytes_with_local_parameters(
        data: Vec<u8>,
        options: OpenOptions,
        local_parameters: &[LocalParameterEntry<'_>],
    ) -> Result<Self> {
        Self::from_bytes_with_local_parameters_and_grib1_predefined_bitmaps(
            data,
            options,
            local_parameters,
            &[],
        )
    }

    /// Open a GRIB file from bytes using caller-supplied GRIB1 predefined bitmaps.
    pub fn from_bytes_with_grib1_predefined_bitmaps(
        data: Vec<u8>,
        options: OpenOptions,
        predefined_bitmaps: &[PredefinedBitmap<'_>],
    ) -> Result<Self> {
        Self::from_bytes_with_local_parameters_and_grib1_predefined_bitmaps(
            data,
            options,
            &[],
            predefined_bitmaps,
        )
    }

    /// Open a GRIB file from bytes using GRIB2 local parameters and GRIB1 predefined bitmaps.
    pub fn from_bytes_with_local_parameters_and_grib1_predefined_bitmaps(
        data: Vec<u8>,
        options: OpenOptions,
        local_parameters: &[LocalParameterEntry<'_>],
        predefined_bitmaps: &[PredefinedBitmap<'_>],
    ) -> Result<Self> {
        Self::from_data(
            GribData::Bytes(data),
            options,
            local_parameters,
            predefined_bitmaps,
        )
    }

    fn from_data(
        data: GribData,
        options: OpenOptions,
        local_parameters: &[LocalParameterEntry<'_>],
        predefined_bitmaps: &[PredefinedBitmap<'_>],
    ) -> Result<Self> {
        let messages = scan_messages(
            data.as_bytes(),
            options,
            local_parameters,
            predefined_bitmaps,
        )?;
        if messages.is_empty() {
            return Err(Error::NoMessages);
        }
        Ok(Self {
            data,
            messages,
            options,
        })
    }

    /// Returns the GRIB edition of the first field.
    pub fn edition(&self) -> u8 {
        self.messages
            .first()
            .map(|message| message.metadata.edition)
            .unwrap_or(0)
    }

    /// Returns the number of logical fields in the file.
    pub fn message_count(&self) -> usize {
        self.messages.len()
    }

    /// Access a field by index.
    pub fn message(&self, index: usize) -> Result<Message<'_>> {
        let record = self
            .messages
            .get(index)
            .ok_or(Error::MessageNotFound(index))?;
        let bytes = &self.data.as_bytes()[record.offset..record.offset + record.length];
        Ok(Message {
            index,
            bytes,
            metadata: &record.metadata,
            decode_plan: record.decode_plan.clone(),
            options: self.options,
        })
    }

    /// Iterate over all fields.
    pub fn messages(&self) -> MessageIter<'_> {
        MessageIter {
            file: self,
            index: 0,
        }
    }

    /// Decode every field in the file.
    pub fn read_all_data_as_f64(&self) -> Result<Vec<ArrayD<f64>>> {
        #[cfg(feature = "rayon")]
        {
            (0..self.message_count())
                .into_par_iter()
                .map(|index| self.message(index)?.read_data_as_f64())
                .collect()
        }
        #[cfg(not(feature = "rayon"))]
        {
            (0..self.message_count())
                .map(|index| self.message(index)?.read_data_as_f64())
                .collect()
        }
    }

    /// Decode every field in the file as `f32`.
    pub fn read_all_data_as_f32(&self) -> Result<Vec<ArrayD<f32>>> {
        #[cfg(feature = "rayon")]
        {
            (0..self.message_count())
                .into_par_iter()
                .map(|index| self.message(index)?.read_data_as_f32())
                .collect()
        }
        #[cfg(not(feature = "rayon"))]
        {
            (0..self.message_count())
                .map(|index| self.message(index)?.read_data_as_f32())
                .collect()
        }
    }
}

/// A single logical GRIB field.
pub struct Message<'a> {
    bytes: &'a [u8],
    metadata: &'a MessageMetadata,
    decode_plan: DecodePlan,
    options: OpenOptions,
    index: usize,
}

impl<'a> Message<'a> {
    pub fn edition(&self) -> u8 {
        self.metadata.edition
    }

    pub fn index(&self) -> usize {
        self.index
    }

    pub fn metadata(&self) -> &MessageMetadata {
        self.metadata
    }

    pub fn reference_time(&self) -> &ReferenceTime {
        &self.metadata.reference_time
    }

    pub fn parameter(&self) -> &Parameter {
        &self.metadata.parameter
    }

    pub fn center_id(&self) -> u16 {
        self.metadata.center_id
    }

    pub fn subcenter_id(&self) -> u16 {
        self.metadata.subcenter_id
    }

    pub fn identification(&self) -> Option<&Identification> {
        self.metadata.grib2_identification.as_ref()
    }

    pub fn product_definition(&self) -> Option<&ProductDefinition> {
        self.metadata.grib2_product.as_ref()
    }

    pub fn grib1_product_definition(&self) -> Option<&grib1::ProductDefinition> {
        self.metadata.grib1_product.as_ref()
    }

    pub fn grid_definition(&self) -> &GridDefinition {
        &self.metadata.grid
    }

    pub fn parameter_name(&self) -> &str {
        self.metadata.parameter.short_name.as_ref()
    }

    pub fn parameter_description(&self) -> &str {
        self.metadata.parameter.description.as_ref()
    }

    pub fn forecast_time_unit(&self) -> Option<u8> {
        self.metadata.forecast_time_unit
    }

    pub fn forecast_time_unit_kind(&self) -> Option<ForecastTimeUnit> {
        let unit = self.metadata.forecast_time_unit?;
        ForecastTimeUnit::from_edition_and_code(self.metadata.edition, unit)
    }

    pub fn forecast_time(&self) -> Option<u32> {
        self.metadata.forecast_time
    }

    pub fn valid_time(&self) -> Option<ReferenceTime> {
        if let Some(end) = self
            .metadata
            .grib2_product
            .as_ref()
            .and_then(ProductDefinition::end_of_overall_time_interval)
        {
            return Some(end);
        }

        let unit = self.metadata.forecast_time_unit?;
        let lead = self.metadata.forecast_time?;
        self.metadata
            .reference_time
            .checked_add_forecast_time_by_edition(self.metadata.edition, unit, lead)
    }

    pub fn grid_shape(&self) -> (usize, usize) {
        self.metadata.grid.shape()
    }

    pub fn latitudes(&self) -> Result<Option<Vec<f64>>> {
        self.metadata
            .grid
            .as_lat_lon()
            .map(|grid| grid.latitudes_with_limit(self.options.max_axis_points))
            .transpose()
    }

    pub fn longitudes(&self) -> Result<Option<Vec<f64>>> {
        self.metadata
            .grid
            .as_lat_lon()
            .map(|grid| grid.longitudes_with_limit(self.options.max_axis_points))
            .transpose()
    }

    pub fn projected_x_coordinates(&self) -> Result<Option<Vec<f64>>> {
        self.metadata
            .grid
            .projected_x_coordinates_with_limit(self.options.max_axis_points)
    }

    pub fn projected_y_coordinates(&self) -> Result<Option<Vec<f64>>> {
        self.metadata
            .grid
            .projected_y_coordinates_with_limit(self.options.max_axis_points)
    }

    pub fn decode_into<T: DecodeSample>(&self, out: &mut [T]) -> Result<()> {
        self.metadata.grid.validate_supported_scan_order()?;
        let num_grid_points = self.checked_num_points()?;
        if out.len() != num_grid_points {
            return Err(Error::DataLengthMismatch {
                expected: num_grid_points,
                actual: out.len(),
            });
        }

        match &self.decode_plan {
            DecodePlan::Grib2(field) => {
                let data_section = section_bytes(self.bytes, field.data);
                let bitmap_section = match field.bitmap {
                    Some(section) => grib2_bitmap_payload(section_bytes(self.bytes, section))?,
                    None => None,
                };
                decode_field_into(
                    data_section,
                    &self.metadata.data_representation,
                    bitmap_section,
                    num_grid_points,
                    out,
                )?
            }
            DecodePlan::Grib1 { bitmap, data } => {
                let bitmap_section = match bitmap {
                    Some(Grib1BitmapSource::Explicit(section)) => {
                        grib1::bitmap_payload(section_bytes(self.bytes, *section))?
                    }
                    Some(Grib1BitmapSource::Predefined(payload)) => Some(payload.as_ref()),
                    None => None,
                };
                let data_section = section_bytes(self.bytes, *data);
                if data_section.len() < 11 {
                    return Err(Error::InvalidSection {
                        section: 4,
                        reason: format!("expected at least 11 bytes, got {}", data_section.len()),
                    });
                }
                decode_payload_into(
                    &data_section[11..],
                    &self.metadata.data_representation,
                    bitmap_section,
                    num_grid_points,
                    out,
                )?
            }
        }

        self.metadata.grid.reorder_for_ndarray_in_place(out)
    }

    pub fn read_flat_data_as_f64(&self) -> Result<Vec<f64>> {
        let num_grid_points = self.checked_num_points()?;
        let mut decoded = zeroed_vec(num_grid_points, 0.0_f64, "decoded f64 field")?;
        self.decode_into(&mut decoded)?;
        Ok(decoded)
    }

    pub fn read_flat_data_as_f32(&self) -> Result<Vec<f32>> {
        let num_grid_points = self.checked_num_points()?;
        let mut decoded = zeroed_vec(num_grid_points, 0.0_f32, "decoded f32 field")?;
        self.decode_into(&mut decoded)?;
        Ok(decoded)
    }

    pub fn read_data_as_f64(&self) -> Result<ArrayD<f64>> {
        let ordered = self.read_flat_data_as_f64()?;
        ArrayD::from_shape_vec(IxDyn(&self.metadata.grid.ndarray_shape()), ordered)
            .map_err(|e| Error::Other(format!("failed to build ndarray from decoded field: {e}")))
    }

    pub fn read_data_as_f32(&self) -> Result<ArrayD<f32>> {
        let ordered = self.read_flat_data_as_f32()?;
        ArrayD::from_shape_vec(IxDyn(&self.metadata.grid.ndarray_shape()), ordered)
            .map_err(|e| Error::Other(format!("failed to build ndarray from decoded field: {e}")))
    }

    pub fn raw_bytes(&self) -> &[u8] {
        self.bytes
    }

    fn checked_num_points(&self) -> Result<usize> {
        let num_grid_points = self.metadata.grid.checked_num_points()?;
        ensure_limit(
            "decoded grid points",
            num_grid_points,
            self.options.max_decoded_points,
        )?;
        Ok(num_grid_points)
    }
}

/// Iterator over fields in a GRIB file.
pub struct MessageIter<'a> {
    file: &'a GribFile,
    index: usize,
}

impl<'a> Iterator for MessageIter<'a> {
    type Item = Message<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.file.message_count() {
            return None;
        }
        let message = self.file.message(self.index).ok()?;
        self.index += 1;
        Some(message)
    }
}

fn section_bytes(msg_bytes: &[u8], section: SectionRef) -> &[u8] {
    &msg_bytes[section.offset..section.offset + section.length]
}

fn zeroed_vec<T: Copy>(len: usize, value: T, what: &'static str) -> Result<Vec<T>> {
    let mut out = Vec::new();
    out.try_reserve(len)
        .map_err(|e| Error::Other(format!("failed to reserve {len} {what} values: {e}")))?;
    out.resize(len, value);
    Ok(out)
}

fn ensure_limit(what: &'static str, requested: usize, limit: Option<usize>) -> Result<()> {
    if let Some(limit) = limit {
        if requested > limit {
            return Err(Error::LimitExceeded {
                what,
                requested,
                limit,
            });
        }
    }
    Ok(())
}

fn scan_messages(
    data: &[u8],
    options: OpenOptions,
    local_parameters: &[LocalParameterEntry<'_>],
    predefined_bitmaps: &[PredefinedBitmap<'_>],
) -> Result<Vec<MessageIndex>> {
    let mut messages = Vec::new();
    let mut pos = 0usize;

    while pos + 8 <= data.len() {
        if &data[pos..pos + 4] != GRIB_MAGIC {
            pos += 1;
            continue;
        }

        let (indicator, next_pos) = match locate_message(data, pos) {
            Ok(located) => located,
            Err(err) if !options.strict && is_recoverable_candidate_error(&err) => {
                pos += 4;
                continue;
            }
            Err(err) => return Err(err),
        };

        let message_bytes = &data[pos..next_pos];
        let indexed = match indicator.edition {
            1 => index_grib1_message(message_bytes, pos, options, predefined_bitmaps)?,
            2 => index_grib2_message(message_bytes, pos, options, &indicator, local_parameters)?,
            other => return Err(Error::UnsupportedEdition(other)),
        };

        messages.extend(indexed);
        pos = next_pos;
    }

    Ok(messages)
}

fn is_recoverable_candidate_error(err: &Error) -> bool {
    matches!(err, Error::InvalidMessage(_) | Error::Truncated { .. })
}

fn locate_message(data: &[u8], pos: usize) -> Result<(Indicator, usize)> {
    let edition = Indicator::edition(&data[pos..]).ok_or_else(|| {
        Error::InvalidMessage(format!("failed to parse indicator at byte offset {pos}"))
    })?;
    if !matches!(edition, 1 | 2) {
        return Err(Error::UnsupportedEdition(edition));
    }

    let indicator = Indicator::parse(&data[pos..]).ok_or_else(|| {
        Error::InvalidMessage(format!("failed to parse indicator at byte offset {pos}"))
    })?;
    let length = indicator.total_length as usize;
    if length < 12 {
        return Err(Error::InvalidMessage(format!(
            "message at byte offset {pos} reports impossible length {length}"
        )));
    }
    let end = pos
        .checked_add(length)
        .ok_or_else(|| Error::InvalidMessage("message length overflow".into()))?;
    if end > data.len() {
        return Err(Error::Truncated { offset: end as u64 });
    }
    if &data[end - 4..end] != b"7777" {
        return Err(Error::InvalidMessage(format!(
            "message at byte offset {pos} does not end with 7777"
        )));
    }

    Ok((indicator, end))
}

fn index_grib1_message(
    message_bytes: &[u8],
    offset: usize,
    options: OpenOptions,
    predefined_bitmaps: &[PredefinedBitmap<'_>],
) -> Result<Vec<MessageIndex>> {
    let sections = grib1::parse_message_sections(message_bytes)?;
    let grid_ref = sections.grid.ok_or_else(|| {
        Error::InvalidSectionOrder(
            "GRIB1 decoding requires an explicit grid definition section".into(),
        )
    })?;
    let grid_description = GridDescription::parse(section_bytes(message_bytes, grid_ref))?;
    let grid = grid_description.grid;
    let num_grid_points = validate_grid_limits(&grid, options)?;

    let bitmap = match sections.bitmap {
        Some(section) => {
            let section_bytes = section_bytes(message_bytes, section);
            let table_reference = grib1::bitmap_table_reference(section_bytes)?;
            if table_reference == 0 {
                Some(Grib1BitmapSource::Explicit(section))
            } else {
                let payload = resolve_predefined_bitmap(
                    predefined_bitmaps,
                    sections.product.center_id as u16,
                    sections.product.subcenter_id as u16,
                    table_reference,
                )?;
                Some(Grib1BitmapSource::Predefined(Arc::from(payload)))
            }
        }
        None => None,
    };

    let bitmap_present_count = match &bitmap {
        Some(Grib1BitmapSource::Explicit(section)) => {
            let bitmap_payload = grib1::bitmap_payload(section_bytes(message_bytes, *section))?
                .ok_or(Error::MissingBitmap)?;
            count_bitmap_present_points(bitmap_payload, num_grid_points)?
        }
        Some(Grib1BitmapSource::Predefined(payload)) => {
            count_bitmap_present_points(payload, num_grid_points)?
        }
        None => num_grid_points,
    };

    let (_bds, data_representation) = BinaryDataSection::parse(
        section_bytes(message_bytes, sections.data),
        sections.product.decimal_scale,
        bitmap_present_count,
    )?;
    let parameter = sections.product.parameter();

    Ok(vec![MessageIndex {
        offset,
        length: message_bytes.len(),
        decode_plan: DecodePlan::Grib1 {
            bitmap,
            data: sections.data,
        },
        metadata: MessageMetadata {
            edition: 1,
            center_id: sections.product.center_id as u16,
            subcenter_id: sections.product.subcenter_id as u16,
            discipline: None,
            reference_time: sections.product.reference_time,
            parameter,
            grid,
            data_representation,
            forecast_time_unit: Some(sections.product.forecast_time_unit),
            forecast_time: sections.product.forecast_time(),
            message_offset: offset as u64,
            message_length: message_bytes.len() as u64,
            field_index_in_message: 0,
            grib1_product: Some(sections.product),
            grib2_identification: None,
            grib2_product: None,
        },
    }])
}

fn resolve_predefined_bitmap<'a>(
    predefined_bitmaps: &[PredefinedBitmap<'a>],
    center_id: u16,
    subcenter_id: u16,
    table_reference: u16,
) -> Result<&'a [u8]> {
    predefined_bitmaps
        .iter()
        .find(|entry| {
            entry.center_id == center_id
                && entry.subcenter_id == Some(subcenter_id)
                && entry.table_reference == table_reference
        })
        .or_else(|| {
            predefined_bitmaps.iter().find(|entry| {
                entry.center_id == center_id
                    && entry.subcenter_id.is_none()
                    && entry.table_reference == table_reference
            })
        })
        .map(|entry| entry.bitmap)
        .ok_or(Error::UnsupportedBitmapIndicator(table_reference))
}

fn validate_grid_limits(grid: &GridDefinition, options: OpenOptions) -> Result<usize> {
    let num_grid_points = grid.checked_num_points()?;
    ensure_limit(
        "decoded grid points",
        num_grid_points,
        options.max_decoded_points,
    )?;
    Ok(num_grid_points)
}

fn validate_grib2_grid_points(grid: &GridDefinition) -> Result<()> {
    let Some(declared) = grid.declared_num_points() else {
        return Ok(());
    };
    let projected = grid.shape_num_points()?;
    if declared != projected {
        return Err(Error::InvalidSection {
            section: 3,
            reason: format!(
                "grid template 3.{} declares {declared} points but Nx*Ny is {projected}",
                grid.template_number()
            ),
        });
    }
    Ok(())
}

fn index_grib2_message(
    message_bytes: &[u8],
    offset: usize,
    options: OpenOptions,
    indicator: &Indicator,
    local_parameters: &[LocalParameterEntry<'_>],
) -> Result<Vec<MessageIndex>> {
    let fields = index_fields(message_bytes)?;
    let mut messages = Vec::with_capacity(fields.len());

    for (field_index_in_message, field_sections) in fields.into_iter().enumerate() {
        let identification =
            Identification::parse(section_bytes(message_bytes, field_sections.identification))?;
        let grid_section = section_bytes(message_bytes, field_sections.grid);
        let grid = GridDefinition::parse(grid_section)?;
        validate_grib2_grid_points(&grid)?;
        validate_grid_limits(&grid, options)?;
        let product =
            ProductDefinition::parse(section_bytes(message_bytes, field_sections.product))?;
        let data_representation = DataRepresentation::parse(section_bytes(
            message_bytes,
            field_sections.data_representation,
        ))?;
        let parameter = lookup_parameter_with_local_entries(
            indicator.discipline,
            product.parameter_category,
            product.parameter_number,
            identification.center_id,
            identification.subcenter_id,
            identification.local_table_version,
            local_parameters,
        );

        messages.push(MessageIndex {
            offset,
            length: message_bytes.len(),
            decode_plan: DecodePlan::Grib2(field_sections),
            metadata: MessageMetadata {
                edition: indicator.edition,
                center_id: identification.center_id,
                subcenter_id: identification.subcenter_id,
                discipline: Some(indicator.discipline),
                reference_time: ReferenceTime {
                    year: identification.reference_year,
                    month: identification.reference_month,
                    day: identification.reference_day,
                    hour: identification.reference_hour,
                    minute: identification.reference_minute,
                    second: identification.reference_second,
                },
                parameter,
                grid,
                data_representation,
                forecast_time_unit: product.forecast_time_unit(),
                forecast_time: product.forecast_time(),
                message_offset: offset as u64,
                message_length: message_bytes.len() as u64,
                field_index_in_message,
                grib1_product: None,
                grib2_identification: Some(identification),
                grib2_product: Some(product),
            },
        });
    }

    Ok(messages)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn grib_i32_bytes(value: i32) -> [u8; 4] {
        if value >= 0 {
            (value as u32).to_be_bytes()
        } else {
            ((-value) as u32 | 0x8000_0000).to_be_bytes()
        }
    }

    fn build_indicator(total_len: usize, discipline: u8) -> Vec<u8> {
        let mut indicator = Vec::with_capacity(16);
        indicator.extend_from_slice(b"GRIB");
        indicator.extend_from_slice(&[0, 0]);
        indicator.push(discipline);
        indicator.push(2);
        indicator.extend_from_slice(&(total_len as u64).to_be_bytes());
        indicator
    }

    fn build_identification() -> Vec<u8> {
        let mut section = vec![0u8; 21];
        section[..4].copy_from_slice(&(21u32).to_be_bytes());
        section[4] = 1;
        section[5..7].copy_from_slice(&7u16.to_be_bytes());
        section[7..9].copy_from_slice(&0u16.to_be_bytes());
        section[9] = 35;
        section[10] = 1;
        section[11] = 1;
        section[12..14].copy_from_slice(&2026u16.to_be_bytes());
        section[14] = 3;
        section[15] = 20;
        section[16] = 12;
        section[17] = 0;
        section[18] = 0;
        section[19] = 0;
        section[20] = 1;
        section
    }

    fn build_grid(ni: u32, nj: u32, scanning_mode: u8) -> Vec<u8> {
        let mut section = vec![0u8; 72];
        section[..4].copy_from_slice(&(72u32).to_be_bytes());
        section[4] = 3;
        section[6..10].copy_from_slice(&(ni * nj).to_be_bytes());
        section[12..14].copy_from_slice(&0u16.to_be_bytes());
        section[30..34].copy_from_slice(&ni.to_be_bytes());
        section[34..38].copy_from_slice(&nj.to_be_bytes());
        section[46..50].copy_from_slice(&grib_i32_bytes(50_000_000));
        section[50..54].copy_from_slice(&grib_i32_bytes(-120_000_000));
        section[55..59].copy_from_slice(&grib_i32_bytes(49_000_000));
        section[59..63].copy_from_slice(&grib_i32_bytes(-119_000_000));
        section[63..67].copy_from_slice(&1_000_000u32.to_be_bytes());
        section[67..71].copy_from_slice(&1_000_000u32.to_be_bytes());
        section[71] = scanning_mode;
        section
    }

    fn build_product(parameter_category: u8, parameter_number: u8) -> Vec<u8> {
        let mut section = vec![0u8; 34];
        section[..4].copy_from_slice(&(34u32).to_be_bytes());
        section[4] = 4;
        section[7..9].copy_from_slice(&0u16.to_be_bytes());
        section[9] = parameter_category;
        section[10] = parameter_number;
        section[11] = 2;
        section[17] = 1;
        section[18..22].copy_from_slice(&0u32.to_be_bytes());
        section[22] = 103;
        section[23] = 0;
        section[24..28].copy_from_slice(&850u32.to_be_bytes());
        section[28] = 255;
        section
    }

    fn build_simple_representation(encoded_values: usize, bits_per_value: u8) -> Vec<u8> {
        let mut section = vec![0u8; 21];
        section[..4].copy_from_slice(&(21u32).to_be_bytes());
        section[4] = 5;
        section[5..9].copy_from_slice(&(encoded_values as u32).to_be_bytes());
        section[9..11].copy_from_slice(&0u16.to_be_bytes());
        section[11..15].copy_from_slice(&0f32.to_be_bytes());
        section[19] = bits_per_value;
        section[20] = 0;
        section
    }

    fn pack_u8_values(values: &[u8]) -> Vec<u8> {
        values.to_vec()
    }

    fn build_bitmap(bits: &[bool]) -> Vec<u8> {
        let payload_len = bits.len().div_ceil(8) + 1;
        let mut section = vec![0u8; payload_len + 5];
        section[..4].copy_from_slice(&((payload_len + 5) as u32).to_be_bytes());
        section[4] = 6;
        section[5] = 0;
        for (index, bit) in bits.iter().copied().enumerate() {
            if bit {
                section[6 + index / 8] |= 1 << (7 - (index % 8));
            }
        }
        section
    }

    fn build_data(payload: &[u8]) -> Vec<u8> {
        let mut section = vec![0u8; payload.len() + 5];
        section[..4].copy_from_slice(&((payload.len() + 5) as u32).to_be_bytes());
        section[4] = 7;
        section[5..].copy_from_slice(payload);
        section
    }

    fn assemble_grib2_message(sections: &[Vec<u8>]) -> Vec<u8> {
        let total_len = 16 + sections.iter().map(|section| section.len()).sum::<usize>() + 4;
        let mut message = build_indicator(total_len, 0);
        for section in sections {
            message.extend_from_slice(section);
        }
        message.extend_from_slice(b"7777");
        message
    }

    fn build_grib1_message(values: &[u8]) -> Vec<u8> {
        let mut pds = vec![0u8; 28];
        pds[..3].copy_from_slice(&[0, 0, 28]);
        pds[3] = 2;
        pds[4] = 7;
        pds[5] = 255;
        pds[6] = 0;
        pds[7] = 0b1000_0000;
        pds[8] = 11;
        pds[9] = 100;
        pds[10..12].copy_from_slice(&850u16.to_be_bytes());
        pds[12] = 26;
        pds[13] = 3;
        pds[14] = 20;
        pds[15] = 12;
        pds[16] = 0;
        pds[17] = 1;
        pds[18] = 0;
        pds[19] = 0;
        pds[20] = 0;
        pds[24] = 21;
        pds[25] = 0;

        let mut gds = vec![0u8; 32];
        gds[..3].copy_from_slice(&[0, 0, 32]);
        gds[5] = 0;
        gds[6..8].copy_from_slice(&2u16.to_be_bytes());
        gds[8..10].copy_from_slice(&2u16.to_be_bytes());
        gds[10..13].copy_from_slice(&[0x01, 0x4d, 0x50]);
        gds[13..16].copy_from_slice(&[0x81, 0xd4, 0xc0]);
        gds[16] = 0x80;
        gds[17..20].copy_from_slice(&[0x01, 0x49, 0x68]);
        gds[20..23].copy_from_slice(&[0x81, 0xd0, 0xd8]);
        gds[23..25].copy_from_slice(&1000u16.to_be_bytes());
        gds[25..27].copy_from_slice(&1000u16.to_be_bytes());

        let mut bds = vec![0u8; 11 + values.len()];
        let len = bds.len() as u32;
        bds[..3].copy_from_slice(&[(len >> 16) as u8, (len >> 8) as u8, len as u8]);
        bds[3] = 0;
        bds[10] = 8;
        bds[11..].copy_from_slice(values);

        let total_len = 8 + pds.len() + gds.len() + bds.len() + 4;
        let mut message = Vec::new();
        message.extend_from_slice(b"GRIB");
        message.extend_from_slice(&[
            ((total_len >> 16) & 0xff) as u8,
            ((total_len >> 8) & 0xff) as u8,
            (total_len & 0xff) as u8,
            1,
        ]);
        message.extend_from_slice(&pds);
        message.extend_from_slice(&gds);
        message.extend_from_slice(&bds);
        message.extend_from_slice(b"7777");
        message
    }

    fn build_grib1_message_with_predefined_bitmap(values: &[u8], table_reference: u16) -> Vec<u8> {
        let mut message = build_grib1_message(values);
        message[8 + 7] = 0b1100_0000;

        let mut bitmap = [0u8; 6];
        bitmap[..3].copy_from_slice(&[0, 0, 6]);
        bitmap[4..6].copy_from_slice(&table_reference.to_be_bytes());

        let bitmap_offset = 8 + 28 + 32;
        message.splice(bitmap_offset..bitmap_offset, bitmap);
        let total_len = message.len();
        message[4] = ((total_len >> 16) & 0xff) as u8;
        message[5] = ((total_len >> 8) & 0xff) as u8;
        message[6] = (total_len & 0xff) as u8;
        message
    }

    #[test]
    fn scans_single_grib2_message() {
        let message = assemble_grib2_message(&[
            build_identification(),
            build_grid(2, 2, 0),
            build_product(0, 0),
            build_simple_representation(4, 8),
            build_data(&pack_u8_values(&[1, 2, 3, 4])),
        ]);
        let messages = scan_messages(&message, OpenOptions::default(), &[], &[]).unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].metadata.parameter.short_name, "TMP");
    }

    #[test]
    fn decodes_simple_grib2_message_to_ndarray() {
        let message = assemble_grib2_message(&[
            build_identification(),
            build_grid(2, 2, 0),
            build_product(0, 0),
            build_simple_representation(4, 8),
            build_data(&pack_u8_values(&[1, 2, 3, 4])),
        ]);
        let file = GribFile::from_bytes(message).unwrap();
        let array = file.message(0).unwrap().read_data_as_f64().unwrap();
        assert_eq!(array.shape(), &[2, 2]);
        assert_eq!(
            array.iter().copied().collect::<Vec<_>>(),
            vec![1.0, 2.0, 3.0, 4.0]
        );
    }

    #[test]
    fn applies_bitmap_to_missing_values() {
        let message = assemble_grib2_message(&[
            build_identification(),
            build_grid(2, 2, 0),
            build_product(0, 1),
            build_simple_representation(3, 8),
            build_bitmap(&[true, false, true, true]),
            build_data(&pack_u8_values(&[10, 20, 30])),
        ]);
        let file = GribFile::from_bytes(message).unwrap();
        let array = file.message(0).unwrap().read_data_as_f64().unwrap();
        let values = array.iter().copied().collect::<Vec<_>>();
        assert_eq!(values[0], 10.0);
        assert!(values[1].is_nan());
        assert_eq!(values[2], 20.0);
        assert_eq!(values[3], 30.0);
    }

    #[test]
    fn indexes_multiple_fields_in_one_grib2_message() {
        let message = assemble_grib2_message(&[
            build_identification(),
            build_grid(2, 2, 0),
            build_product(0, 0),
            build_simple_representation(4, 8),
            build_data(&pack_u8_values(&[1, 2, 3, 4])),
            build_product(0, 2),
            build_simple_representation(4, 8),
            build_data(&pack_u8_values(&[5, 6, 7, 8])),
        ]);
        let file = GribFile::from_bytes(message).unwrap();
        assert_eq!(file.message_count(), 2);
        assert_eq!(file.message(0).unwrap().parameter_name(), "TMP");
        assert_eq!(file.message(1).unwrap().parameter_name(), "POT");
    }

    #[test]
    fn decodes_simple_grib1_message_to_ndarray() {
        let message = build_grib1_message(&[1, 2, 3, 4]);
        let file = GribFile::from_bytes(message).unwrap();
        assert_eq!(file.edition(), 1);
        let field = file.message(0).unwrap();
        assert_eq!(field.parameter_name(), "TMP");
        assert!(field.identification().is_none());
        assert!(field.grib1_product_definition().is_some());
        let array = field.read_data_as_f64().unwrap();
        assert_eq!(array.shape(), &[2, 2]);
        assert_eq!(
            array.iter().copied().collect::<Vec<_>>(),
            vec![1.0, 2.0, 3.0, 4.0]
        );
    }

    #[test]
    fn decodes_grib1_predefined_bitmap_when_supplied() {
        let message = build_grib1_message_with_predefined_bitmap(&[9, 7], 300);
        let bitmap = [0b1010_0000];
        let predefined = [PredefinedBitmap {
            center_id: 7,
            subcenter_id: Some(0),
            table_reference: 300,
            bitmap: &bitmap,
        }];

        let file = GribFile::from_bytes_with_grib1_predefined_bitmaps(
            message,
            OpenOptions::default(),
            &predefined,
        )
        .unwrap();
        let decoded = file.message(0).unwrap().read_flat_data_as_f64().unwrap();
        assert_eq!(decoded[0], 9.0);
        assert!(decoded[1].is_nan());
        assert_eq!(decoded[2], 7.0);
        assert!(decoded[3].is_nan());
    }

    #[test]
    fn rejects_grib1_predefined_bitmap_without_supplied_table() {
        let message = build_grib1_message_with_predefined_bitmap(&[9, 7], 300);
        let err = match GribFile::from_bytes(message) {
            Ok(_) => panic!("expected unsupported predefined bitmap"),
            Err(err) => err,
        };

        assert!(matches!(err, Error::UnsupportedBitmapIndicator(300)));
    }
}