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
//! Serialization wrapper
extern crate serde;

use self::serde::{Serialize, Deserialize, de::DeserializeOwned};

use ::std::default::Default;
use ::std::marker;
use ::std::io;
use ::std::path;
use ::std::mem;

use ::file as inner;

/// Describes methods to serialize/deserialize data
pub trait Serialization<'de, T: Serialize + Deserialize<'de>>: Default {
    /// Serializes data into binary.
    fn serialize(data: &T) -> Result<Vec<u8>, io::Error>;
    /// Deserializes binary into data
    fn deserialize(bytes: &'de [u8]) -> Result<T, io::Error>;
}

#[cfg(feature = "ser_toml")]
pub mod toml;
#[cfg(feature = "ser_toml")]
pub use self::toml::Toml;

#[cfg(feature = "ser_json")]
pub mod json;
#[cfg(feature = "ser_json")]
pub use self::json::Json;

#[inline(always)]
fn empty_write_error() -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, "Attempt to write data that serializes into empty bytes sequence")
}

///View on memory mapped File's Data.
///
///In comparsion with [File](struct.File.html) it doesn't
///hold `Data` in memory and instead load on demand.
///
/// ## Type parameters:
///
/// - `Data` - is data's type that can be serialized and de-serialized using `serde`
/// - `Ser` - describes `serde` implementation to use
///
/// ## Usage:
///
/// ```rust
/// extern crate mmap_storage;
///
/// use std::fs;
/// use std::collections::HashMap;
///
/// const STORAGE_PATH: &'static str = "some_view.toml";
///
/// use mmap_storage::serializer::{
///     FileView,
///     Toml
/// };
///
/// fn handle_storage() {
///     let mut storage = FileView::<HashMap<String, String>, Toml>::open(STORAGE_PATH).expect("To create storage");
///     let mut data = match storage.load() {
///         Ok(data) => data,
///         Err(error) => HashMap::new()
///     };
///     data.insert(1.to_string(), "".to_string());
///     storage.save(&data);
/// }
/// fn main() {
///     handle_storage();
///     let _ = fs::remove_file(STORAGE_PATH);
/// }
/// ```
pub struct FileView<Data, Ser> {
    inner: inner::Storage,
    _data: marker::PhantomData<Data>,
    _ser: marker::PhantomData<Ser>
}

impl<Data, Ser> FileView<Data, Ser> {
    ///Opens view on file storage.
    pub fn open<P: AsRef<path::Path>>(path: P) -> io::Result<Self> {
        inner::Storage::open(path).map(|mmap| Self {
            inner: mmap,
            _data: marker::PhantomData,
            _ser: marker::PhantomData,
        })
    }

    ///Opens view on file storage if it exists. If not initialize with default impl.
    ///
    ///Note it is error to try to write empty data.
    pub fn open_or_default<'de, P: AsRef<path::Path>>(path: P) -> io::Result<Self> where Data: Serialize + Deserialize<'de> + Default, Ser: Serialization<'de, Data> {
        let path = path.as_ref();
        let inner = match inner::Storage::open_exising(path) {
            Ok(inner) => inner,
            Err(_) => {
                let default = Ser::serialize(&Data::default())?;
                if default.len() == 0 {
                    return Err(empty_write_error());
                }
                let mut inner = inner::Storage::open(path)?;
                inner.put_data(&default)?;
                inner.flush_sync()?;
                inner
            }
        };

        Ok(Self {
            inner,
            _data: marker::PhantomData,
            _ser: marker::PhantomData,
        })
    }

    ///Opens view on file storage if it exists. If not initialize use provided default data.
    ///
    ///Note it is error to try to write empty data.
    pub fn open_or<'de, P: AsRef<path::Path>>(path: P, default: &Data) -> io::Result<Self>
        where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        let path = path.as_ref();
        let inner = match inner::Storage::open_exising(path) {
            Ok(inner) => inner,
            Err(_) => {
                let default = Ser::serialize(&default)?;
                if default.len() == 0 {
                    return Err(empty_write_error());
                }
                let mut inner = inner::Storage::open(path)?;
                inner.put_data(&default)?;
                inner.flush_sync()?;
                inner
            }
        };

        Ok(Self {
            inner,
            _data: marker::PhantomData,
            _ser: marker::PhantomData,
        })
    }

    ///Loads data, if it is available.
    ///
    ///If currently file cannot be serialized it returns Error
    pub fn load<'de>(&'de self) -> io::Result<Data> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        Ser::deserialize(self.inner.as_slice())
    }

    ///Loads data, if it is available.
    ///
    ///If currently file cannot be serialized it returns Error
    pub fn load_owned<'de>(&'de self) -> io::Result<Data> where Data: Serialize + DeserializeOwned, Ser: Serialization<'de, Data> {
        Ser::deserialize(self.inner.as_slice())
    }

    ///Loads data, if it is available or use default impl.
    pub fn load_or_default<'de>(&'de self) -> Data where Data: Serialize + Deserialize<'de> + Default, Ser: Serialization<'de, Data> {
        Ser::deserialize(self.inner.as_slice()).unwrap_or(Data::default())
    }

    ///Modifies data via temporary serialization.
    ///
    ///This method is useful when working with non-owned data
    ///as it is not possible to load and save in the same scope.
    ///
    ///**NOTE:** In case of non-owned data it is valid
    ///only until the lifetime of callback execution.
    pub fn modify<'de, F: FnOnce(Data) -> Data>(&mut self, cb: F) -> io::Result<()> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        let new_data = {
            //We cannot give 'de lifetime to reference
            //as it would tie up user.
            //The borrow will live only in this scope
            //so we can hack  it
            let inner: &inner::Storage = unsafe { mem::transmute(&self.inner) };
            let mut data = Ser::deserialize(inner.as_slice())?;
            let data = cb(data);
            Ser::serialize(&data)?
        };

        if new_data.len() == 0 {
            Err(empty_write_error())
        } else {
            self.inner.put_data(&new_data)?;
            self.inner.flush_sync()
        }
    }

    fn inner_save<'de>(&mut self, data: &Data) -> io::Result<()> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        let data = Ser::serialize(&data)?;
        if data.len() == 0 {
            Err(empty_write_error())
        } else {
            self.inner.put_data(&data)
        }
    }

    ///Saves data to file and flushes.
    ///
    ///It completely overwrites existing one.
    pub fn save<'de>(&mut self, data: &Data) -> io::Result<()> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        self.inner_save(&data)?;
        self.inner.flush_sync()
    }

    ///Saves data to file and asynchronously flushes.
    ///
    ///It completely overwrites existing one.
    pub fn save_async<'de>(&mut self, data: &Data) -> io::Result<()> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        self.inner_save(&data)?;
        self.inner.flush_async()
    }
}