grib-core 0.8.0

Shared GRIB data model, primitives, and code tables
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
//! GRIB Edition 1 shared metadata and section models.

use crate::binary::{decode_ibm_f32, decode_wmo_i16, decode_wmo_i24};
use crate::bit::read_bit;
use crate::data::{
    DataRepresentation, Grib1SecondOrderLayout, Grib1SecondOrderPackingParams, ScaledPackingParams,
};
use crate::error::{Error, Result};
use crate::grid::{GridDefinition, LatLonGrid, MISSING_INCREMENT};
use crate::metadata::{Parameter, ReferenceTime};
use crate::parameter;

/// GRIB1 product definition metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProductDefinition {
    pub table_version: u8,
    pub center_id: u8,
    pub generating_process_id: u8,
    pub grid_id: u8,
    pub has_grid_definition: bool,
    pub has_bitmap: bool,
    pub parameter_number: u8,
    pub level_type: u8,
    pub level_value: u16,
    pub reference_time: ReferenceTime,
    pub forecast_time_unit: u8,
    pub p1: u8,
    pub p2: u8,
    pub time_range_indicator: u8,
    pub average_count: u16,
    pub missing_count: u8,
    pub century: u8,
    pub subcenter_id: u8,
    pub decimal_scale: i16,
}

impl ProductDefinition {
    pub fn parse(section_bytes: &[u8]) -> Result<Self> {
        if section_bytes.len() < 28 {
            return Err(Error::InvalidSection {
                section: 1,
                reason: format!("expected at least 28 bytes, got {}", section_bytes.len()),
            });
        }

        Ok(Self {
            table_version: section_bytes[3],
            center_id: section_bytes[4],
            generating_process_id: section_bytes[5],
            grid_id: section_bytes[6],
            has_grid_definition: section_bytes[7] & 0b1000_0000 != 0,
            has_bitmap: section_bytes[7] & 0b0100_0000 != 0,
            parameter_number: section_bytes[8],
            level_type: section_bytes[9],
            level_value: u16::from_be_bytes(section_bytes[10..12].try_into().unwrap()),
            reference_time: parse_reference_time(section_bytes)?,
            forecast_time_unit: section_bytes[17],
            p1: section_bytes[18],
            p2: section_bytes[19],
            time_range_indicator: section_bytes[20],
            average_count: u16::from_be_bytes(section_bytes[21..23].try_into().unwrap()),
            missing_count: section_bytes[23],
            century: section_bytes[24],
            subcenter_id: section_bytes[25],
            decimal_scale: decode_wmo_i16(&section_bytes[26..28]).unwrap(),
        })
    }

    pub fn parameter(&self) -> Parameter {
        let short_name = parameter::grib1_parameter_name(self.table_version, self.parameter_number);
        let description =
            parameter::grib1_parameter_description(self.table_version, self.parameter_number);
        Parameter::new_grib1(
            self.table_version,
            self.parameter_number,
            short_name,
            description,
        )
    }

    pub fn forecast_time(&self) -> Option<u32> {
        match self.time_range_indicator {
            0 | 1 => Some(u32::from(self.p1)),
            10 => Some(u32::from(u16::from_be_bytes([self.p1, self.p2]))),
            _ => None,
        }
    }

    /// Offset from the reference time at which the product is valid, in
    /// `forecast_time_unit` units.
    ///
    /// Ranges, averages, accumulations, and differences (time range
    /// indicators 2 through 5) are valid at the end of their period, `P2`.
    pub fn valid_time_offset(&self) -> Option<u32> {
        match self.time_range_indicator {
            2..=5 => Some(u32::from(self.p2)),
            _ => self.forecast_time(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct GridDescription {
    pub nv: u8,
    pub pv_or_pl: u8,
    pub data_representation_type: u8,
    pub grid: GridDefinition,
}

impl GridDescription {
    pub fn parse(section_bytes: &[u8]) -> Result<Self> {
        if section_bytes.len() < 32 {
            return Err(Error::InvalidSection {
                section: 2,
                reason: format!("expected at least 32 bytes, got {}", section_bytes.len()),
            });
        }

        let data_representation_type = section_bytes[5];
        let grid = match data_representation_type {
            0 => parse_latlon_grid(section_bytes)?,
            other => GridDefinition::Unsupported(u16::from(other)),
        };

        Ok(Self {
            nv: section_bytes[3],
            pv_or_pl: section_bytes[4],
            data_representation_type,
            grid,
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct BinaryDataSection {
    pub flags: u8,
    pub unused_bits: u8,
    pub binary_scale: i16,
    pub reference_value: f32,
    pub bits_per_value: u8,
}

impl BinaryDataSection {
    pub fn parse(
        section_bytes: &[u8],
        decimal_scale: i16,
        encoded_values: usize,
    ) -> Result<(Self, DataRepresentation)> {
        if section_bytes.len() < 11 {
            return Err(Error::InvalidSection {
                section: 4,
                reason: format!("expected at least 11 bytes, got {}", section_bytes.len()),
            });
        }

        let data_flag = section_bytes[3];
        let flags = data_flag >> 4;
        if flags & 0b1000 != 0 {
            return Err(Error::UnsupportedDataTemplate(1004));
        }

        let binary_scale = decode_wmo_i16(&section_bytes[4..6]).unwrap();
        let reference_value = decode_ibm_f32(section_bytes[6..10].try_into().unwrap());
        let bits_per_value = section_bytes[10];
        if bits_per_value > 64 {
            return Err(Error::UnsupportedPackingWidth(bits_per_value));
        }
        let packing = ScaledPackingParams {
            encoded_values,
            reference_value,
            binary_scale,
            decimal_scale,
            bits_per_value,
            original_field_type: u8::from(flags & 0b0010 != 0),
        };
        let representation = if flags & 0b0100 != 0 {
            parse_second_order_packing(section_bytes, packing, data_flag & 0x0f)?
        } else {
            if flags & 0b0001 != 0 {
                return Err(Error::UnsupportedDataTemplate(1007));
            }
            DataRepresentation::SimplePacking(packing)
        };

        Ok((
            Self {
                flags,
                unused_bits: data_flag & 0x0f,
                binary_scale,
                reference_value,
                bits_per_value,
            },
            representation,
        ))
    }
}

fn parse_second_order_packing(
    section: &[u8],
    packing: ScaledPackingParams,
    unused_bits: u8,
) -> Result<DataRepresentation> {
    if section.len() < 22 {
        return Err(invalid_second_order(format!(
            "requires at least 22 bytes, got {}",
            section.len()
        )));
    }

    let n1 = usize::from(u16::from_be_bytes(section[11..13].try_into().unwrap()));
    let extended_flags = section[13];
    let n2 = usize::from(u16::from_be_bytes(section[14..16].try_into().unwrap()));
    let coded_group_count = usize::from(u16::from_be_bytes(section[16..18].try_into().unwrap()));
    let encoded_values = usize::from(u16::from_be_bytes(section[18..20].try_into().unwrap()));
    if section[20] != 0 {
        return Err(invalid_second_order(format!(
            "reserved octet 21 must be zero, got {}",
            section[20]
        )));
    }
    let group_count = coded_group_count;

    if encoded_values != packing.encoded_values {
        return Err(Error::DataLengthMismatch {
            expected: packing.encoded_values,
            actual: encoded_values,
        });
    }
    if extended_flags & 0x80 != 0 {
        return Err(invalid_second_order("reserved extended flag bit 1 is set"));
    }
    if extended_flags & 0x40 != 0 {
        return Err(invalid_second_order(
            "matrix-valued grid points are not supported",
        ));
    }
    if extended_flags & 0x0f != 0 {
        return Err(invalid_second_order(format!(
            "non-WMO extended ordering or spatial differencing flags are set: 0x{:02x}",
            extended_flags & 0x0f
        )));
    }

    let has_secondary_bitmap = extended_flags & 0x20 != 0;
    let has_variable_widths = extended_flags & 0x10 != 0;
    let layout = match (has_secondary_bitmap, has_variable_widths) {
        (false, true) => Grib1SecondOrderLayout::RowByRow,
        (true, false) => Grib1SecondOrderLayout::ConstantWidth,
        (true, true) => Grib1SecondOrderLayout::VariableWidth,
        (false, false) => {
            return Err(invalid_second_order(
                "constant-width groups require a secondary bitmap",
            ));
        }
    };

    if encoded_values > 0 && group_count == 0 {
        return Err(invalid_second_order(
            "non-empty fields require at least one group",
        ));
    }

    let width_count = match layout {
        Grib1SecondOrderLayout::ConstantWidth => 1,
        Grib1SecondOrderLayout::RowByRow | Grib1SecondOrderLayout::VariableWidth => group_count,
    };
    let descriptors_end = 21_usize
        .checked_add(width_count)
        .ok_or(Error::ArithmeticOverflow {
            operation: "computing GRIB1 second-order width descriptor boundary",
        })?;
    let secondary_bitmap_bytes = if has_secondary_bitmap {
        encoded_values.div_ceil(8)
    } else {
        0
    };
    let expected_first_order_index =
        descriptors_end
            .checked_add(secondary_bitmap_bytes)
            .ok_or(Error::ArithmeticOverflow {
                operation: "computing GRIB1 first-order value offset",
            })?;
    let first_order_index = n1
        .checked_sub(1)
        .ok_or_else(|| invalid_second_order("N1 must be a one-based octet position"))?;
    if first_order_index != expected_first_order_index {
        return Err(invalid_second_order(format!(
            "N1 points to octet {n1}, expected {}",
            expected_first_order_index + 1
        )));
    }
    if expected_first_order_index > section.len() {
        return Err(invalid_second_order(format!(
            "width descriptors and secondary bitmap require {expected_first_order_index} bytes, got {}",
            section.len()
        )));
    }

    let width_bytes = &section[21..descriptors_end];
    if width_bytes.iter().any(|width| *width > 64) {
        let width = width_bytes
            .iter()
            .copied()
            .find(|width| *width > 64)
            .expect("out-of-range width exists");
        return Err(Error::UnsupportedPackingWidth(width));
    }
    let mut group_widths = Vec::new();
    group_widths
        .try_reserve_exact(width_count)
        .map_err(|error| Error::allocation("GRIB1 group widths", width_count, error))?;
    group_widths.extend_from_slice(width_bytes);

    let group_lengths = if has_secondary_bitmap {
        parse_secondary_group_lengths(
            &section[descriptors_end..expected_first_order_index],
            encoded_values,
            group_count,
        )?
    } else {
        Vec::new()
    };

    let first_order_bits = group_count
        .checked_mul(usize::from(packing.bits_per_value))
        .ok_or(Error::BitOffsetOverflow)?;
    let expected_second_order_index = expected_first_order_index
        .checked_add(first_order_bits.div_ceil(8))
        .ok_or(Error::ArithmeticOverflow {
            operation: "computing GRIB1 second-order value offset",
        })?;
    let second_order_index = n2
        .checked_sub(1)
        .ok_or_else(|| invalid_second_order("N2 must be a one-based octet position"))?;
    if second_order_index != expected_second_order_index {
        return Err(invalid_second_order(format!(
            "N2 points to octet {n2}, expected {}",
            expected_second_order_index + 1
        )));
    }
    if second_order_index > section.len() {
        return Err(invalid_second_order(format!(
            "first-order values require {second_order_index} bytes, got {}",
            section.len()
        )));
    }

    let first_order_values_offset = first_order_index - 11;
    let second_order_values_offset = second_order_index - 11;
    let payload_bits = section[11..]
        .len()
        .checked_mul(8)
        .ok_or(Error::BitOffsetOverflow)?;
    let usable_bits = payload_bits
        .checked_sub(usize::from(unused_bits))
        .ok_or_else(|| invalid_second_order("unused-bit count exceeds the BDS payload"))?;
    let second_order_start = second_order_values_offset
        .checked_mul(8)
        .ok_or(Error::BitOffsetOverflow)?;

    if layout != Grib1SecondOrderLayout::RowByRow {
        let second_order_bits =
            group_lengths
                .iter()
                .enumerate()
                .try_fold(0usize, |total, (group_index, length)| {
                    let width = match layout {
                        Grib1SecondOrderLayout::ConstantWidth => group_widths[0],
                        Grib1SecondOrderLayout::VariableWidth => group_widths[group_index],
                        Grib1SecondOrderLayout::RowByRow => unreachable!(),
                    };
                    length
                        .checked_mul(usize::from(width))
                        .and_then(|bits| total.checked_add(bits))
                        .ok_or(Error::BitOffsetOverflow)
                })?;
        let expected_end = second_order_start
            .checked_add(second_order_bits)
            .ok_or(Error::BitOffsetOverflow)?;
        if expected_end != usable_bits {
            return Err(invalid_second_order(format!(
                "packed values end at bit {expected_end}, but the usable BDS payload ends at bit {usable_bits}"
            )));
        }
    } else if second_order_start > usable_bits {
        return Err(invalid_second_order(
            "N2 points beyond the usable BDS payload",
        ));
    }

    Ok(DataRepresentation::Grib1SecondOrderPacking(
        Grib1SecondOrderPackingParams {
            packing,
            layout,
            group_count,
            group_widths,
            group_lengths,
            first_order_values_offset,
            second_order_values_offset,
            unused_bits,
        },
    ))
}

fn parse_secondary_group_lengths(
    bitmap: &[u8],
    encoded_values: usize,
    group_count: usize,
) -> Result<Vec<usize>> {
    if encoded_values == 0 {
        if group_count == 0 {
            return Ok(Vec::new());
        }
        return Err(invalid_second_order(format!(
            "empty secondary bitmap cannot describe {group_count} groups"
        )));
    }
    if !read_bit(bitmap, 0)? {
        return Err(invalid_second_order(
            "secondary bitmap must start with a group boundary",
        ));
    }

    let mut lengths = Vec::new();
    lengths
        .try_reserve_exact(group_count)
        .map_err(|error| Error::allocation("GRIB1 group lengths", group_count, error))?;
    let mut group_start = 0usize;
    for bit_index in 1..encoded_values {
        if read_bit(bitmap, bit_index)? {
            lengths.push(bit_index - group_start);
            group_start = bit_index;
        }
    }
    lengths.push(encoded_values - group_start);
    if lengths.len() != group_count {
        return Err(invalid_second_order(format!(
            "secondary bitmap defines {} groups, but P1 declares {group_count}",
            lengths.len()
        )));
    }
    Ok(lengths)
}

fn invalid_second_order(reason: impl Into<String>) -> Error {
    Error::InvalidSection {
        section: 4,
        reason: format!("invalid GRIB1 second-order packing: {}", reason.into()),
    }
}

fn parse_reference_time(section_bytes: &[u8]) -> Result<ReferenceTime> {
    let century = section_bytes[24];
    let year_of_century = u16::from(section_bytes[12]);
    let year = match century {
        0 => year_of_century,
        c => (u16::from(c) - 1) * 100 + year_of_century,
    };

    let reference_time = ReferenceTime {
        year,
        month: section_bytes[13],
        day: section_bytes[14],
        hour: section_bytes[15],
        minute: section_bytes[16],
        second: 0,
    };
    reference_time.validate_in_section(1)?;
    Ok(reference_time)
}

fn parse_latlon_grid(section_bytes: &[u8]) -> Result<GridDefinition> {
    let ni = u32::from(u16::from_be_bytes(section_bytes[6..8].try_into().unwrap()));
    let nj = u32::from(u16::from_be_bytes(section_bytes[8..10].try_into().unwrap()));
    let lat_first = parse_coordinate(&section_bytes[10..13], 90_000_000, "first latitude")?;
    let lon_first = parse_coordinate(&section_bytes[13..16], 360_000_000, "first longitude")?;
    let lat_last = parse_coordinate(&section_bytes[17..20], 90_000_000, "last latitude")?;
    let lon_last = parse_coordinate(&section_bytes[20..23], 360_000_000, "last longitude")?;
    let increments_given = section_bytes[16] & 0x80 != 0;
    let di = parse_increment(&section_bytes[23..25], increments_given);
    let dj = parse_increment(&section_bytes[25..27], increments_given);
    let scanning_mode = section_bytes[27];

    Ok(GridDefinition::LatLon(LatLonGrid {
        ni,
        nj,
        lat_first,
        lon_first,
        lat_last,
        lon_last,
        di,
        dj,
        scanning_mode,
    }))
}

/// Converts a GRIB1 millidegree increment to microdegrees, mapping the
/// all-ones pattern and increments flagged as not given to
/// [`MISSING_INCREMENT`].
fn parse_increment(bytes: &[u8], given: bool) -> u32 {
    let raw = u16::from_be_bytes(bytes.try_into().unwrap());
    if !given || raw == u16::MAX {
        MISSING_INCREMENT
    } else {
        u32::from(raw) * 1_000
    }
}

fn parse_coordinate(bytes: &[u8], absolute_limit: i64, name: &str) -> Result<i32> {
    let millidegrees = decode_wmo_i24(bytes).ok_or_else(|| Error::InvalidSection {
        section: 2,
        reason: format!("truncated {name}"),
    })?;
    let microdegrees = i64::from(millidegrees) * 1_000;
    if microdegrees.abs() > absolute_limit {
        return Err(Error::InvalidSection {
            section: 2,
            reason: format!(
                "{name} {microdegrees} microdegrees is outside the valid range -{absolute_limit}..={absolute_limit}"
            ),
        });
    }

    i32::try_from(microdegrees).map_err(|_| Error::InvalidSection {
        section: 2,
        reason: format!("{name} does not fit the internal microdegree representation"),
    })
}

#[cfg(test)]
mod tests {
    use super::{BinaryDataSection, GridDescription, ProductDefinition};
    use crate::data::{DataRepresentation, Grib1SecondOrderLayout};
    use crate::error::Error;
    use crate::grid::{GridDefinition, MISSING_INCREMENT};
    use crate::metadata::ReferenceTime;

    #[test]
    fn decodes_indicator_ten_forecast_time_as_u16() {
        let product = ProductDefinition {
            table_version: 2,
            center_id: 7,
            generating_process_id: 255,
            grid_id: 0,
            has_grid_definition: true,
            has_bitmap: false,
            parameter_number: 11,
            level_type: 100,
            level_value: 850,
            reference_time: ReferenceTime {
                year: 2026,
                month: 3,
                day: 20,
                hour: 12,
                minute: 0,
                second: 0,
            },
            forecast_time_unit: 1,
            p1: 0x01,
            p2: 0x2c,
            time_range_indicator: 10,
            average_count: 0,
            missing_count: 0,
            century: 21,
            subcenter_id: 0,
            decimal_scale: 0,
        };

        assert_eq!(product.forecast_time(), Some(300));
    }

    #[test]
    fn rejects_invalid_product_definition_reference_time() {
        let mut section = valid_product_definition_section();
        section[13] = 2;
        section[14] = 29;
        let err = ProductDefinition::parse(&section).unwrap_err();
        assert!(matches!(err, Error::InvalidSection { section: 1, .. }));
        assert!(err.to_string().contains("invalid reference timestamp"));

        let mut section = valid_product_definition_section();
        section[15] = 24;
        let err = ProductDefinition::parse(&section).unwrap_err();
        assert!(matches!(err, Error::InvalidSection { section: 1, .. }));

        let mut section = valid_product_definition_section();
        section[16] = 60;
        let err = ProductDefinition::parse(&section).unwrap_err();
        assert!(matches!(err, Error::InvalidSection { section: 1, .. }));
    }

    #[test]
    fn rejects_grib1_coordinates_outside_geographic_bounds_without_overflowing() {
        let mut section = valid_grid_description_section();
        section[10..13].copy_from_slice(&[0x7f, 0xff, 0xff]);

        let err = GridDescription::parse(&section).unwrap_err();
        assert!(matches!(err, Error::InvalidSection { section: 2, .. }));
        assert!(err.to_string().contains("first latitude"));

        let mut section = valid_grid_description_section();
        section[13..16].copy_from_slice(&[0xff, 0xff, 0xff]);

        let err = GridDescription::parse(&section).unwrap_err();
        assert!(matches!(err, Error::InvalidSection { section: 2, .. }));
        assert!(err.to_string().contains("first longitude"));
    }

    #[test]
    fn maps_grib1_increments_not_given_to_missing_and_infers_axes() {
        let grid_of = |section: &[u8]| match GridDescription::parse(section).unwrap().grid {
            GridDefinition::LatLon(grid) => grid,
            other => panic!("expected a latitude/longitude grid, got {other:?}"),
        };

        let mut section = valid_grid_description_section();
        section[16] = 0x80;
        let given = grid_of(&section);
        assert_eq!((given.di, given.dj), (1_000_000, 1_000_000));

        section[23..25].copy_from_slice(&u16::MAX.to_be_bytes());
        assert_eq!(grid_of(&section).di, MISSING_INCREMENT);

        let not_given = grid_of(&valid_grid_description_section());
        assert_eq!(
            (not_given.di, not_given.dj),
            (MISSING_INCREMENT, MISSING_INCREMENT)
        );
        assert_eq!(not_given.longitudes().unwrap(), vec![0.0, 1.0]);
        assert_eq!(not_given.latitudes().unwrap(), vec![0.0, -1.0]);
    }

    #[test]
    fn parses_row_by_row_second_order_packing() {
        let section = second_order_section(Grib1SecondOrderLayout::RowByRow);
        let (_, representation) = BinaryDataSection::parse(&section, 0, 6).unwrap();
        let DataRepresentation::Grib1SecondOrderPacking(params) = representation else {
            panic!("expected GRIB1 second-order packing");
        };

        assert_eq!(params.layout(), Grib1SecondOrderLayout::RowByRow);
        assert_eq!(params.group_count(), 2);
        assert_eq!(params.group_widths(), &[2, 2]);
        assert!(params.group_lengths().is_empty());
        assert_eq!(params.first_order_values_offset(), 12);
        assert_eq!(params.second_order_values_offset(), 14);
    }

    #[test]
    fn parses_secondary_bitmap_second_order_layouts() {
        for layout in [
            Grib1SecondOrderLayout::ConstantWidth,
            Grib1SecondOrderLayout::VariableWidth,
        ] {
            let section = second_order_section(layout);
            let (_, representation) = BinaryDataSection::parse(&section, 0, 6).unwrap();
            let DataRepresentation::Grib1SecondOrderPacking(params) = representation else {
                panic!("expected GRIB1 second-order packing");
            };

            assert_eq!(params.layout(), layout);
            assert_eq!(params.group_count(), 2);
            assert_eq!(params.group_lengths(), &[3, 3]);
            if layout == Grib1SecondOrderLayout::ConstantWidth {
                assert_eq!(params.group_widths(), &[2]);
            } else {
                assert_eq!(params.group_widths(), &[2, 2]);
            }
        }
    }

    #[test]
    fn rejects_second_order_secondary_bitmap_without_initial_boundary() {
        let mut section = second_order_section(Grib1SecondOrderLayout::VariableWidth);
        section[23] = 0b0001_0000;
        let error = BinaryDataSection::parse(&section, 0, 6).unwrap_err();
        assert!(matches!(error, Error::InvalidSection { section: 4, .. }));
        assert!(error
            .to_string()
            .contains("must start with a group boundary"));
    }

    #[test]
    fn rejects_nonstandard_second_order_extensions_and_inconsistent_offsets() {
        let mut section = second_order_section(Grib1SecondOrderLayout::RowByRow);
        section[20] = 1;
        let error = BinaryDataSection::parse(&section, 0, 6).unwrap_err();
        assert!(error.to_string().contains("reserved octet 21"));

        let mut section = second_order_section(Grib1SecondOrderLayout::RowByRow);
        section[13] |= 0x04;
        let error = BinaryDataSection::parse(&section, 0, 6).unwrap_err();
        assert!(error.to_string().contains("non-WMO extended ordering"));

        let mut section = second_order_section(Grib1SecondOrderLayout::VariableWidth);
        section[14..16].copy_from_slice(&28u16.to_be_bytes());
        let error = BinaryDataSection::parse(&section, 0, 6).unwrap_err();
        assert!(error.to_string().contains("N2 points to octet 28"));
    }

    #[test]
    fn preserves_simple_integer_field_type() {
        let mut section = vec![0u8; 12];
        section[..3].copy_from_slice(&[0, 0, 12]);
        section[3] = 0x20;
        section[10] = 8;
        let (_, representation) = BinaryDataSection::parse(&section, 0, 1).unwrap();
        let DataRepresentation::SimplePacking(params) = representation else {
            panic!("expected simple packing");
        };
        assert_eq!(params.original_field_type, 1);
    }

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

    fn valid_grid_description_section() -> Vec<u8> {
        let mut section = vec![0u8; 32];
        section[..3].copy_from_slice(&[0, 0, 32]);
        section[5] = 0;
        section[6..8].copy_from_slice(&2u16.to_be_bytes());
        section[8..10].copy_from_slice(&2u16.to_be_bytes());
        section[10..13].copy_from_slice(&[0, 0, 0]);
        section[13..16].copy_from_slice(&[0, 0, 0]);
        section[17..20].copy_from_slice(&[0, 3, 0xe8]);
        section[20..23].copy_from_slice(&[0, 3, 0xe8]);
        section[23..25].copy_from_slice(&1_000u16.to_be_bytes());
        section[25..27].copy_from_slice(&1_000u16.to_be_bytes());
        section
    }

    fn second_order_section(layout: Grib1SecondOrderLayout) -> Vec<u8> {
        let (length, extended_flags, n1, n2, widths, bitmap_offset) = match layout {
            Grib1SecondOrderLayout::RowByRow => (27usize, 0x10, 24u16, 26u16, &[2, 2][..], None),
            Grib1SecondOrderLayout::ConstantWidth => (27, 0x20, 24, 26, &[2][..], Some(22usize)),
            Grib1SecondOrderLayout::VariableWidth => (28, 0x30, 25, 27, &[2, 2][..], Some(23usize)),
        };
        let mut section = vec![0u8; length];
        section[..3].copy_from_slice(&[
            ((length >> 16) & 0xff) as u8,
            ((length >> 8) & 0xff) as u8,
            (length & 0xff) as u8,
        ]);
        section[3] = 0x44;
        section[10] = 5;
        section[11..13].copy_from_slice(&n1.to_be_bytes());
        section[13] = extended_flags;
        section[14..16].copy_from_slice(&n2.to_be_bytes());
        section[16..18].copy_from_slice(&2u16.to_be_bytes());
        section[18..20].copy_from_slice(&6u16.to_be_bytes());
        section[21..21 + widths.len()].copy_from_slice(widths);
        if let Some(offset) = bitmap_offset {
            section[offset] = 0b1001_0000;
        }
        let first_order_index = usize::from(n1) - 1;
        section[first_order_index..first_order_index + 2].copy_from_slice(&[0x55, 0x00]);
        let second_order_index = usize::from(n2) - 1;
        section[second_order_index..second_order_index + 2].copy_from_slice(&[0x18, 0xb0]);
        section
    }
}