serdeconv/
convert_msgpack.rs

1use rmp_serde;
2use serde::{Deserialize, Serialize};
3use std::fs::File;
4use std::io::{Read, Write};
5use std::path::Path;
6
7use {Error, Result};
8
9/// Converts from the MessagePack file to a value of `T` type.
10pub fn from_msgpack_file<T, P>(path: P) -> Result<T>
11where
12    T: for<'a> Deserialize<'a>,
13    P: AsRef<Path>,
14{
15    let f = track!(File::open(path).map_err(Error::from))?;
16    track!(from_msgpack_reader(f))
17}
18
19/// Reads a MessagePack bytes from the reader and converts it to a value of `T` type.
20pub fn from_msgpack_reader<T, R>(reader: R) -> Result<T>
21where
22    T: for<'a> Deserialize<'a>,
23    R: Read,
24{
25    let value = track!(rmp_serde::decode::from_read(reader).map_err(Error::from))?;
26    Ok(value)
27}
28
29/// Converts from the MessagePack bytes to a value of `T` type.
30pub fn from_msgpack_slice<'a, T>(bytes: &'a [u8]) -> Result<T>
31where
32    T: Deserialize<'a>,
33{
34    let value = track!(rmp_serde::from_slice(bytes).map_err(Error::from))?;
35    Ok(value)
36}
37
38/// Converts the value to a MessagePack bytes and writes it to the speficied file.
39pub fn to_msgpack_file<T, P>(value: &T, path: P) -> Result<()>
40where
41    T: ?Sized + Serialize,
42    P: AsRef<Path>,
43{
44    let f = track!(File::create(path).map_err(Error::from))?;
45    track!(to_msgpack_writer(value, f))
46}
47
48/// Converts the value to a MessagePack bytes and writes it to the writer.
49pub fn to_msgpack_writer<T, W>(value: &T, mut writer: W) -> Result<()>
50where
51    T: ?Sized + Serialize,
52    W: Write,
53{
54    track!(rmp_serde::encode::write(&mut writer, value).map_err(Error::from,))?;
55    Ok(())
56}
57
58/// Converts the value to a MessagePack bytes.
59pub fn to_msgpack_vec<T>(value: &T) -> Result<Vec<u8>>
60where
61    T: ?Sized + Serialize,
62{
63    let bytes = track!(rmp_serde::encode::to_vec(value).map_err(Error::from))?;
64    Ok(bytes)
65}