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
//! Serialization wrapper
use serde::{Serialize, Deserialize, de::DeserializeOwned};

use core::default::Default;
use core::{mem, marker};
use std::{path, io};

use crate::file as inner;

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

#[cfg(feature = "bincode")]
pub mod bincode;
#[cfg(feature = "bincode")]
pub use self::bincode::Bincode;

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

#[cfg(feature = "json")]
pub mod json;
#[cfg(feature = "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 data = Ser::serialize(&Data::default())?;
                if data.len() == 0 {
                    return Err(empty_write_error());
                }
                let mut inner = inner::Storage::open(path)?;
                inner.put_data(&data)?;
                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 data = Ser::serialize(&default)?;
                if data.len() == 0 {
                    return Err(empty_write_error());
                }
                let mut inner = inner::Storage::open(path)?;
                inner.put_data(&data)?;
                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_default()
    }

    ///Saves raw bytes into file map.
    ///
    ///It is not possible to write 0 sizes slices
    ///and error shall be returned in this case.
    pub fn save_bytes(&mut self, bytes: &[u8]) -> io::Result<()> {
        match bytes.len() {
            0 => Err(empty_write_error()),
            _ => self.inner.put_data(&bytes)
        }
    }

    ///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> {
        //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 data = Ser::deserialize(inner.as_slice())?;
        let data = cb(data);
        //TODO: UB
        //      For some reason if you try to use
        //      writer interface you get corrupted output
        //      I assume it is due to lifetime hack above
        let data = Ser::serialize(&data)?;
        self.save_bytes(&data)
    }

    ///Synchronously flushes changes of file.
    pub fn flush_sync(&mut self) -> io::Result<()> {
        self.inner.flush_sync()
    }

    ///Asynchronously flushes changes of file.
    pub fn flush_async(&mut self) -> io::Result<()> {
        self.inner.flush_sync()
    }

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

    #[inline]
    ///Saves data to file and flushes synchronously to policy.
    pub fn save_sync<'de>(&mut self, data: &Data) -> io::Result<()> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        self.save(&data)?;
        self.flush_sync()
    }

    #[inline]
    ///Saves data to file and flushes asynchronously to policy.
    pub fn save_async<'de>(&mut self, data: &Data) -> io::Result<()> where Data: Serialize + Deserialize<'de>, Ser: Serialization<'de, Data> {
        self.save(&data)?;
        self.flush_async()
    }
}