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
use std::{fs::OpenOptions, io::Write, path::Path, slice};

use crate::{
    codes_handle::{Key, KeyType, KeyedMessage},
    errors::CodesError,
    intermediate_bindings::{
        codes_get_message, codes_set_bytes, codes_set_double, codes_set_double_array,
        codes_set_long, codes_set_long_array, codes_set_string,
    },
};

impl KeyedMessage {
    ///Function to write given `KeyedMessage` to a file at provided path.
    ///If file does not exists it will be created.
    ///If `append` is set to `true` file will be opened in append mode
    ///and no data will be overwritten (useful when writing mutiple messages to one file).
    ///
    ///## Example
    ///
    ///```
    ///# use eccodes::{
    ///#     codes_handle::{CodesHandle, Key, KeyType::Str, ProductKind::GRIB},
    ///#     errors::CodesError,
    ///# };
    ///# use crate::eccodes::FallibleIterator;
    ///# use std::path::Path;
    ///# use std::fs::remove_file;
    ///#
    ///# fn main() -> Result<(), CodesError> {
    ///let in_path = Path::new("./data/iceland-levels.grib");
    ///let out_path  = Path::new("./data/iceland-temperature-levels.grib");
    ///
    ///let handle = CodesHandle::new_from_file(in_path, GRIB)?;
    ///
    ///let mut t_levels =
    ///    handle.filter(|msg| Ok(msg.read_key("shortName")?.value == Str("t".to_string())));
    ///
    ///while let Some(msg) = t_levels.next()? {
    ///    msg.write_to_file(out_path, true)?;
    ///}
    ///# remove_file(out_path).unwrap();
    ///# Ok(())
    ///# }
    ///```
    ///
    ///## Errors
    ///
    ///Returns [`CodesError::FileHandlingInterrupted`] when the file cannot be opened,
    ///created or correctly written.
    ///
    ///Returns [`CodesInternal`](crate::errors::CodesInternal)
    ///when internal ecCodes function returns non-zero code.
    pub fn write_to_file(&self, file_path: &Path, append: bool) -> Result<(), CodesError> {
        let msg = unsafe { codes_get_message(self.message_handle)? };
        let buf = unsafe { slice::from_raw_parts(msg.0.cast::<u8>(), msg.1 as usize) };
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .append(append)
            .open(file_path)?;

        file.write_all(buf)?;

        Ok(())
    }

    ///Function to set specified `Key` inside the `KeyedMessage`.
    ///This function automatically matches the `KeyType` and uses adequate
    ///internal ecCodes function to set the key.
    ///The message must be mutable to use this function.
    ///
    ///**User must provide the `Key` with correct type**, otherwise
    ///error will occur.
    ///Note that not all keys can be set, for example
    ///`"name"` and `shortName` are read-only. Trying to set such keys
    ///will result in error. Some keys can also be set using a non-native
    ///type (eg. `centre`), but [`read_key()`](KeyedMessage::read_key()) function will only read then
    ///in native type.
    ///
    ///Refer to [ecCodes library documentation](https://confluence.ecmwf.int/display/ECC/ecCodes+Home)
    ///for more details.
    ///
    ///## Example
    ///
    ///```
    ///# use eccodes::{
    ///#     codes_handle::{CodesHandle, Key, KeyType, ProductKind::GRIB},
    ///# };
    ///# use crate::eccodes::FallibleIterator;
    ///# use std::path::Path;
    ///#
    ///let file_path = Path::new("./data/iceland.grib");
    ///
    ///let mut handle = CodesHandle::new_from_file(file_path, GRIB).unwrap();
    ///let mut current_message = handle.next().unwrap().unwrap();
    ///
    ///let new_key = Key {
    ///    name: "centre".to_string(),
    ///    value: KeyType::Str("cnmc".to_string()),
    ///};
    ///
    ///current_message.write_key(new_key).unwrap();
    ///```
    ///
    ///## Errors
    ///
    ///This method will return [`CodesInternal`](crate::errors::CodesInternal)
    ///when internal ecCodes function returns non-zero code.
    pub fn write_key(&mut self, key: Key) -> Result<(), CodesError> {
        match key.value {
            KeyType::Float(val) => unsafe {
                codes_set_double(self.message_handle, &key.name, val)?;
            },
            KeyType::Int(val) => unsafe {
                codes_set_long(self.message_handle, &key.name, val)?;
            },
            KeyType::FloatArray(val) => unsafe {
                codes_set_double_array(self.message_handle, &key.name, &val)?;
            },
            KeyType::IntArray(val) => unsafe {
                codes_set_long_array(self.message_handle, &key.name, &val)?;
            },
            KeyType::Str(val) => unsafe {
                codes_set_string(self.message_handle, &key.name, &val)?;
            },
            KeyType::Bytes(val) => unsafe {
                codes_set_bytes(self.message_handle, &key.name, &val)?;
            },
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        codes_handle::{
            CodesHandle, Key,
            KeyType::{self},
            ProductKind,
        },
        FallibleIterator,
    };
    use std::{fs::remove_file, path::Path};

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

        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let current_message = handle.next().unwrap().unwrap();

        drop(handle);

        let out_path = Path::new("./data/iceland_write.grib");
        current_message.write_to_file(out_path, false).unwrap();

        remove_file(out_path).unwrap();
    }

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

        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let current_message = handle.next().unwrap().unwrap().clone();

        drop(handle);

        let out_path = Path::new("./data/iceland_write_clone.grib");
        current_message.write_to_file(out_path, false).unwrap();

        remove_file(out_path).unwrap();
    }

    #[test]
    fn append_message() {
        let product_kind = ProductKind::GRIB;
        let out_path = Path::new("./data/iceland_append.grib");

        let file_path = Path::new("./data/iceland-surface.grib");
        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let current_message = handle.next().unwrap().unwrap();
        current_message.write_to_file(out_path, false).unwrap();

        let file_path = Path::new("./data/iceland-levels.grib");
        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let current_message = handle.next().unwrap().unwrap();
        current_message.write_to_file(out_path, true).unwrap();

        remove_file(out_path).unwrap();
    }

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

        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let mut current_message = handle.next().unwrap().unwrap();

        let old_key = current_message.read_key("centre").unwrap();

        let new_key = Key {
            name: "centre".to_string(),
            value: KeyType::Str("cnmc".to_string()),
        };

        current_message.write_key(new_key.clone()).unwrap();

        let read_key = current_message.read_key("centre").unwrap();

        assert_eq!(new_key, read_key);
        assert_ne!(old_key, read_key);
    }

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

        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let mut current_message = handle.next().unwrap().unwrap();

        let old_key = current_message.read_key("centre").unwrap();

        let new_key = Key {
            name: "centre".to_string(),
            value: KeyType::Str("cnmc".to_string()),
        };

        current_message.write_key(new_key.clone()).unwrap();

        current_message
            .write_to_file(Path::new("./data/iceland_edit.grib"), false)
            .unwrap();

        let file_path = Path::new("./data/iceland_edit.grib");

        let mut handle = CodesHandle::new_from_file(file_path, product_kind).unwrap();
        let current_message = handle.next().unwrap().unwrap();

        let read_key = current_message.read_key("centre").unwrap();

        assert_eq!(new_key, read_key);
        assert_ne!(old_key, read_key);

        remove_file(Path::new("./data/iceland_edit.grib")).unwrap();
    }
}