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
//Copyright 2020
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//documentation files (the "Software"), to deal in the Software without restriction, including without limitation
//the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
//and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions
//of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
//THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! A small lib that help to serialize and deserialize from/to rmp (RustMessagePack) with a file.
//! It does nothing special, just encapsulates rmp_serde in two functions that can be used repeatedly.
//! ```
//! #[macro_use]
//! extern crate serde_derive;
//!
//! use rmp_fs::{save_to_rmp, load_from_rmp};
//! use std::path::Path;
//!
//! // Define a struct of data
//! #[derive(Debug, PartialEq, Deserialize, Serialize)]
//! struct ExampleData {
//!     value: i64,
//!     message: String,
//! }
//!
//! fn main() {
//!     let file_name = Path::new("test_rmp_fs.blob");
//!
//!     let data = ExampleData {
//!         value: -123456,
//!         message: "Example rmp_fs".to_string()
//!     };
//!
//!     // Save to a file it return Result<(), Box<dyn Error>>
//!     save_to_rmp(file_name, &data).expect("Fail to save as rmp.");
//!
//!     // Load from a file it return Result<T, Box<dyn Error>>
//!     let data2: ExampleData =load_from_rmp(file_name).expect("Fail to load from rmp.");
//!     println!("{:?}\n{:?}",data,data2);
//! }
//! ```
extern crate rmp_serde as rmps;
extern crate serde;
#[macro_use]
extern crate serde_derive;

use std::fs;
use std::error::Error;
use std::fs::OpenOptions;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;

use rmps::Serializer;
use serde::Serialize;
use serde::de::DeserializeOwned;

/// Save Serializable data to a file as RustMessagePack format.
/// Note if the file already exist. **The existing file is deleted.**
pub fn save_to_rmp<T>(file : &Path, data : &T) -> Result<(), Box<dyn Error>>
    where T : Serialize {
    if file.exists() {
        fs::remove_file(file)?;
    }
    let file_handler = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(file)?;

    let mut buf= Vec::new();
    data.serialize(&mut Serializer::new(&mut buf))?;
    let mut buf_writer = BufWriter::new(&file_handler);
    buf_writer.write_all(buf.as_slice())?;
    Ok(())
}

/// Load RustMessagePack format Deserializable data from a file.
pub fn load_from_rmp<T>(file : &Path) -> Result<T, Box<dyn Error>>
    where T : DeserializeOwned{
    let file_handler = OpenOptions::new()
        .read(true)
        .open(file)?;
    let buf_reader = BufReader::new(&file_handler);
    let data : T = rmps::from_read(buf_reader)?;
    Ok(data)
}

/// Tests with different type of data.
#[cfg(test)]
mod tests {
    use std::collections::{HashMap, BTreeSet};
    use std::fs;
    use std::path::Path;

    use chrono::{DateTime, Utc};

    use crate::{load_from_rmp, save_to_rmp};

    #[derive(Debug, PartialEq, Deserialize, Serialize)]
    struct StructTest01 {
        text : String,
        value1 : u16,
        value2 : i32,
        value3 : u8,
        value4 : i16,
        value5 : u32,
        value6 : u64,
        value7 : i64,
        value8 : usize,
        value9 : f32,
        value10 : f64,
        array : Vec<u8>,
        tuple : (DateTime<Utc>,u64),
        complex : StructTest02,
    }

    #[derive(Debug, PartialEq, Deserialize, Serialize)]
    struct StructTest02 {
        data_v : Vec<i16>,
        data_m : HashMap<String,String>,
        state : bool,
    }

    #[derive(Debug, PartialEq, Deserialize, Serialize)]
    enum Status {
        State1,
        State2
    }

    const TEST01_FILE: &str = "data1.rmp";
    const TEST02_FILE: &str = "data2.rmp";
    const TEST03_FILE: &str = "data3.rmp";
    const TEST04_FILE: &str = "data4.rmp";

    #[test]
    fn test_save_load_rmp_file_01() {

        let mut data_m : HashMap<String,String> =HashMap::new();
        data_m.insert("k1".into(),"V1".into());
        data_m.insert("k2".into(),"V2".into());

        let complex = StructTest02 {
            data_v: vec![-1i16;100],
            data_m,
            state: true
        };

        let data1 = StructTest01 {
            text: "Test value1 ڜڝڞڟ".to_string(),
            value1 : u16::max_value(),
            value2 : i32::min_value(),
            value3 : u8::max_value(),
            value4 : i16::min_value(),
            value5 : u32::max_value(),
            value6 : u64::max_value(),
            value7 : i64::min_value(),
            value8 : 1024 as usize,
            value9 : std::f32::INFINITY,
            value10 : std::f64::MAX,
            array: vec![0x62u8;20],
            tuple: (Utc::now(), 0x61),
            complex
        };

        let save_result= save_to_rmp(Path::new(TEST01_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<StructTest01, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST01_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST01_FILE).unwrap();
    }

    #[test]
    fn test_save_load_rmp_file_02() {
        let data1 = Status::State1;

        let save_result= save_to_rmp(Path::new(TEST02_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<Status, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST02_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST02_FILE).unwrap();
    }

    #[test]
    fn test_save_load_rmp_file_03() {
        let data1 = 33i32;

        let save_result= save_to_rmp(Path::new(TEST03_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<i32, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST03_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST03_FILE).unwrap();
    }

    #[test]
    fn test_save_load_rmp_file_04() {
        let mut data1 : BTreeSet<String> = BTreeSet::new();

        data1.insert("Hello".into());
        data1.insert("Salut".into());
        data1.insert("Hola".into());

        let save_result= save_to_rmp(Path::new(TEST04_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<BTreeSet<String>, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST04_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST04_FILE).unwrap();
    }
}