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
use std::ptr;

use fallible_streaming_iterator::FallibleStreamingIterator;

use crate::{
    errors::CodesError,
    intermediate_bindings::{codes_handle_delete, codes_handle_new_from_file},
    CodesHandle, KeyedMessage,
};
#[cfg(feature = "experimental_index")]
use crate::{intermediate_bindings::codes_handle_new_from_index, CodesIndex};

use super::GribFile;

/// # Errors
///
/// The `advance()` and `next()` methods will return [`CodesInternal`](crate::errors::CodesInternal)
/// when internal ecCodes function returns non-zero code.
impl FallibleStreamingIterator for CodesHandle<GribFile> {
    type Item = KeyedMessage;

    type Error = CodesError;

    fn advance(&mut self) -> Result<(), Self::Error> {
        unsafe {
            codes_handle_delete(self.unsafe_message.message_handle)?;
        }

        // nullify message handle so that destructor is harmless
        // it might be excessive but it follows the correct pattern
        self.unsafe_message.message_handle = ptr::null_mut();

        let new_eccodes_handle =
            unsafe { codes_handle_new_from_file(self.source.pointer, self.product_kind)? };

        self.unsafe_message = KeyedMessage {
            message_handle: new_eccodes_handle,
        };

        Ok(())
    }

    fn get(&self) -> Option<&Self::Item> {
        if self.unsafe_message.message_handle.is_null() {
            None
        } else {
            Some(&self.unsafe_message)
        }
    }
}

#[cfg(feature = "experimental_index")]
#[cfg_attr(docsrs, doc(cfg(feature = "experimental_index")))]
/// # Errors
///
/// The `advance()` and `next()` methods will return [`CodesInternal`](crate::errors::CodesInternal)
/// when internal ecCodes function returns non-zero code.
impl FallibleStreamingIterator for CodesHandle<CodesIndex> {
    type Item = KeyedMessage;

    type Error = CodesError;

    fn advance(&mut self) -> Result<(), Self::Error> {
        unsafe {
            codes_handle_delete(self.unsafe_message.message_handle)?;
        }

        // nullify message handle so that destructor is harmless
        // it might be excessive but it follows the correct pattern
        self.unsafe_message.message_handle = ptr::null_mut();

        let new_eccodes_handle = unsafe { codes_handle_new_from_index(self.source.pointer)? };

        self.unsafe_message = KeyedMessage {
            message_handle: new_eccodes_handle,
        };

        Ok(())
    }

    fn get(&self) -> Option<&Self::Item> {
        if self.unsafe_message.message_handle.is_null() {
            None
        } else {
            Some(&self.unsafe_message)
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        codes_handle::{CodesHandle, ProductKind},
        KeyType,
    };
    use anyhow::{Context, Ok, Result};
    use fallible_streaming_iterator::FallibleStreamingIterator;
    use std::path::Path;

    #[test]
    fn iterator_lifetimes() -> Result<()> {
        let file_path = Path::new("./data/iceland-levels.grib");
        let product_kind = ProductKind::GRIB;
        let mut handle = CodesHandle::new_from_file(file_path, product_kind)?;

        let msg1 = handle.next()?.context("Message not some")?;
        let key1 = msg1.read_key("typeOfLevel")?;

        let msg2 = handle.next()?.context("Message not some")?;
        let key2 = msg2.read_key("typeOfLevel")?;

        let msg3 = handle.next()?.context("Message not some")?;
        let key3 = msg3.read_key("typeOfLevel")?;

        assert_eq!(key1.value, KeyType::Str("isobaricInhPa".to_string()));
        assert_eq!(key2.value, KeyType::Str("isobaricInhPa".to_string()));
        assert_eq!(key3.value, KeyType::Str("isobaricInhPa".to_string()));

        Ok(())
    }

    #[test]
    fn iterator_fn() -> Result<()> {
        let file_path = Path::new("./data/iceland-surface.grib");
        let product_kind = ProductKind::GRIB;

        let mut handle = CodesHandle::new_from_file(file_path, product_kind)?;

        while let Some(msg) = handle.next()? {
            let key = msg.read_key("shortName")?;

            match key.value {
                KeyType::Str(_) => {}
                _ => panic!("Incorrect variant of string key"),
            }
        }

        Ok(())
    }

    #[test]
    fn iterator_collected() -> Result<()> {
        let file_path = Path::new("./data/iceland-surface.grib");
        let product_kind = ProductKind::GRIB;
        let mut handle = CodesHandle::new_from_file(file_path, product_kind)?;

        let mut handle_collected = vec![];

        while let Some(msg) = handle.next()? {
            handle_collected.push(msg.try_clone()?);
        }

        for msg in handle_collected {
            let key = msg.read_key("name")?;
            match key.value {
                KeyType::Str(_) => {}
                _ => panic!("Incorrect variant of string key"),
            }
        }

        Ok(())
    }

    #[test]
    fn iterator_return() -> Result<()> {
        let file_path = Path::new("./data/iceland-surface.grib");
        let product_kind = ProductKind::GRIB;

        let mut handle = CodesHandle::new_from_file(file_path, product_kind)?;
        let current_message = handle.next()?.context("Message not some")?;

        assert!(!current_message.message_handle.is_null());

        Ok(())
    }

    #[test]
    fn iterator_beyond_none() -> Result<()> {
        let file_path = Path::new("./data/iceland-surface.grib");
        let product_kind = ProductKind::GRIB;

        let mut handle = CodesHandle::new_from_file(file_path, product_kind)?;

        assert!(handle.next()?.is_some());
        assert!(handle.next()?.is_some());
        assert!(handle.next()?.is_some());
        assert!(handle.next()?.is_some());
        assert!(handle.next()?.is_some());

        assert!(handle.next()?.is_none());
        assert!(handle.next()?.is_none());
        assert!(handle.next()?.is_none());
        assert!(handle.next()?.is_none());

        Ok(())
    }

    #[test]
    fn iterator_filter() -> Result<()> {
        let file_path = Path::new("./data/iceland.grib");
        let product_kind = ProductKind::GRIB;

        let mut handle = CodesHandle::new_from_file(file_path, product_kind)?;

        // Use iterator to get a Keyed message with shortName "msl" and typeOfLevel "surface"
        // First, filter and collect the messages to get those that we want
        let mut level = vec![];

        while let Some(msg) = handle.next()? {
            if msg.read_key("shortName")?.value == KeyType::Str("msl".to_string())
                && msg.read_key("typeOfLevel")?.value == KeyType::Str("surface".to_string())
            {
                level.push(msg.try_clone()?);
            }
        }

        // Now unwrap and access the first and only element of resulting vector
        // Find nearest modifies internal KeyedMessage fields so we need mutable reference
        let level = &level[0];

        println!("{:?}", level.read_key("shortName"));

        // Get the four nearest gridpoints of Reykjavik
        let nearest_gridpoints = level.codes_nearest()?.find_nearest(64.13, -21.89)?;

        // Print value and distance of the nearest gridpoint
        println!(
            "value: {}, distance: {}",
            nearest_gridpoints[3].value, nearest_gridpoints[3].distance
        );

        Ok(())
    }
}