easy_mmap 0.3.1

Strongly typed memory mapped files that allow for easy manipulation of large amounts of data.
Documentation
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use std::{
    fs,
    marker::PhantomData,
    ops::{Index, IndexMut},
    os::unix::prelude::AsRawFd,
    slice::{Iter, IterMut},
};

pub use mmap::MapOption;
use mmap::MemoryMap;
use rayon::prelude::*;

/// The main abstraction over the `mmap` crate.
/// Owns a memory map and provides simplified and safe access to this memory region.
/// Also provides some additional features such as iterators over the data.
pub struct EasyMmap<'a, T> {
    _map: MemoryMap,
    _data: &'a mut [T],
    capacity: usize,
    _file: Option<fs::File>,
}

impl<'a, T> EasyMmap<'a, T>
where
    T: Copy,
{
    /// Creates a new EasyMmap struct with enough capacity to hold `capacity` elements of type `T`.
    fn new(capacity: usize, options: &[MapOption], file: Option<fs::File>) -> EasyMmap<'a, T> {
        let map = MemoryMap::new(capacity * std::mem::size_of::<T>(), options).unwrap();
        let slice = unsafe { std::slice::from_raw_parts_mut(map.data().cast::<T>(), capacity) };

        EasyMmap {
            _map: map,
            _data: slice,
            capacity,
            _file: file,
        }
    }

    /// How many elements can be stored in the memory map.
    pub fn len(&self) -> usize {
        self.capacity
    }

    /// Returns a read-only iterator over the elements of the memory map.
    pub fn iter(&self) -> Iter<'_, T> {
        self._data.iter()
    }

    /// Returns a mutable iterator over the elements of the memory map.
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        self._data.iter_mut()
    }

    /// Returns a parallel iterator over the elements of the memory map.
    pub fn par_iter(&self) -> impl ParallelIterator<Item = &T> where T: Send + Sync {
        self._data.par_iter()
    }

    /// Returns a mutable parallel iterator over the elements of the memory map.
    pub fn par_iter_mut(&mut self) -> impl ParallelIterator<Item = &mut T> where T : Send + Sync{
        self._data.par_iter_mut()
    }

    /// Returns a read-only slice of the memory map data.
    pub fn get_data_as_slice(&self) -> &[T] {
        self._data
    }

    /// Returns a mutable slice of the memory map data.
    pub fn get_data_as_slice_mut(&mut self) -> &mut [T] {
        self._data
    }

    /// Convenience method for filling the memory map with a custom function
    /// Example:
    /// ```
    /// let mut mmap = easy_mmap::EasyMmapBuilder::new()
    ///                            .readable()
    ///                            .writable()
    ///                            .capacity(5)
    ///                            .build();
    ///
    /// mmap.fill(|i| i as u32);
    /// assert_eq!(mmap.get_data_as_slice(), &[0, 1, 2, 3, 4]);
    /// ```
    pub fn fill(&mut self, f: impl Fn(usize) -> T) {
        for (i, v) in self._data.iter_mut().enumerate() {
            *v = f(i);
        }
    }
}

/// The structure can be indexed similarly to an array.
/// Example:
/// ```
/// let mut mmap = easy_mmap::EasyMmapBuilder::new()
///                     .options(&[
///                         mmap::MapOption::MapWritable,
///                         mmap::MapOption::MapReadable,
///                     ])
///                     .capacity(10)
///                     .build();
/// mmap[0] = 1;
/// println!("{}", mmap[0]);
/// ```
impl<'a, T> Index<usize> for EasyMmap<'a, T>
where
    T: Copy,
{
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        if index >= self.len() {
            panic!(
                "Index {} is out of bounds for type {}",
                index,
                std::any::type_name::<T>(),
            );
        };
        &self._data[index]
    }
}

/// The structure can be indexed an array or slice.
/// See the `Index` trait for an example.
impl<'a, T> IndexMut<usize> for EasyMmap<'a, T>
where
    T: Copy,
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        if index >= self.len() {
            panic!(
                "Index {} is out of bounds for type {}",
                index,
                std::any::type_name::<T>(),
            )
        }
        &mut self._data[index]
    }
}

/// The builder class for the EasyMmap struct.
/// Provides an easy-to-use interface to create a new EasyMmap struct.
pub struct EasyMmapBuilder<T> {
    file: Option<fs::File>,
    capacity: usize,
    options: Vec<MapOption>,
    _type: PhantomData<T>,
}

impl<'a, T> EasyMmapBuilder<T> {
    /// Creates a new EasyMmapBuilder struct.
    pub fn new() -> EasyMmapBuilder<T> {
        EasyMmapBuilder {
            file: None,
            capacity: 0,
            options: Vec::new(),
            _type: PhantomData,
        }
    }

    /// Builds the memory map with the given specifications.
    /// If the file has been specified, its size will be set to the requirements of the map.
    pub fn build(mut self) -> EasyMmap<'a, T>
    where
        T: Copy,
    {
        if self.file.is_some() {
            let file = self.file.unwrap();
            // allocate enough size in the file
            file.set_len((self.capacity * std::mem::size_of::<T>()) as u64)
                .unwrap();

            // Get file descriptor of file
            self.options.push(MapOption::MapFd(file.as_raw_fd()));
            self.options // To make the code share the file in memory
                .push(MapOption::MapNonStandardFlags(libc::MAP_SHARED));

            self.file = Some(file);
        }

        EasyMmap::new(self.capacity, &self.options, self.file)
    }

    /// Passes the ownership of the file to the memory map.
    pub fn file(mut self, file: fs::File) -> EasyMmapBuilder<T> {
        self.file = Some(file);
        self
    }

    /// Sets the capacity that the mapped region must have.
    /// This capacity must be the number of objects of type `T` that can be stored in the memory map.
    pub fn capacity(mut self, capacity: usize) -> EasyMmapBuilder<T> {
        self.capacity = capacity;
        self
    }

    /// Batch sets the options that the mapped region must have.
    pub fn options(mut self, options: &[MapOption]) -> EasyMmapBuilder<T> {
        self.options = options.to_vec();
        self
    }

    /// Adds an individual option.
    pub fn add_option(mut self, option: MapOption) -> EasyMmapBuilder<T> {
        self.options.push(option);
        self
    }

    pub fn readable(mut self) -> EasyMmapBuilder<T> {
        self.options.push(MapOption::MapReadable);
        self
    }

    pub fn writable(mut self) -> EasyMmapBuilder<T> {
        self.options.push(MapOption::MapWritable);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_random_file() -> fs::File {
        fs::OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .open(format!("/tmp/map{}", rand::random::<u64>()))
            .unwrap()
    }

    #[test]
    fn map_create() {
        let map = &mut EasyMmapBuilder::<u32>::new()
            .capacity(10)
            .options(&[])
            .build();

        assert_eq!(map.len(), 10);
    }

    #[test]
    fn map_write_read() {
        let map = &mut EasyMmapBuilder::<u32>::new()
            .capacity(1)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map[0] = 1;

        assert_eq!(map[0], 1);
    }

    #[test]
    fn map_iter() {
        let map = &mut EasyMmapBuilder::<u32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        for i in 0..5 {
            map[i] = i as u32;
        }

        assert_eq!(
            map.iter().map(|x| *x).collect::<Vec<_>>(),
            vec![0, 1, 2, 3, 4]
        );
    }

    #[test]
    #[should_panic]
    fn map_oob_write() {
        let map = &mut EasyMmapBuilder::<u32>::new()
            .capacity(1)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map[1] = 1;
    }

    #[test]
    #[should_panic]
    fn map_oob_read() {
        let map = &mut EasyMmapBuilder::<u32>::new()
            .capacity(1)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map[1];
    }

    #[test]
    fn map_create_file() {
        let file = create_random_file();

        let map = &mut EasyMmapBuilder::<u32>::new()
            .file(file)
            .capacity(10)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        assert_eq!(map.len(), 10);

        // Write to file
        map[0] = 1;
        assert_eq!(map[0], 1);
    }

    #[test]
    fn test_large_size() {
        let map = &mut EasyMmapBuilder::new()
            .capacity(65535)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        // Populate map
        for i in 0..65535 {
            map[i] = i as u64;
        }

        // Check if map is populated
        for i in 0..65535 {
            assert_eq!(map[i], i as u64);
        }
    }

    #[test]
    fn test_struct() {
        #[derive(Clone, Copy)]
        struct TestStruct {
            v1: i64,
            v2: bool,
        }

        let length = 100000;

        let file = create_random_file();

        let map = &mut EasyMmapBuilder::new()
            .capacity(length)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .file(file)
            .build();

        for i in 0..length {
            map[i] = TestStruct {
                v1: i as i64,
                v2: i % 2 == 0,
            };
        }

        for i in 0..length {
            let s = map[i];
            assert_eq!(s.v1, i as i64);
            assert_eq!(s.v2, i % 2 == 0);
        }
    }

    #[test]
    fn test_iter() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        for i in 0..5 {
            map[i] = i as i32;
        }

        for (i, x) in map.iter().enumerate() {
            assert_eq!(i as i32, *x);
        }
    }

    #[test]
    fn test_iter_mut() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        for (i, x) in map.iter_mut().enumerate() {
            *x = i as i32;
        }

        for (i, x) in map.iter().enumerate() {
            assert_eq!(i as i32, *x);
        }
    }

    #[test]
    fn test_complex_iterator() {
        let mut map = EasyMmapBuilder::<u32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map.iter_mut()
            .enumerate()
            .for_each(|(idx, x)| *x = idx as u32);

        let v = map
            .iter()
            .map(|x| *x * 3)
            .filter(|x| x % 2 == 0)
            .collect::<Vec<u32>>();

        map.iter_mut().zip(v).for_each(|(x, y)| *x = y);

        assert_eq!(
            map.iter().map(|x| *x).collect::<Vec<_>>(),
            vec![0, 6, 12, 3, 4]
        );
    }

    #[test]
    fn get_data_slice() {
        let mut map = EasyMmapBuilder::<u32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map.iter_mut()
            .enumerate()
            .for_each(|(idx, x)| *x = idx as u32);

        let slice = map.get_data_as_slice();

        assert_eq!(slice.len(), 5);
        assert_eq!(slice[0], map[0]);
        assert_eq!(slice[1], map[1]);
        assert_eq!(slice[2], map[2]);
        assert_eq!(slice[3], map[3]);
        assert_eq!(slice[4], map[4]);

        let slice = map.get_data_as_slice_mut();
        assert_eq!(slice.len(), 5);
        slice[0] = 10;

        assert_eq!(map[0], 10);
    }

    #[test]
    fn easier_builder() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(1)
            .readable()
            .writable()
            .build();

        map[0] = 1;
        assert_eq!(map[0], 1);
    }

    #[test]
    fn fill_constant() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(5)
            .readable()
            .writable()
            .build();

        map.fill(|_| 1);
        assert_eq!(map.get_data_as_slice(), vec![1, 1, 1, 1, 1]);
    }

    #[test]
    fn fill_large() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(100000)
            .readable()
            .writable()
            .build();

        map.fill(|i| i as i32);
        assert_eq!(map.get_data_as_slice(), (0..100000).collect::<Vec<_>>());
    }

    #[test]
    fn open_written_file() {
        let values = vec![1, 2, 3, 4, 5, 10, 20, 50];

        // Write to random file
        let filename = format!("/tmp/file{}", rand::random::<i32>());
        fs::write(&filename, &values).expect("Failed to write values to file");

        let file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(false)
            .open(&filename)
            .expect("Failed to open file");

        // Now read the contents into the mmap
        let map = EasyMmapBuilder::<u8>::new()
            .capacity(values.len())
            .writable()
            .readable()
            .file(file)
            .build();

        assert_eq!(map.get_data_as_slice(), values);
    }

    #[test]
    fn parallel_iterators() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map.fill(|i| i as i32);

        assert_eq!(
            map.par_iter().map(|x| *x).collect::<Vec<_>>(),
            (0..5).collect::<Vec<_>>()
        );
    }

    #[test]
    fn parallel_iterators_mut() {
        let mut map = EasyMmapBuilder::<i32>::new()
            .capacity(5)
            .options(&[MapOption::MapReadable, MapOption::MapWritable])
            .build();

        map.fill(|i| i as i32);

        map.par_iter_mut().for_each(|x| *x += 1);

        assert_eq!(
            map.par_iter().map(|x| *x).collect::<Vec<_>>(),
            (1..6).collect::<Vec<_>>()
        );
    }
}