1use super::missing::DecodedValue::{self, Missing1, Missing2, Normal};
2use crate::{decoder::DecodeError, helpers::grib_int_from_bytes};
3
4fn unsigned_int_from_bytes(bytes: &[u8]) -> i64 {
5 bytes
6 .iter()
7 .fold(0_i64, |value, &byte| (value << 8) | i64::from(byte))
8}
9
10pub(crate) struct SpatialDifferencingExtraDescriptors<'a> {
11 slice: &'a [u8],
12 num_octets: usize,
13}
14
15impl<'a> SpatialDifferencingExtraDescriptors<'a> {
16 pub(crate) fn new(
17 order: u8,
18 num_extra_desc_octets: u8,
19 parent_slice: &'a [u8],
20 ) -> Result<Self, DecodeError> {
21 if num_extra_desc_octets == 0 || num_extra_desc_octets > 4 {
22 return Err(DecodeError::from(format!(
23 "unexpected value for \"number of octets required in the data section to specify extra descriptors needed for spatial differencing\": {num_extra_desc_octets}"
24 )));
25 }
26 let num_octets = usize::from(num_extra_desc_octets);
27 let byte_length = usize::from(order + 1) * num_octets;
28 if parent_slice.len() < byte_length {
29 return Err(DecodeError::LengthMismatch);
30 }
31
32 Ok(Self {
33 slice: &parent_slice[..byte_length],
34 num_octets,
35 })
36 }
37
38 pub(crate) fn len(&self) -> usize {
40 self.slice.len()
41 }
42
43 pub(crate) fn minimum(&self) -> i32 {
45 let slice = &self.slice[self.first_value_end_pos()..];
46 grib_int_from_bytes(slice)
47 }
48
49 pub(crate) fn first_values(&self) -> FirstValues<'_, 'a> {
50 FirstValues::new(self)
51 }
52
53 fn first_value_end_pos(&self) -> usize {
54 self.len() - self.num_octets
55 }
56}
57
58pub(crate) struct FirstValues<'s, 'a> {
59 spdiff_info: &'s SpatialDifferencingExtraDescriptors<'a>,
60 pos: usize,
61}
62
63impl<'s, 'a> FirstValues<'s, 'a> {
64 pub(crate) fn new(spdiff_info: &'s SpatialDifferencingExtraDescriptors<'a>) -> Self {
65 Self {
66 spdiff_info,
67 pos: 0,
68 }
69 }
70}
71
72impl Iterator for FirstValues<'_, '_> {
73 type Item = i64;
74
75 fn next(&mut self) -> Option<Self::Item> {
76 if self.pos >= self.spdiff_info.first_value_end_pos() {
77 return None;
78 }
79
80 let num_octets = self.spdiff_info.num_octets;
81 let slice = &self.spdiff_info.slice[self.pos..self.pos + num_octets];
82 let val = unsigned_int_from_bytes(slice);
85 self.pos += num_octets;
86 Some(val)
87 }
88}
89
90pub(crate) enum SpatialDifferencingDecodeIterator<I, J> {
91 FirstOrder(FirstOrderSpatialDifferencingDecodeIterator<I, J>),
92 SecondOrder(SecondOrderSpatialDifferencingDecodeIterator<I, J>),
93}
94
95impl<I, J> Iterator for SpatialDifferencingDecodeIterator<I, J>
96where
97 I: Iterator<Item = DecodedValue<i32>>,
98 J: Iterator<Item = i64>,
99{
100 type Item = DecodedValue<i64>;
101
102 fn next(&mut self) -> Option<Self::Item> {
103 match self {
104 SpatialDifferencingDecodeIterator::FirstOrder(iter) => iter.next(),
105 SpatialDifferencingDecodeIterator::SecondOrder(iter) => iter.next(),
106 }
107 }
108}
109
110pub(crate) struct FirstOrderSpatialDifferencingDecodeIterator<I, J> {
111 iter: I,
112 first_values: J,
113 count: u32,
114 prev: i64,
115}
116
117impl<I, J> FirstOrderSpatialDifferencingDecodeIterator<I, J> {
118 pub(crate) fn new(iter: I, first_values: J) -> Self {
119 Self {
120 iter,
121 first_values,
122 count: 0,
123 prev: 0,
124 }
125 }
126}
127
128impl<I, J> Iterator for FirstOrderSpatialDifferencingDecodeIterator<I, J>
129where
130 I: Iterator<Item = DecodedValue<i32>>,
131 J: Iterator<Item = i64>,
132{
133 type Item = DecodedValue<i64>;
134
135 fn next(&mut self) -> Option<Self::Item> {
136 match self.iter.next() {
137 None => None,
138 Some(Normal(v)) => match self.count {
139 0 => {
140 self.prev = self.first_values.next().unwrap();
141 self.count += 1;
142 Some(Normal(self.prev))
143 }
144 _ => {
145 let v = i64::from(v) + self.prev;
146 self.prev = v;
147 Some(Normal(v))
148 }
149 },
150 Some(Missing1) => Some(Missing1),
151 Some(Missing2) => Some(Missing2),
152 }
153 }
154}
155
156pub(crate) struct SecondOrderSpatialDifferencingDecodeIterator<I, J> {
157 iter: I,
158 first_values: J,
159 count: u32,
160 prev1: i64,
161 prev2: i64,
162}
163
164impl<I, J> SecondOrderSpatialDifferencingDecodeIterator<I, J> {
165 pub(crate) fn new(iter: I, first_values: J) -> Self {
166 Self {
167 iter,
168 first_values,
169 count: 0,
170 prev1: 0,
171 prev2: 0,
172 }
173 }
174}
175
176impl<I, J> Iterator for SecondOrderSpatialDifferencingDecodeIterator<I, J>
177where
178 I: Iterator<Item = DecodedValue<i32>>,
179 J: Iterator<Item = i64>,
180{
181 type Item = DecodedValue<i64>;
182
183 fn next(&mut self) -> Option<Self::Item> {
184 match self.iter.next() {
185 None => None,
186 Some(Normal(v)) => match self.count {
187 0 => {
188 self.prev2 = self.first_values.next().unwrap();
189 self.count += 1;
190 Some(Normal(self.prev2))
191 }
192 1 => {
193 self.prev1 = self.first_values.next().unwrap();
194 self.count += 1;
195 Some(Normal(self.prev1))
196 }
197 _ => {
198 let v = i64::from(v) + 2 * self.prev1 - self.prev2;
199 self.prev2 = self.prev1;
200 self.prev1 = v;
201 Some(Normal(v))
202 }
203 },
204 Some(Missing1) => Some(Missing1),
205 Some(Missing2) => Some(Missing2),
206 }
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::{
213 super::missing::DecodedValue::{Missing1, Missing2},
214 *,
215 };
216
217 #[test]
218 fn spdiff_rejects_truncated_extra_descriptors() {
219 assert!(matches!(
220 SpatialDifferencingExtraDescriptors::new(1, 2, &[0, 1, 2]),
221 Err(DecodeError::LengthMismatch)
222 ));
223 }
224
225 macro_rules! test_spdiff_minimum_value {
226 ($(($name:ident, $num_octets:expr, $expected:expr $(,)?)),* $(,)?) => ($(
227 #[test]
228 fn $name() {
229 let order = 2;
230 let num_extra_desc_octets = $num_octets;
231 let octets = (0x00..0x10).collect::<Vec<_>>();
232 let spdiff_params = SpatialDifferencingExtraDescriptors::new(
233 order,
234 num_extra_desc_octets,
235 &octets,
236 ).unwrap();
237 let actual = spdiff_params.minimum();
238 assert_eq!(actual, $expected);
239 }
240 )*);
241 }
242
243 test_spdiff_minimum_value! {
244 (spdiff_minimum_value_when_num_octets_is_1, 1, 0x02),
245 (spdiff_minimum_value_when_num_octets_is_2, 2, 0x04_05),
246 (spdiff_minimum_value_when_num_octets_is_3, 3, 0x06_07_08),
247 (spdiff_minimum_value_when_num_octets_is_4, 4, 0x08_09_0a_0b),
248 }
249
250 macro_rules! test_spdiff_first_values {
251 ($(($name:ident, $num_octets:expr, $expected:expr $(,)?)),* $(,)?) => ($(
252 #[test]
253 fn $name() {
254 let order = 2;
255 let num_extra_desc_octets = $num_octets;
256 let octets = (0x00..0x10).collect::<Vec<_>>();
257 let spdiff_params = SpatialDifferencingExtraDescriptors::new(
258 order,
259 num_extra_desc_octets,
260 &octets,
261 ).unwrap();
262 let actual = spdiff_params.first_values().collect::<Vec<_>>();
263 assert_eq!(actual, $expected);
264 }
265 )*);
266 }
267
268 test_spdiff_first_values! {
269 (spdiff_first_values_when_num_octets_is_1, 1, vec![0x00, 0x01]),
270 (spdiff_first_values_when_num_octets_is_2, 2, vec![0x00_01, 0x02_03]),
271 (spdiff_first_values_when_num_octets_is_3, 3, vec![0x00_01_02, 0x03_04_05]),
272 (spdiff_first_values_when_num_octets_is_4, 4, vec![0x00_01_02_03, 0x04_05_06_07]),
273 }
274
275 #[test]
276 fn spdiff_first_values_with_high_bits_are_unsigned() -> Result<(), DecodeError> {
277 let cases: [(u8, &[u8], &[i64], i32); 4] = [
278 (1, &[0x7f, 0x80, 0x9d], &[127, 128], -29),
279 (2, &[0x00, 0x7f, 0x80, 0x00, 0x80, 0x01], &[127, 32_768], -1),
280 (
281 3,
282 &[0x00, 0x00, 0x7f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x01],
283 &[127, 8_388_608],
284 -1,
285 ),
286 (
287 4,
288 &[
289 0x00, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x01,
290 ],
291 &[127, 2_147_483_648],
292 -1,
293 ),
294 ];
295 for (num_octets, bytes, expected, minimum) in cases {
296 let descriptors = SpatialDifferencingExtraDescriptors::new(2, num_octets, bytes)?;
297 assert_eq!(descriptors.first_values().collect::<Vec<_>>(), expected);
298 assert_eq!(descriptors.minimum(), minimum);
299 }
300 Ok(())
301 }
302
303 macro_rules! test_first_order_spatial_differencing_decoding {
304 ($(($name:ident, $input:expr, $expected:expr $(,)?)),* $(,)?) => ($(
305 #[test]
306 fn $name() {
307 let input = $input
308 .into_iter();
309 let first_values = vec![100].into_iter();
310 let iter = FirstOrderSpatialDifferencingDecodeIterator::new(input, first_values);
311 assert_eq!(
312 iter.collect::<Vec<_>>(),
313 $expected
314 );
315 }
316 )*);
317 }
318
319 test_first_order_spatial_differencing_decoding! {
320 (
321 first_order_spatial_differencing_decoding_consisting_of_normal_values,
322 (0_u32..10).map(|n| Normal(n as i32 * (-1_i32).pow(n))),
323 vec![
324 Normal(100),
325 Normal(99),
326 Normal(101),
327 Normal(98),
328 Normal(102),
329 Normal(97),
330 Normal(103),
331 Normal(96),
332 Normal(104),
333 Normal(95),
334 ],
335 ),
336 (
337 first_order_spatial_differencing_decoding_with_missing_values_in_first_values,
338 vec![
339 Missing1,
340 Normal(0),
341 Normal(-1),
342 Normal(2),
343 Normal(-3),
344 Normal(4),
345 Normal(-5),
346 Normal(6),
347 Normal(-7),
348 Normal(8),
349 ],
350 vec![
351 Missing1,
352 Normal(100),
353 Normal(99),
354 Normal(101),
355 Normal(98),
356 Normal(102),
357 Normal(97),
358 Normal(103),
359 Normal(96),
360 Normal(104),
361 ],
362 ),
363 (
364 first_order_spatial_differencing_decoding_with_missing_values_in_non_first_values,
365 vec![
366 Normal(0),
367 Normal(-1),
368 Missing1,
369 Normal(2),
370 Normal(-3),
371 Normal(4),
372 Missing2,
373 Normal(-5),
374 Normal(6),
375 Normal(-7),
376 ],
377 vec![
378 Normal(100),
379 Normal(99),
380 Missing1,
381 Normal(101),
382 Normal(98),
383 Normal(102),
384 Missing2,
385 Normal(97),
386 Normal(103),
387 Normal(96),
388 ],
389 ),
390 }
391
392 macro_rules! test_second_order_spatial_differencing_decoding {
393 ($(($name:ident, $input:expr, $expected:expr $(,)?)),* $(,)?) => ($(
394 #[test]
395 fn $name() {
396 let input = $input
397 .into_iter();
398 let first_values = vec![100, 99].into_iter();
399 let iter = SecondOrderSpatialDifferencingDecodeIterator::new(input, first_values);
400 assert_eq!(
401 iter.collect::<Vec<_>>(),
402 $expected
403 );
404 }
405 )*);
406 }
407
408 test_second_order_spatial_differencing_decoding! {
409 (
410 second_order_spatial_differencing_decoding_consisting_of_normal_values,
411 (0_u32..10).map(|n| Normal(n as i32 * (-1_i32).pow(n))),
412 vec![
413 Normal(100),
414 Normal(99),
415 Normal(100),
416 Normal(98),
417 Normal(100),
418 Normal(97),
419 Normal(100),
420 Normal(96),
421 Normal(100),
422 Normal(95),
423 ],
424 ),
425 (
426 second_order_spatial_differencing_decoding_with_missing_values_in_first_values,
427 vec![
428 Missing1,
429 Missing2,
430 Normal(0),
431 Normal(-1),
432 Normal(2),
433 Normal(-3),
434 Normal(4),
435 Normal(-5),
436 Normal(6),
437 Normal(-7),
438 ],
439 vec![
440 Missing1,
441 Missing2,
442 Normal(100),
443 Normal(99),
444 Normal(100),
445 Normal(98),
446 Normal(100),
447 Normal(97),
448 Normal(100),
449 Normal(96),
450 ],
451 ),
452 (
453 second_order_spatial_differencing_decoding_with_missing_values_in_non_first_values,
454 vec![
455 Normal(0),
456 Normal(-1),
457 Missing1,
458 Normal(2),
459 Normal(-3),
460 Normal(4),
461 Missing2,
462 Normal(-5),
463 Normal(6),
464 Normal(-7),
465 ],
466 vec![
467 Normal(100),
468 Normal(99),
469 Missing1,
470 Normal(100),
471 Normal(98),
472 Normal(100),
473 Missing2,
474 Normal(97),
475 Normal(100),
476 Normal(96),
477 ],
478 ),
479 }
480}