Skip to main content

grib/
context.rs

1use std::{
2    cell::{RefCell, RefMut},
3    collections::HashSet,
4    fmt::{self, Display, Formatter},
5    io::{Cursor, Read, Seek},
6};
7
8#[cfg(feature = "time-calculation")]
9use crate::TemporalInfo;
10use crate::{
11    Dump as _, GridDefinitionTemplateValues, GridPointIndex, GridPointIndexIterator, LatLons,
12    TemporalRawInfo, TryFromSlice as _,
13    codetables::{CodeTable3_1, CodeTable4_0, CodeTable5_0, Lookup},
14    datatypes::*,
15    def::grib2::{Section1, Section3, Section4, Section5, Section6, SectionHeader},
16    error::*,
17    grid::GridPointLatLons,
18    parser::Grib2SubmessageIndexStream,
19    reader::{Grib2Read, Grib2SectionStream, SECT8_ES_SIZE, SeekableGrib2Reader},
20};
21
22#[derive(Default, Debug, Clone, PartialEq, Eq)]
23pub struct SectionInfo {
24    pub num: u8,
25    pub offset: usize,
26    pub size: usize,
27    pub body: Option<SectionBody>,
28}
29
30impl SectionInfo {
31    pub fn get_tmpl_code(&self) -> Option<TemplateInfo> {
32        let tmpl_num = self.body.as_ref()?.get_tmpl_num()?;
33        Some(TemplateInfo(self.num, tmpl_num))
34    }
35
36    pub(crate) fn new_8(offset: usize) -> Self {
37        Self {
38            num: 8,
39            offset,
40            size: SECT8_ES_SIZE,
41            body: None,
42        }
43    }
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum SectionBody {
48    Section0(Indicator),
49    Section1(Identification),
50    Section2(LocalUse),
51    Section3(GridDefinition),
52    Section4(ProdDefinition),
53    Section5(ReprDefinition),
54    Section6(BitMap),
55    Section7,
56}
57
58impl SectionBody {
59    fn get_tmpl_num(&self) -> Option<u16> {
60        match self {
61            Self::Section3(s) => Some(s.grid_tmpl_num()),
62            Self::Section4(s) => Some(s.prod_tmpl_num()),
63            Self::Section5(s) => Some(s.repr_tmpl_num()),
64            _ => None,
65        }
66    }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
70pub struct TemplateInfo(pub u8, pub u16);
71
72impl TemplateInfo {
73    pub fn describe(&self) -> Option<String> {
74        match self.0 {
75            3 => Some(CodeTable3_1.lookup(usize::from(self.1)).to_string()),
76            4 => Some(CodeTable4_0.lookup(usize::from(self.1)).to_string()),
77            5 => Some(CodeTable5_0.lookup(usize::from(self.1)).to_string()),
78            _ => None,
79        }
80    }
81}
82
83impl Display for TemplateInfo {
84    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
85        write!(f, "{}.{}", self.0, self.1)
86    }
87}
88
89/// Reads a [`Grib2`] instance from an I/O stream of GRIB2.
90///
91/// # Examples
92///
93/// ```
94/// fn main() -> Result<(), Box<dyn std::error::Error>> {
95///     let f = std::fs::File::open(
96///         "testdata/icon_global_icosahedral_single-level_2021112018_000_TOT_PREC.grib2",
97///     )?;
98///     let f = std::io::BufReader::new(f);
99///     let result = grib::from_reader(f);
100///
101///     assert!(result.is_ok());
102///     let grib2 = result?;
103///     assert_eq!(grib2.len(), 1);
104///     Ok(())
105/// }
106/// ```
107pub fn from_reader<SR: Read + Seek>(
108    reader: SR,
109) -> Result<Grib2<SeekableGrib2Reader<SR>>, GribError> {
110    Grib2::<SeekableGrib2Reader<SR>>::read_with_seekable(reader)
111}
112
113/// Reads a [`Grib2`] instance from bytes of GRIB2.
114///
115/// # Examples
116///
117/// You can use this method to create a reader from a slice, i.e., a borrowed
118/// sequence of bytes:
119///
120/// ```
121/// use std::io::Read;
122///
123/// fn main() -> Result<(), Box<dyn std::error::Error>> {
124///     let f = std::fs::File::open(
125///         "testdata/icon_global_icosahedral_single-level_2021112018_000_TOT_PREC.grib2",
126///     )?;
127///     let mut f = std::io::BufReader::new(f);
128///     let mut buf = Vec::new();
129///     f.read_to_end(&mut buf).unwrap();
130///     let result = grib::from_bytes(&buf);
131///
132///     assert!(result.is_ok());
133///     let grib2 = result?;
134///     assert_eq!(grib2.len(), 1);
135///     Ok(())
136/// }
137/// ```
138///
139/// Also, you can use this method to create a reader from an owned sequence of
140/// bytes:
141///
142/// ```
143/// use std::io::Read;
144///
145/// fn main() -> Result<(), Box<dyn std::error::Error>> {
146///     let f = std::fs::File::open(
147///         "testdata/icon_global_icosahedral_single-level_2021112018_000_TOT_PREC.grib2",
148///     )?;
149///     let mut f = std::io::BufReader::new(f);
150///     let mut buf = Vec::new();
151///     f.read_to_end(&mut buf).unwrap();
152///     let result = grib::from_bytes(buf);
153///
154///     assert!(result.is_ok());
155///     let grib2 = result?;
156///     assert_eq!(grib2.len(), 1);
157///     Ok(())
158/// }
159/// ```
160pub fn from_bytes<T>(bytes: T) -> Result<Grib2<SeekableGrib2Reader<Cursor<T>>>, GribError>
161where
162    T: AsRef<[u8]>,
163{
164    let reader = Cursor::new(bytes);
165    Grib2::<SeekableGrib2Reader<Cursor<T>>>::read_with_seekable(reader)
166}
167
168pub struct Grib2<R> {
169    reader: RefCell<R>,
170    sections: Box<[SectionInfo]>,
171    submessages: Vec<Grib2SubmessageIndex>,
172}
173
174impl<R> Grib2<R> {
175    /// Returns the length of submessages in the data.
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
181    ///     let f = std::fs::File::open(
182    ///         "testdata/icon_global_icosahedral_single-level_2021112018_000_TOT_PREC.grib2",
183    ///     )?;
184    ///     let f = std::io::BufReader::new(f);
185    ///     let grib2 = grib::from_reader(f)?;
186    ///
187    ///     assert_eq!(grib2.len(), 1);
188    ///     Ok(())
189    /// }
190    /// ```
191    pub fn len(&self) -> usize {
192        self.submessages.len()
193    }
194
195    /// Returns `true` if `self` has zero submessages.
196    #[inline]
197    pub fn is_empty(&self) -> bool {
198        self.len() == 0
199    }
200
201    /// Returns an iterator over submessages in the data.
202    ///
203    /// # Examples
204    ///
205    /// ```
206    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
207    ///     let f = std::fs::File::open(
208    ///         "testdata/icon_global_icosahedral_single-level_2021112018_000_TOT_PREC.grib2",
209    ///     )?;
210    ///     let f = std::io::BufReader::new(f);
211    ///     let grib2 = grib::from_reader(f)?;
212    ///
213    ///     let mut iter = grib2.iter();
214    ///     let first = iter.next();
215    ///     assert!(first.is_some());
216    ///
217    ///     let first = first.unwrap();
218    ///     let (message_index, _) = first;
219    ///     assert_eq!(message_index, (0, 0));
220    ///
221    ///     let second = iter.next();
222    ///     assert!(second.is_none());
223    ///     Ok(())
224    /// }
225    /// ```
226    #[inline]
227    pub fn iter(&self) -> SubmessageIterator<'_, R> {
228        self.into_iter()
229    }
230
231    /// Returns an iterator over submessages in the data.
232    ///
233    /// This is an alias to [`Grib2::iter()`].
234    pub fn submessages(&self) -> SubmessageIterator<'_, R> {
235        self.into_iter()
236    }
237
238    /// Returns an iterator over sections in the data.
239    ///
240    /// # Examples
241    ///
242    /// ```
243    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
244    ///     let f = std::fs::File::open(
245    ///         "testdata/icon_global_icosahedral_single-level_2021112018_000_TOT_PREC.grib2",
246    ///     )?;
247    ///     let f = std::io::BufReader::new(f);
248    ///     let grib2 = grib::from_reader(f)?;
249    ///
250    ///     let mut iter = grib2.sections();
251    ///     let first = iter.next();
252    ///     assert!(first.is_some());
253    ///
254    ///     let first = first.unwrap();
255    ///     assert_eq!(first.num, 0);
256    ///
257    ///     let tenth = iter.nth(9);
258    ///     assert!(tenth.is_none());
259    ///     Ok(())
260    /// }
261    /// ```
262    pub fn sections(&self) -> std::slice::Iter<'_, SectionInfo> {
263        self.sections.iter()
264    }
265}
266
267impl<R: Grib2Read> Grib2<R> {
268    pub fn read(r: R) -> Result<Self, GribError> {
269        let mut sect_stream = Grib2SectionStream::new(r);
270        let mut cacher = Vec::new();
271        let parser = Grib2SubmessageIndexStream::new(sect_stream.by_ref()).with_cacher(&mut cacher);
272        let submessages = parser.collect::<Result<Vec<_>, _>>()?;
273        Ok(Self {
274            reader: RefCell::new(sect_stream.into_reader()),
275            sections: cacher.into_boxed_slice(),
276            submessages,
277        })
278    }
279
280    pub fn read_with_seekable<SR: Read + Seek>(
281        r: SR,
282    ) -> Result<Grib2<SeekableGrib2Reader<SR>>, GribError> {
283        let r = SeekableGrib2Reader::new(r);
284        Grib2::<SeekableGrib2Reader<SR>>::read(r)
285    }
286
287    pub fn list_templates(&self) -> Vec<TemplateInfo> {
288        get_templates(&self.sections)
289    }
290}
291
292impl<'a, R: 'a> IntoIterator for &'a Grib2<R> {
293    type Item = (MessageIndex, SubMessage<'a, R>);
294    type IntoIter = SubmessageIterator<'a, R>;
295
296    fn into_iter(self) -> Self::IntoIter {
297        Self::IntoIter::new(self)
298    }
299}
300
301fn get_templates(sects: &[SectionInfo]) -> Vec<TemplateInfo> {
302    let uniq: HashSet<_> = sects.iter().filter_map(|s| s.get_tmpl_code()).collect();
303    let mut vec: Vec<_> = uniq.into_iter().collect();
304    vec.sort_unstable();
305    vec
306}
307
308/// An iterator over submessages in the GRIB data.
309///
310/// This `struct` is created by the [`iter`] method on [`Grib2`]. See its
311/// documentation for more.
312///
313/// [`iter`]: Grib2::iter
314#[derive(Clone)]
315pub struct SubmessageIterator<'a, R> {
316    context: &'a Grib2<R>,
317    pos: usize,
318}
319
320impl<'a, R> SubmessageIterator<'a, R> {
321    fn new(context: &'a Grib2<R>) -> Self {
322        Self { context, pos: 0 }
323    }
324
325    fn new_submessage_section(&self, index: usize) -> Option<SubMessageSection<'a>> {
326        Some(SubMessageSection::new(
327            index,
328            self.context.sections.get(index)?,
329        ))
330    }
331}
332
333impl<'a, R> Iterator for SubmessageIterator<'a, R> {
334    type Item = (MessageIndex, SubMessage<'a, R>);
335
336    fn next(&mut self) -> Option<Self::Item> {
337        let submessage_index = self.context.submessages.get(self.pos)?;
338        self.pos += 1;
339
340        Some((
341            submessage_index.message_index(),
342            SubMessage(
343                self.new_submessage_section(submessage_index.0)?,
344                self.new_submessage_section(submessage_index.1)?,
345                submessage_index
346                    .2
347                    .and_then(|i| self.new_submessage_section(i)),
348                self.new_submessage_section(submessage_index.3)?,
349                self.new_submessage_section(submessage_index.4)?,
350                self.new_submessage_section(submessage_index.5)?,
351                self.new_submessage_section(submessage_index.6)?,
352                self.new_submessage_section(submessage_index.7)?,
353                self.new_submessage_section(submessage_index.8)?,
354                self.context.reader.borrow_mut(),
355            ),
356        ))
357    }
358
359    fn size_hint(&self) -> (usize, Option<usize>) {
360        let size = self.context.submessages.len() - self.pos;
361        (size, Some(size))
362    }
363
364    fn nth(&mut self, n: usize) -> Option<Self::Item> {
365        self.pos = n;
366        self.next()
367    }
368}
369
370impl<'a, R> IntoIterator for &'a SubmessageIterator<'a, R> {
371    type Item = (MessageIndex, SubMessage<'a, R>);
372    type IntoIter = SubmessageIterator<'a, R>;
373
374    fn into_iter(self) -> Self::IntoIter {
375        SubmessageIterator {
376            context: self.context,
377            pos: self.pos,
378        }
379    }
380}
381
382pub struct SubMessage<'a, R>(
383    pub SubMessageSection<'a>,
384    pub SubMessageSection<'a>,
385    pub Option<SubMessageSection<'a>>,
386    pub SubMessageSection<'a>,
387    pub SubMessageSection<'a>,
388    pub SubMessageSection<'a>,
389    pub SubMessageSection<'a>,
390    pub SubMessageSection<'a>,
391    pub SubMessageSection<'a>,
392    pub(crate) RefMut<'a, R>,
393);
394
395impl<R> SubMessage<'_, R> {
396    /// Returns the product's parameter.
397    ///
398    /// In the context of GRIB products, parameters refer to weather elements
399    /// such as air temperature, air pressure, and humidity, and other physical
400    /// quantities.
401    ///
402    /// # Examples
403    ///
404    /// ```
405    /// use std::{
406    ///     fs::File,
407    ///     io::{BufReader, Read},
408    /// };
409    ///
410    /// use grib::codetables::NCEP;
411    ///
412    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
413    ///     let mut buf = Vec::new();
414    ///
415    ///     let f = File::open("testdata/gdas.t12z.pgrb2.0p25.f000.0-10.xz")?;
416    ///     let f = BufReader::new(f);
417    ///     let mut f = xz2::bufread::XzDecoder::new(f);
418    ///     f.read_to_end(&mut buf)?;
419    ///
420    ///     let f = std::io::Cursor::new(buf);
421    ///     let grib2 = grib::from_reader(f)?;
422    ///
423    ///     let mut iter = grib2.iter();
424    ///     let (_, message) = iter.next().ok_or_else(|| "first message is not found")?;
425    ///
426    ///     let param = message.parameter();
427    ///     assert_eq!(
428    ///         param,
429    ///         Some(grib::Parameter {
430    ///             discipline: 0,
431    ///             centre: 7,
432    ///             master_ver: 2,
433    ///             local_ver: 1,
434    ///             category: 3,
435    ///             num: 1
436    ///         })
437    ///     );
438    ///     let param = param.unwrap();
439    ///     assert_eq!(
440    ///         param.description(),
441    ///         Some("Pressure reduced to MSL".to_owned())
442    ///     );
443    ///     assert!(param.is_identical_to(NCEP::PRMSL));
444    ///     Ok(())
445    /// }
446    /// ```
447    pub fn parameter(&self) -> Option<Parameter> {
448        let discipline = self.indicator().discipline;
449        let ident = self.identification();
450        let centre = ident.centre_id();
451        let master_ver = ident.master_table_version();
452        let local_ver = ident.local_table_version();
453        let prod_def = self.prod_def();
454        let category = prod_def.parameter_category()?;
455        let num = prod_def.parameter_number()?;
456        Some(Parameter {
457            discipline,
458            centre,
459            master_ver,
460            local_ver,
461            category,
462            num,
463        })
464    }
465
466    pub fn indicator(&self) -> &Indicator {
467        // panics should not happen if data is correct
468        match self.0.body.body.as_ref().unwrap() {
469            SectionBody::Section0(data) => data,
470            _ => panic!("something unexpected happened"),
471        }
472    }
473
474    pub fn identification(&self) -> &Identification {
475        // panics should not happen if data is correct
476        match self.1.body.body.as_ref().unwrap() {
477            SectionBody::Section1(data) => data,
478            _ => panic!("something unexpected happened"),
479        }
480    }
481
482    pub fn grid_def(&self) -> &GridDefinition {
483        // panics should not happen if data is correct
484        match self.3.body.body.as_ref().unwrap() {
485            SectionBody::Section3(data) => data,
486            _ => panic!("something unexpected happened"),
487        }
488    }
489
490    pub fn prod_def(&self) -> &ProdDefinition {
491        // panics should not happen if data is correct
492        match self.4.body.body.as_ref().unwrap() {
493            SectionBody::Section4(data) => data,
494            _ => panic!("something unexpected happened"),
495        }
496    }
497
498    pub fn repr_def(&self) -> &ReprDefinition {
499        // panics should not happen if data is correct
500        match self.5.body.body.as_ref().unwrap() {
501            SectionBody::Section5(data) => data,
502            _ => panic!("something unexpected happened"),
503        }
504    }
505
506    /// Provides access to the parameters in Section 1.
507    ///
508    /// # Examples
509    /// ```
510    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
511    ///     let f = std::fs::File::open(
512    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
513    ///     )?;
514    ///     let f = std::io::BufReader::new(f);
515    ///     let grib2 = grib::from_reader(f)?;
516    ///     let (_index, first_submessage) = grib2.iter().next().unwrap();
517    ///
518    ///     let actual = first_submessage.section1();
519    ///     let expected = Ok(grib::def::grib2::Section1 {
520    ///         header: grib::def::grib2::SectionHeader {
521    ///             len: 21,
522    ///             sect_num: 1,
523    ///         },
524    ///         payload: grib::def::grib2::Section1Payload {
525    ///             centre_id: grib::def::grib2::table::CentreId(34),
526    ///             subcentre_id: grib::def::grib2::table::SubcentreId(0),
527    ///             master_table_version: grib::def::grib2::table::MasterTableVer(5),
528    ///             local_table_version: grib::def::grib2::table::LocalTableVer(1),
529    ///             ref_time_significance: grib::def::grib2::table::RefTimeSignificance(0),
530    ///             ref_time: grib::def::grib2::template::param_set::DateTime {
531    ///                 year: 2016,
532    ///                 month: 8,
533    ///                 day: 22,
534    ///                 hour: 2,
535    ///                 minute: 0,
536    ///                 second: 0,
537    ///             },
538    ///             prod_status: grib::def::grib2::table::ProductionStatus(0),
539    ///             data_type: grib::def::grib2::table::ProcessedDataType(2),
540    ///             optional: None,
541    ///         },
542    ///     });
543    ///     assert_eq!(actual, expected);
544    ///
545    ///     Ok(())
546    /// }
547    /// ```
548    pub fn section1(&self) -> Result<Section1, GribError> {
549        let Identification { payload } = self.identification();
550        let mut pos = 0;
551        let payload = crate::def::grib2::Section1Payload::try_from_slice(payload, &mut pos)?;
552
553        let SectionInfo { num, size, .. } = self.1.body;
554        Ok(Section1 {
555            header: SectionHeader {
556                len: *size as u32,
557                sect_num: *num,
558            },
559            payload,
560        })
561    }
562
563    /// Provides access to the parameters in Section 3.
564    ///
565    /// # Examples
566    /// ```
567    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
568    ///     let f = std::fs::File::open(
569    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
570    ///     )?;
571    ///     let f = std::io::BufReader::new(f);
572    ///     let grib2 = grib::from_reader(f)?;
573    ///     let (_index, first_submessage) = grib2.iter().next().unwrap();
574    ///
575    ///     let actual = first_submessage.section3();
576    ///     let expected = Ok(grib::def::grib2::Section3 {
577    ///         header: grib::def::grib2::SectionHeader {
578    ///             len: 72,
579    ///             sect_num: 3,
580    ///         },
581    ///         payload: grib::def::grib2::Section3Payload {
582    ///             grid_def_source: 0,
583    ///             num_points: 86016,
584    ///             num_point_list_octets: 0,
585    ///             point_list_interpretation: grib::def::grib2::table::PointListInterpretation(0),
586    ///             template_num: grib::def::grib2::table::GridDefinitionTemplateNum(0),
587    ///             template: grib::def::grib2::GridDefinitionTemplate::_3_0(grib::def::grib2::template::Template3_0 {
588    ///                 earth: grib::def::grib2::template::param_set::EarthShape {
589    ///                     shape: grib::def::grib2::table::EarthShapeType(4),
590    ///                     spherical_earth_radius: grib::def::grib2::template::param_set::ScaledValue {
591    ///                         scale_factor: 0xff,
592    ///                         scaled_value: 0xffffffff,
593    ///                     },
594    ///                     major_axis: grib::def::grib2::template::param_set::ScaledValue {
595    ///                         scale_factor: 1,
596    ///                         scaled_value: 63781370,
597    ///                     },
598    ///                     minor_axis: grib::def::grib2::template::param_set::ScaledValue {
599    ///                         scale_factor: 1,
600    ///                         scaled_value: 63567523,
601    ///                     },
602    ///                 },
603    ///                 lat_lon: grib::def::grib2::template::param_set::LatLonGrid {
604    ///                     grid: grib::def::grib2::template::param_set::Grid {
605    ///                         ni: 256,
606    ///                         nj: 336,
607    ///                         initial_production_domain_basic_angle: 0,
608    ///                         basic_angle_subdivisions: 0xffffffff,
609    ///                         first_point_lat: 47958333,
610    ///                         first_point_lon: 118062500,
611    ///                         resolution_and_component_flags: grib::def::grib2::table::ResolutionAndComponentFlags(0b00110000),
612    ///                         last_point_lat: 20041667,
613    ///                         last_point_lon: 149937500,
614    ///                     },
615    ///                     i_direction_inc: 125000,
616    ///                     j_direction_inc: 83333,
617    ///                     scanning_mode: grib::def::grib2::table::ScanningMode(0b00000000),
618    ///                 },
619    ///             }),
620    ///         },
621    ///     });
622    ///     assert_eq!(actual, expected);
623    ///
624    ///     Ok(())
625    /// }
626    /// ```
627    pub fn section3(&self) -> Result<Section3, GribError> {
628        let GridDefinition { payload } = self.grid_def();
629        let mut pos = 0;
630        let payload = crate::def::grib2::Section3Payload::try_from_slice(payload, &mut pos)?;
631
632        let SectionInfo { num, size, .. } = self.3.body;
633        Ok(Section3 {
634            header: SectionHeader {
635                len: *size as u32,
636                sect_num: *num,
637            },
638            payload,
639        })
640    }
641
642    /// Provides access to the parameters in Section 4.
643    ///
644    /// # Examples
645    /// ```
646    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
647    ///     let f = std::fs::File::open(
648    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
649    ///     )?;
650    ///     let f = std::io::BufReader::new(f);
651    ///     let grib2 = grib::from_reader(f)?;
652    ///     let (_index, first_submessage) = grib2.iter().next().unwrap();
653    ///
654    ///     let actual = first_submessage.section4();
655    ///     let expected = Ok(grib::def::grib2::Section4 {
656    ///         header: grib::def::grib2::SectionHeader {
657    ///             len: 34,
658    ///             sect_num: 4,
659    ///         },
660    ///         payload: grib::def::grib2::Section4Payload {
661    ///             num_coord_values: 0,
662    ///             template_num: grib::def::grib2::table::ProductDefinitionTemplateNum(0),
663    ///             template: grib::def::grib2::ProductDefinitionTemplate::_4_0(
664    ///                 grib::def::grib2::template::Template4_0 {
665    ///                     param: grib::def::grib2::template::param_set::ProductParam {
666    ///                         category: grib::def::grib2::table::ParamCategory(193),
667    ///                         num: grib::def::grib2::table::ParamNum(0),
668    ///                     },
669    ///                     generating_process:
670    ///                         grib::def::grib2::template::param_set::GeneratingProcess {
671    ///                             process_type: grib::def::grib2::table::GeneratingProcessType(0),
672    ///                             background_process: 153,
673    ///                             process_id: 255,
674    ///                         },
675    ///                     forecast_time: grib::def::grib2::template::param_set::ForecastTime {
676    ///                         cutoff_hours: 0,
677    ///                         cutoff_minutes: 0,
678    ///                         time: grib::def::grib2::template::param_set::TimeRange {
679    ///                             unit: grib::def::grib2::table::TimeRangeUnit(0),
680    ///                             len: 0,
681    ///                         },
682    ///                     },
683    ///                     horizontal: grib::def::grib2::template::param_set::Horizontal {
684    ///                         first_surface: grib::def::grib2::template::param_set::FixedSurface {
685    ///                             surface_type: grib::def::grib2::table::FixedSurfaceType(1),
686    ///                             value: grib::def::grib2::template::param_set::ScaledValue {
687    ///                                 scale_factor: -127,
688    ///                                 scaled_value: -2147483647,
689    ///                             },
690    ///                         },
691    ///                         second_surface: grib::def::grib2::template::param_set::FixedSurface {
692    ///                             surface_type: grib::def::grib2::table::FixedSurfaceType(255),
693    ///                             value: grib::def::grib2::template::param_set::ScaledValue {
694    ///                                 scale_factor: -127,
695    ///                                 scaled_value: -2147483647,
696    ///                             },
697    ///                         },
698    ///                     },
699    ///                 },
700    ///             ),
701    ///         },
702    ///     });
703    ///     assert_eq!(actual, expected);
704    ///
705    ///     Ok(())
706    /// }
707    /// ```
708    pub fn section4(&self) -> Result<Section4, GribError> {
709        let ProdDefinition { payload }: &ProdDefinition = self.prod_def();
710        let mut pos = 0;
711        let payload = crate::def::grib2::Section4Payload::try_from_slice(payload, &mut pos)?;
712
713        let SectionInfo { num, size, .. } = self.4.body;
714        Ok(Section4 {
715            header: SectionHeader {
716                len: *size as u32,
717                sect_num: *num,
718            },
719            payload,
720        })
721    }
722
723    /// Provides access to the parameters in Section 5.
724    ///
725    /// # Examples
726    /// ```
727    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
728    ///     let f = std::fs::File::open(
729    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
730    ///     )?;
731    ///     let f = std::io::BufReader::new(f);
732    ///     let grib2 = grib::from_reader(f)?;
733    ///     let (_index, first_submessage) = grib2.iter().next().unwrap();
734    ///
735    ///     let actual = first_submessage.section5();
736    ///     let expected = Ok(grib::def::grib2::Section5 {
737    ///         header: grib::def::grib2::SectionHeader {
738    ///             len: 23,
739    ///             sect_num: 5,
740    ///         },
741    ///         payload: grib::def::grib2::Section5Payload {
742    ///             num_encoded_points: 86016,
743    ///             template_num: grib::def::grib2::table::DataRepresentationTemplateNum(200),
744    ///             template: grib::def::grib2::DataRepresentationTemplate::_5_200(
745    ///                 grib::def::grib2::template::Template5_200 {
746    ///                     num_bits: 8,
747    ///                     max_val: 3,
748    ///                     max_level: 3,
749    ///                     dec: 0,
750    ///                     level_vals: vec![1, 2, 3],
751    ///                 },
752    ///             ),
753    ///         },
754    ///     });
755    ///     assert_eq!(actual, expected);
756    ///
757    ///     Ok(())
758    /// }
759    /// ```
760    pub fn section5(&self) -> Result<Section5, GribError> {
761        let ReprDefinition { payload } = self.repr_def();
762        let mut pos = 0;
763        let payload = crate::def::grib2::Section5Payload::try_from_slice(payload, &mut pos)?;
764
765        let SectionInfo { num, size, .. } = self.5.body;
766        Ok(Section5 {
767            header: SectionHeader {
768                len: *size as u32,
769                sect_num: *num,
770            },
771            payload,
772        })
773    }
774
775    /// Provides access to the parameters in Section 6.
776    ///
777    /// # Examples
778    /// ```
779    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
780    ///     let f = std::fs::File::open(
781    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
782    ///     )?;
783    ///     let f = std::io::BufReader::new(f);
784    ///     let grib2 = grib::from_reader(f)?;
785    ///     let (_index, first_submessage) = grib2.iter().next().unwrap();
786    ///
787    ///     let actual = first_submessage.section6();
788    ///     let expected = Ok(grib::def::grib2::Section6 {
789    ///         header: grib::def::grib2::SectionHeader {
790    ///             len: 6,
791    ///             sect_num: 6,
792    ///         },
793    ///         payload: grib::def::grib2::Section6Payload {
794    ///             bitmap_indicator: grib::def::grib2::table::BitMapIndicator(255),
795    ///         },
796    ///     });
797    ///     assert_eq!(actual, expected);
798    ///
799    ///     Ok(())
800    /// }
801    /// ```
802    pub fn section6(&self) -> Result<Section6, GribError> {
803        // panics should not happen if data is correct
804        let BitMap { bitmap_indicator } = match self.6.body.body.as_ref().unwrap() {
805            SectionBody::Section6(data) => data,
806            _ => panic!("something unexpected happened"),
807        };
808        let payload = crate::def::grib2::Section6Payload {
809            bitmap_indicator: crate::def::grib2::table::BitMapIndicator(*bitmap_indicator),
810        };
811
812        let SectionInfo { num, size, .. } = self.6.body;
813        Ok(Section6 {
814            header: SectionHeader {
815                len: *size as u32,
816                sect_num: *num,
817            },
818            payload,
819        })
820    }
821
822    /// Dumps the GRIB2 submessage.
823    ///
824    /// # Examples
825    /// ```
826    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
827    ///     let f = std::fs::File::open(
828    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
829    ///     )?;
830    ///     let f = std::io::BufReader::new(f);
831    ///     let grib2 = grib::from_reader(f)?;
832    ///     let (_index, first_submessage) = grib2.iter().next().unwrap();
833    ///
834    ///     let mut buf = std::io::Cursor::new(Vec::with_capacity(10240));
835    ///     first_submessage.dump(&mut buf)?;
836    ///     let expected = "\
837    /// ##  SUBMESSAGE (total_length = 10321)
838    /// ###  SECTION 0: INDICATOR SECTION (length = 16)
839    /// ###  SECTION 1: IDENTIFICATION SECTION (length = 21)
840    /// 1-4       header.len = 21  // Length of section in octets (nn).
841    /// 5         header.sect_num = 1  // Number of section.
842    /// 6-7       payload.centre_id = 34 [Tokyo (RSMC), Japan Meteorological Agency]  // Identification of originating/generating centre (see Common Code table C-11).
843    /// 8-9       payload.subcentre_id = 0  // Identification of originating/generating subcentre (allocated by originating/generating centre).
844    /// 10        payload.master_table_version = 5 [4 November 2009]  // GRIB master table version number (see Common Code table C-0 and Note 1).
845    /// 11        payload.local_table_version = 1 [Number of local tables version used]  // Version number of GRIB Local tables used to augment Master tables (see Code table 1.1 and Note 2).
846    /// 12        payload.ref_time_significance = 0 [Analysis]  // Significance of reference time (see Code table 1.2).
847    /// 13-14     payload.ref_time.year = 2016  // Year (4 digits) - Reference time of data.
848    /// 15        payload.ref_time.month = 8  // Month - Reference time of data.
849    /// 16        payload.ref_time.day = 22  // Day - Reference time of data.
850    /// 17        payload.ref_time.hour = 2  // Hour - Reference time of data.
851    /// 18        payload.ref_time.minute = 0  // Minute - Reference time of data.
852    /// 19        payload.ref_time.second = 0  // Second - Reference time of data.
853    /// 20        payload.prod_status = 0 [Operational products]  // Production status of processed data in this GRIB message (see Code table 1.3).
854    /// 21        payload.data_type = 2 [Analysis and forecast products]  // Type of processed data in this GRIB message (see Code table 1.4).
855    /// ###  SECTION 3: GRID DEFINITION SECTION (length = 72)
856    /// 1-4       header.len = 72  // Length of section in octets (nn).
857    /// 5         header.sect_num = 3  // Number of section.
858    /// 6         payload.grid_def_source = 0  // Source of grid definition (see Code table 3.0 and Note 1).
859    /// 7-10      payload.num_points = 86016  // Number of data points.
860    /// 11        payload.num_point_list_octets = 0  // Number of octets for optional list of numbers (see Note 2).
861    /// 12        payload.point_list_interpretation = 0 [There is no appended list]  // Interpretation of list of numbers (see Code table 3.11).
862    /// 13-14     payload.template_num = 0 [Latitude/longitude]  // Grid definition template number (= N) (see Code table 3.1).
863    /// 15        payload.template.earth.shape = 4 [Earth assumed oblate spheroid as defined in IAG-GRS80 model (major axis = 6 378 137.0 m, minor axis = 6 356 752.314 m, f = 1/298.257 222 101)]  // Shape of the Earth (see Code table 3.2).
864    /// 16        payload.template.earth.spherical_earth_radius.scale_factor = 255 [Missing]  // Scale factor of radius of spherical Earth.
865    /// 17-20     payload.template.earth.spherical_earth_radius.scaled_value = 4294967295 [Missing]  // Scaled value of radius of spherical Earth.
866    /// 21        payload.template.earth.major_axis.scale_factor = 1  // Scale factor of major axis of oblate spheroid Earth.
867    /// 22-25     payload.template.earth.major_axis.scaled_value = 63781370  // Scaled value of major axis of oblate spheroid Earth.
868    /// 26        payload.template.earth.minor_axis.scale_factor = 1  // Scale factor of minor axis of oblate spheroid Earth.
869    /// 27-30     payload.template.earth.minor_axis.scaled_value = 63567523  // Scaled value of minor axis of oblate spheroid Earth.
870    /// 31-34     payload.template.lat_lon.grid.ni = 256  // Ni - number of points along a parallel.
871    /// 35-38     payload.template.lat_lon.grid.nj = 336  // Nj - number of points along a meridian.
872    /// 39-42     payload.template.lat_lon.grid.initial_production_domain_basic_angle = 0  // Basic angle of the initial production domain (see Note 1).
873    /// 43-46     payload.template.lat_lon.grid.basic_angle_subdivisions = 4294967295 [Missing]  // Subdivisions of basic angle used to define extreme longitudes and latitudes, and direction increments (see Note 1).
874    /// 47-50     payload.template.lat_lon.grid.first_point_lat = 47958333  // La1 - latitude of first grid point (see Note 1).
875    /// 51-54     payload.template.lat_lon.grid.first_point_lon = 118062500  // Lo1 - longitude of first grid point (see Note 1).
876    /// 55        payload.template.lat_lon.grid.resolution_and_component_flags = 0b00110000  // Resolution and component flags (see Flag table 3.3).
877    /// 56-59     payload.template.lat_lon.grid.last_point_lat = 20041667  // La2 - latitude of last grid point (see Note 1).
878    /// 60-63     payload.template.lat_lon.grid.last_point_lon = 149937500  // Lo2 - longitude of last grid point (see Note 1).
879    /// 64-67     payload.template.lat_lon.i_direction_inc = 125000  // Di - i direction increment (see Notes 1 and 5).
880    /// 68-71     payload.template.lat_lon.j_direction_inc = 83333  // Dj - j direction increment (see Notes 1 and 5).
881    /// 72        payload.template.lat_lon.scanning_mode = 0b00000000  // Scanning mode (flags - see Flag table 3.4).
882    /// ###  SECTION 4: PRODUCT DEFINITION SECTION (length = 34)
883    /// 1-4       header.len = 34  // Length of section in octets (nn).
884    /// 5         header.sect_num = 4  // Number of section.
885    /// 6-7       payload.num_coord_values = 0  // Number of coordinate values after template or number of information according to 3D vertical coordinate GRIB2 message (see Notes 1 and 5).
886    /// 8-9       payload.template_num = 0 [Analysis or forecast at a horizontal level or in a horizontal layer at a point in time]  // Product definition template number (see Code table 4.0).
887    /// 10        payload.template.param.category = 193  // Parameter category (see Code Table 4.1).
888    /// 11        payload.template.param.num = 0  // Parameter number (see Code Table 4.2).
889    /// 12        payload.template.generating_process.process_type = 0 [Analysis]  // Type of generating process (see Code Table 4.3).
890    /// 13        payload.template.generating_process.background_process = 153  // Background generating process identifier (defined by originating centre).
891    /// 14        payload.template.generating_process.process_id = 255 [Missing]  // Analysis or forecast generating processes identifier (defined by originating centre).
892    /// 15-16     payload.template.forecast_time.cutoff_hours = 0  // Hours of observational data cutoff after reference time (see Note 1)
893    /// 17        payload.template.forecast_time.cutoff_minutes = 0  // Minutes of observational data cutoff after reference time
894    /// 18        payload.template.forecast_time.time.unit = 0 [Minute]  // Indicator of unit of time range (see Code Table 4.4).
895    /// 19-22     payload.template.forecast_time.time.len = 0  // Forecast time in units defined by octet 18.
896    /// 23        payload.template.horizontal.first_surface.surface_type = 1 [Ground or water surface]  // Type of first fixed surface (see Code Table 4.5).
897    /// 24        payload.template.horizontal.first_surface.value.scale_factor = -127 [Missing]  // Scale factor of first fixed surface.
898    /// 25-28     payload.template.horizontal.first_surface.value.scaled_value = -2147483647 [Missing]  // Scaled value of first fixed surface.
899    /// 29        payload.template.horizontal.second_surface.surface_type = 255 [Missing]  // Type of second fixed surface (see Code Table 4.5).
900    /// 30        payload.template.horizontal.second_surface.value.scale_factor = -127 [Missing]  // Scale factor of second fixed surface.
901    /// 31-34     payload.template.horizontal.second_surface.value.scaled_value = -2147483647 [Missing]  // Scaled value of second fixed surface.
902    /// ###  SECTION 5: DATA REPRESENTATION SECTION (length = 23)
903    /// 1-4       header.len = 23  // Length of section in octets (nn).
904    /// 5         header.sect_num = 5  // Number of section.
905    /// 6-9       payload.num_encoded_points = 86016  // Number of data points where one or more values are specified in Section 7 when a bit map is present, total number of data points when a bit map is absent.
906    /// 10-11     payload.template_num = 200 [Run length packing with level values]  // Data representation template number (see Code table 5.0).
907    /// 12        payload.template.num_bits = 8  // Number of bits used for each packed value in the run length packing with level value.
908    /// 13-14     payload.template.max_val = 3  // MV - maximum value within the levels that are used in the packing.
909    /// 15-16     payload.template.max_level = 3  // MVL - maximum value of level (predefined).
910    /// 17        payload.template.dec = 0  // Decimal scale factor of representative value of each level.
911    /// 18-23     payload.template.level_vals = [1, 2, 3]  // List of MVL scaled representative values of each level from lv=1 to MVL.
912    /// ###  SECTION 6: BIT-MAP SECTION (length = 6)
913    /// 1-4       header.len = 6  // Length of section in octets (nn).
914    /// 5         header.sect_num = 6  // Number of section.
915    /// 6         payload.bitmap_indicator = 255 [A bit map does not apply to this product]  // Bit-map indicator (see Code table 6.0 and the Note).
916    /// ###  SECTION 7: DATA SECTION (length = 1391)
917    /// ###  SECTION 8: END SECTION (length = 4)
918    /// ";
919    ///     assert_eq!(String::from_utf8_lossy(buf.get_ref()), expected);
920    ///
921    ///     Ok(())
922    /// }
923    /// ```
924    pub fn dump<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
925        let write_heading =
926            |writer: &mut W, sect: &SectionInfo, sect_name: &str| -> Result<(), std::io::Error> {
927                let SectionInfo { num, size, .. } = sect;
928                let sect_name = sect_name.to_ascii_uppercase();
929                writeln!(writer, "##  SECTION {num}: {sect_name} (length = {size})")
930            };
931
932        let context = Grib2Context {
933            discipline: self.indicator().discipline,
934        };
935        macro_rules! write_section {
936            ($sect:expr $(,)?) => {{
937                let mut pos = 1;
938                match $sect {
939                    Ok(s) => s.dump(
940                        &context,
941                        None,
942                        grib_template_helpers::DocOverrides::empty(),
943                        &mut pos,
944                        writer,
945                    )?,
946                    Err(e) => writeln!(writer, "error: {}", e)?,
947                }
948            }};
949        }
950
951        let total_length = self.indicator().total_length;
952        writeln!(writer, "#  SUBMESSAGE (total_length = {total_length})")?;
953        write_heading(writer, self.0.body, "indicator section")?;
954        write_heading(writer, self.1.body, "identification section")?;
955        write_section!(self.section1());
956        if let Some(sect) = &self.2 {
957            write_heading(writer, sect.body, "local use section")?;
958        }
959        write_heading(writer, self.3.body, "grid definition section")?;
960        write_section!(self.section3());
961        write_heading(writer, self.4.body, "product definition section")?;
962        write_section!(self.section4());
963        write_heading(writer, self.5.body, "data representation section")?;
964        write_section!(self.section5());
965        write_heading(writer, self.6.body, "bit-map section")?;
966        write_section!(self.section6());
967        write_heading(writer, self.7.body, "data section")?;
968
969        // Since `self.8.body` might be dummy, we don't use that Section 8 data.
970        writeln!(writer, "##  SECTION 8: END SECTION (length = 4)")?;
971
972        Ok(())
973    }
974
975    /// Returns time-related raw information associated with the submessage.
976    ///
977    /// # Examples
978    ///
979    /// ```
980    /// use std::{
981    ///     fs::File,
982    ///     io::{BufReader, Read},
983    /// };
984    ///
985    /// use grib::{
986    ///     Code, ForecastTime, TemporalRawInfo,
987    ///     codetables::grib2::Table4_4,
988    ///     def::grib2::{table::RefTimeSignificance, template::param_set::DateTime},
989    /// };
990    ///
991    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
992    ///     let f = File::open(
993    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
994    ///     )?;
995    ///     let f = BufReader::new(f);
996    ///     let grib2 = grib::from_reader(f)?;
997    ///
998    ///     let mut iter = grib2.iter();
999    ///
1000    ///     {
1001    ///         let (_, message) = iter.next().ok_or_else(|| "first message is not found")?;
1002    ///         let actual = message.temporal_raw_info();
1003    ///         let expected = TemporalRawInfo {
1004    ///             ref_time_significance: RefTimeSignificance::Analysis,
1005    ///             ref_time_unchecked: DateTime::new(2016, 8, 22, 2, 0, 0),
1006    ///             forecast_time_diff: Some(ForecastTime {
1007    ///                 unit: Code::Name(Table4_4::Minute),
1008    ///                 value: 0,
1009    ///             }),
1010    ///         };
1011    ///         assert_eq!(actual, expected);
1012    ///     }
1013    ///
1014    ///     {
1015    ///         let (_, message) = iter.next().ok_or_else(|| "second message is not found")?;
1016    ///         let actual = message.temporal_raw_info();
1017    ///         let expected = TemporalRawInfo {
1018    ///             ref_time_significance: RefTimeSignificance::Analysis,
1019    ///             ref_time_unchecked: DateTime::new(2016, 8, 22, 2, 0, 0),
1020    ///             forecast_time_diff: Some(ForecastTime {
1021    ///                 unit: Code::Name(Table4_4::Minute),
1022    ///                 value: 10,
1023    ///             }),
1024    ///         };
1025    ///         assert_eq!(actual, expected);
1026    ///     }
1027    ///
1028    ///     Ok(())
1029    /// }
1030    /// ```
1031    pub fn temporal_raw_info(&self) -> TemporalRawInfo {
1032        let ref_time_significance = self.identification().ref_time_significance();
1033        let ref_time_unchecked = self.identification().ref_time_unchecked();
1034        let forecast_time_diff = self.prod_def().forecast_time();
1035        TemporalRawInfo {
1036            ref_time_significance: crate::def::grib2::table::RefTimeSignificance(
1037                ref_time_significance,
1038            ),
1039            ref_time_unchecked,
1040            forecast_time_diff,
1041        }
1042    }
1043
1044    #[cfg(feature = "time-calculation")]
1045    #[cfg_attr(docsrs, doc(cfg(feature = "time-calculation")))]
1046    /// Returns time-related calculated information associated with the
1047    /// submessage.
1048    ///
1049    /// # Examples
1050    ///
1051    /// ```
1052    /// use std::{
1053    ///     fs::File,
1054    ///     io::{BufReader, Read},
1055    /// };
1056    ///
1057    /// use chrono::{TimeZone, Utc};
1058    /// use grib::{Code, ForecastTime, TemporalInfo, codetables::grib2::Table4_4};
1059    ///
1060    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
1061    ///     let f = File::open(
1062    ///         "testdata/Z__C_RJTD_20160822020000_NOWC_GPV_Ggis10km_Pphw10_FH0000-0100_grib2.bin",
1063    ///     )?;
1064    ///     let f = BufReader::new(f);
1065    ///     let grib2 = grib::from_reader(f)?;
1066    ///
1067    ///     let mut iter = grib2.iter();
1068    ///
1069    ///     {
1070    ///         let (_, message) = iter.next().ok_or_else(|| "first message is not found")?;
1071    ///         let actual = message.temporal_info();
1072    ///         let expected = TemporalInfo {
1073    ///             ref_time: Some(Utc.with_ymd_and_hms(2016, 8, 22, 2, 0, 0).unwrap()),
1074    ///             forecast_time_target: Some(Utc.with_ymd_and_hms(2016, 8, 22, 2, 0, 0).unwrap()),
1075    ///         };
1076    ///         assert_eq!(actual, expected);
1077    ///     }
1078    ///
1079    ///     {
1080    ///         let (_, message) = iter.next().ok_or_else(|| "second message is not found")?;
1081    ///         let actual = message.temporal_info();
1082    ///         let expected = TemporalInfo {
1083    ///             ref_time: Some(Utc.with_ymd_and_hms(2016, 8, 22, 2, 0, 0).unwrap()),
1084    ///             forecast_time_target: Some(Utc.with_ymd_and_hms(2016, 8, 22, 2, 10, 0).unwrap()),
1085    ///         };
1086    ///         assert_eq!(actual, expected);
1087    ///     }
1088    ///
1089    ///     Ok(())
1090    /// }
1091    /// ```
1092    pub fn temporal_info(&self) -> TemporalInfo {
1093        let raw_info = self.temporal_raw_info();
1094        TemporalInfo::from(&raw_info)
1095    }
1096
1097    /// Returns the shape of the grid, i.e. a tuple of the number of grids in
1098    /// the i and j directions.
1099    ///
1100    /// # Examples
1101    ///
1102    /// ```
1103    /// use std::{
1104    ///     fs::File,
1105    ///     io::{BufReader, Read},
1106    /// };
1107    ///
1108    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
1109    ///     let mut buf = Vec::new();
1110    ///
1111    ///     let f = File::open("testdata/gdas.t12z.pgrb2.0p25.f000.0-10.xz")?;
1112    ///     let f = BufReader::new(f);
1113    ///     let mut f = xz2::bufread::XzDecoder::new(f);
1114    ///     f.read_to_end(&mut buf)?;
1115    ///
1116    ///     let f = std::io::Cursor::new(buf);
1117    ///     let grib2 = grib::from_reader(f)?;
1118    ///
1119    ///     let mut iter = grib2.iter();
1120    ///     let (_, message) = iter.next().ok_or_else(|| "first message is not found")?;
1121    ///
1122    ///     let shape = message.grid_shape()?;
1123    ///     assert_eq!(shape, (1440, 721));
1124    ///     Ok(())
1125    /// }
1126    /// ```
1127    pub fn grid_shape(&self) -> Result<(usize, usize), GribError> {
1128        let grid_def = self.grid_def();
1129        let shape = GridDefinitionTemplateValues::try_from(grid_def)?.grid_shape();
1130        Ok(shape)
1131    }
1132
1133    /// Computes and returns an iterator over `(i, j)` of grid points.
1134    ///
1135    /// The order of items is the same as the order of the grid point values,
1136    /// defined by the scanning mode
1137    /// ([`ScanningMode`](`crate::def::grib2::table::ScanningMode`))
1138    /// in the data.
1139    ///
1140    /// This iterator allows users to perform their own coordinate calculations
1141    /// for unsupported grid systems and map the results to grid point values.
1142    ///
1143    /// # Examples
1144    ///
1145    /// ```
1146    /// use std::{
1147    ///     fs::File,
1148    ///     io::{BufReader, Read},
1149    /// };
1150    ///
1151    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
1152    ///     let mut buf = Vec::new();
1153    ///
1154    ///     let f = File::open("testdata/gdas.t12z.pgrb2.0p25.f000.0-10.xz")?;
1155    ///     let f = BufReader::new(f);
1156    ///     let mut f = xz2::bufread::XzDecoder::new(f);
1157    ///     f.read_to_end(&mut buf)?;
1158    ///
1159    ///     let f = std::io::Cursor::new(buf);
1160    ///     let grib2 = grib::from_reader(f)?;
1161    ///
1162    ///     let mut iter = grib2.iter();
1163    ///     let (_, message) = iter.next().ok_or_else(|| "first message is not found")?;
1164    ///
1165    ///     let mut latlons = message.ij()?;
1166    ///     assert_eq!(latlons.next(), Some((0, 0)));
1167    ///     assert_eq!(latlons.next(), Some((1, 0)));
1168    ///     Ok(())
1169    /// }
1170    /// ```
1171    pub fn ij(&self) -> Result<GridPointIndexIterator, GribError> {
1172        let grid_def = self.grid_def();
1173        let num_defined = grid_def.num_points() as usize;
1174        let ij = GridDefinitionTemplateValues::try_from(grid_def)?.ij()?;
1175        let (num_decoded, _) = ij.size_hint();
1176        if num_defined == num_decoded {
1177            Ok(ij)
1178        } else {
1179            Err(GribError::InvalidValueError(format!(
1180                "number of grid points does not match: {num_defined} (defined) vs {num_decoded} (decoded)"
1181            )))
1182        }
1183    }
1184}
1185
1186impl<'s, R> LatLons for SubMessage<'s, R> {
1187    type Iter<'a>
1188        = GridPointLatLons
1189    where
1190        Self: 'a;
1191
1192    /// Computes and returns an iterator over latitudes and longitudes of grid
1193    /// points in degrees. [Read more](`crate::LatLons::latlons`)
1194    ///
1195    /// # Examples
1196    ///
1197    /// ```
1198    /// use std::{
1199    ///     fs::File,
1200    ///     io::{BufReader, Read},
1201    /// };
1202    ///
1203    /// use grib::LatLons;
1204    ///
1205    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
1206    ///     let mut buf = Vec::new();
1207    ///
1208    ///     let f = File::open("testdata/gdas.t12z.pgrb2.0p25.f000.0-10.xz")?;
1209    ///     let f = BufReader::new(f);
1210    ///     let mut f = xz2::bufread::XzDecoder::new(f);
1211    ///     f.read_to_end(&mut buf)?;
1212    ///
1213    ///     let f = std::io::Cursor::new(buf);
1214    ///     let grib2 = grib::from_reader(f)?;
1215    ///
1216    ///     let mut iter = grib2.iter();
1217    ///     let (_, message) = iter.next().ok_or_else(|| "first message is not found")?;
1218    ///
1219    ///     let mut latlons = message.latlons()?;
1220    ///     assert_eq!(latlons.next(), Some((90.0, 0.0)));
1221    ///     assert_eq!(latlons.next(), Some((90.0, 0.25)));
1222    ///     Ok(())
1223    /// }
1224    /// ```
1225    fn latlons_unchecked<'a>(&'a self) -> Result<Self::Iter<'a>, GribError> {
1226        let grid_def = self.grid_def();
1227        let num_defined = grid_def.num_points() as usize;
1228        let latlons = GridDefinitionTemplateValues::try_from(grid_def)?.latlons_unchecked()?;
1229        let (num_decoded, _) = latlons.size_hint();
1230        if num_defined == num_decoded {
1231            Ok(latlons)
1232        } else {
1233            Err(GribError::InvalidValueError(format!(
1234                "number of grid points does not match: {num_defined} (defined) vs {num_decoded} (decoded)"
1235            )))
1236        }
1237    }
1238}
1239
1240pub struct SubMessageSection<'a> {
1241    pub index: usize,
1242    pub body: &'a SectionInfo,
1243}
1244
1245impl<'a> SubMessageSection<'a> {
1246    pub fn new(index: usize, body: &'a SectionInfo) -> Self {
1247        Self { index, body }
1248    }
1249
1250    pub fn template_code(&self) -> Option<TemplateInfo> {
1251        self.body.get_tmpl_code()
1252    }
1253
1254    pub fn describe(&self) -> Option<String> {
1255        self.template_code().and_then(|code| code.describe())
1256    }
1257}
1258
1259/// External information used to interpret GRIB2 code tables.
1260///
1261/// Lookups currently use the bundled WMO definitions, without version
1262/// selection.
1263#[derive(Debug, Clone, Copy)]
1264pub struct Grib2Context {
1265    pub discipline: u8,
1266}
1267
1268/// Context for interpreting parameter numbers within a parameter category.
1269#[derive(Debug, Clone, Copy)]
1270pub struct ParameterContext {
1271    pub discipline: u8,
1272    pub category: u8,
1273}
1274
1275impl Grib2Context {
1276    pub fn with_parameter_category(
1277        &self,
1278        category: crate::def::grib2::table::ParamCategory,
1279    ) -> ParameterContext {
1280        ParameterContext {
1281            discipline: self.discipline,
1282            category: category.0,
1283        }
1284    }
1285}
1286
1287#[cfg(test)]
1288mod tests {
1289    use std::{fs::File, io::BufReader};
1290
1291    use super::*;
1292    use crate::test_utils::data::grib2::{DWD_ICON, JMA_MSMGUID, NOAA_GDAS_0_10};
1293
1294    macro_rules! sect_placeholder {
1295        ($num:expr $(,)?) => {{
1296            SectionInfo {
1297                num: $num,
1298                offset: 0,
1299                size: 0,
1300                body: None,
1301            }
1302        }};
1303    }
1304
1305    #[test]
1306    fn context_from_buf_reader() {
1307        let f = File::open(DWD_ICON).unwrap();
1308        let f = BufReader::new(f);
1309        let result = from_reader(f);
1310        assert!(result.is_ok())
1311    }
1312
1313    #[test]
1314    fn context_from_bytes() {
1315        let buf = crate::test_utils::decompress_to_vec(DWD_ICON).unwrap();
1316        let result = from_bytes(&buf);
1317        assert!(result.is_ok())
1318    }
1319
1320    #[test]
1321    fn get_tmpl_code_normal() {
1322        let sect = SectionInfo {
1323            num: 5,
1324            offset: 8902,
1325            size: 23,
1326            body: Some(SectionBody::Section5(
1327                ReprDefinition::from_payload(
1328                    vec![0x00, 0x01, 0x50, 0x00, 0x00, 0xc8].into_boxed_slice(),
1329                )
1330                .unwrap(),
1331            )),
1332        };
1333
1334        assert_eq!(sect.get_tmpl_code(), Some(TemplateInfo(5, 200)));
1335    }
1336
1337    #[test]
1338    fn get_templates_normal() {
1339        let sects = vec![
1340            sect_placeholder!(0),
1341            sect_placeholder!(1),
1342            SectionInfo {
1343                num: 3,
1344                offset: 0,
1345                size: 0,
1346                body: Some(SectionBody::Section3(
1347                    GridDefinition::from_payload(vec![0; 9].into_boxed_slice()).unwrap(),
1348                )),
1349            },
1350            SectionInfo {
1351                num: 4,
1352                offset: 0,
1353                size: 0,
1354                body: Some(SectionBody::Section4(
1355                    ProdDefinition::from_payload(vec![0; 4].into_boxed_slice()).unwrap(),
1356                )),
1357            },
1358            SectionInfo {
1359                num: 5,
1360                offset: 0,
1361                size: 0,
1362                body: Some(SectionBody::Section5(
1363                    ReprDefinition::from_payload(vec![0; 6].into_boxed_slice()).unwrap(),
1364                )),
1365            },
1366            sect_placeholder!(6),
1367            sect_placeholder!(7),
1368            SectionInfo {
1369                num: 3,
1370                offset: 0,
1371                size: 0,
1372                body: Some(SectionBody::Section3(
1373                    GridDefinition::from_payload(
1374                        vec![0, 0, 0, 0, 0, 0, 0, 0, 1].into_boxed_slice(),
1375                    )
1376                    .unwrap(),
1377                )),
1378            },
1379            SectionInfo {
1380                num: 4,
1381                offset: 0,
1382                size: 0,
1383                body: Some(SectionBody::Section4(
1384                    ProdDefinition::from_payload(vec![0; 4].into_boxed_slice()).unwrap(),
1385                )),
1386            },
1387            SectionInfo {
1388                num: 5,
1389                offset: 0,
1390                size: 0,
1391                body: Some(SectionBody::Section5(
1392                    ReprDefinition::from_payload(vec![0; 6].into_boxed_slice()).unwrap(),
1393                )),
1394            },
1395            sect_placeholder!(6),
1396            sect_placeholder!(7),
1397            sect_placeholder!(8),
1398        ]
1399        .into_boxed_slice();
1400
1401        assert_eq!(
1402            get_templates(&sects),
1403            vec![
1404                TemplateInfo(3, 0),
1405                TemplateInfo(3, 1),
1406                TemplateInfo(4, 0),
1407                TemplateInfo(5, 0),
1408            ]
1409        );
1410    }
1411
1412    macro_rules! test_submessage_iterator {
1413        ($((
1414            $name:ident,
1415            $xz_compressed_input:expr,
1416            $nth:expr,
1417            $expected_index:expr,
1418            $expected_section_indices:expr $(,)?
1419        )),* $(,)?) => ($(
1420            #[test]
1421            fn $name() -> Result<(), Box<dyn std::error::Error>> {
1422                let buf = crate::test_utils::decompress_to_vec($xz_compressed_input)?;
1423
1424                let f = Cursor::new(buf);
1425                let grib2 = crate::from_reader(f)?;
1426                let mut iter = grib2.iter();
1427
1428                let (actual_index, message) = iter.nth($nth).ok_or_else(|| "item not available")?;
1429                assert_eq!(actual_index, $expected_index);
1430                let actual_section_indices = get_section_indices(message);
1431                assert_eq!(actual_section_indices, $expected_section_indices);
1432
1433                Ok(())
1434            }
1435        )*);
1436    }
1437
1438    test_submessage_iterator! {
1439        (
1440            item_0_from_submessage_iterator_for_single_message_data_with_multiple_submessages,
1441            JMA_MSMGUID,
1442            0,
1443            (0, 0),
1444            (0, 1, None, 2, 3, 4, 5, 6, 0),
1445        ),
1446        (
1447            item_1_from_submessage_iterator_for_single_message_data_with_multiple_submessages,
1448            JMA_MSMGUID,
1449            1,
1450            (0, 1),
1451            (0, 1, None, 2, 7, 8, 9, 10, 0),
1452        ),
1453        (
1454            item_0_from_submessage_iterator_for_multi_message_data,
1455            NOAA_GDAS_0_10,
1456            0,
1457            (0, 0),
1458            (0, 1, None, 2, 3, 4, 5, 6, 7),
1459        ),
1460        (
1461            item_1_from_submessage_iterator_for_multi_message_data,
1462            NOAA_GDAS_0_10,
1463            1,
1464            (1, 0),
1465            (8, 9, None, 10, 11, 12, 13, 14, 15),
1466        ),
1467    }
1468
1469    fn get_section_indices<R>(
1470        submessage: SubMessage<'_, R>,
1471    ) -> (
1472        usize,
1473        usize,
1474        Option<usize>,
1475        usize,
1476        usize,
1477        usize,
1478        usize,
1479        usize,
1480        usize,
1481    ) {
1482        (
1483            submessage.0.index,
1484            submessage.1.index,
1485            submessage.2.map(|s| s.index),
1486            submessage.3.index,
1487            submessage.4.index,
1488            submessage.5.index,
1489            submessage.6.index,
1490            submessage.7.index,
1491            submessage.8.index,
1492        )
1493    }
1494}