rsmarisa 0.4.0

Pure Rust port of marisa-trie: a static and space-efficient trie data structure
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
//! Memory-mapped file access.
//!
//! Ported from:
//! - lib/marisa/grimoire/io/mapper.h
//! - lib/marisa/grimoire/io/mapper.cc
//!
//! Mapper provides read-only access to data through memory mapping.
//! This implementation supports both file-backed memory mapping and borrowed memory.

use memmap2::Mmap;
use std::fs::File;
use std::io;

/// Mapper for memory-mapped data access.
///
/// Mapper provides read-only access to data, primarily used for
/// deserializing trie structures from memory or files.
///
/// The mapper can work in two modes:
/// - File-backed memory mapping using `memmap2::Mmap`
/// - Borrowed memory slices (for testing or in-memory data)
pub struct Mapper {
    /// File-backed memory map.
    mmap: Option<Mmap>,
    /// Borrowed memory reference (static lifetime for safety).
    borrowed: Option<&'static [u8]>,
    /// Current read position.
    position: usize,
}

impl Default for Mapper {
    fn default() -> Self {
        Self::new()
    }
}

impl Mapper {
    /// Creates a new empty mapper.
    pub fn new() -> Self {
        Mapper {
            mmap: None,
            borrowed: None,
            position: 0,
        }
    }

    /// Opens a mapper from a file using memory mapping.
    ///
    /// # Arguments
    ///
    /// * `filename` - Path to the file to map
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened or mapped.
    ///
    /// # Safety
    ///
    /// This function uses memory mapping which is inherently unsafe because:
    /// - The file could be modified externally while mapped
    /// - The file could be truncated while mapped
    ///
    /// The caller must ensure that the file is not modified during the lifetime
    /// of the Mapper. Files should be opened read-only.
    pub fn open_file(filename: &str) -> io::Result<Self> {
        let file = File::open(filename)?;
        let mmap = unsafe { Mmap::map(&file)? };
        Ok(Mapper {
            mmap: Some(mmap),
            borrowed: None,
            position: 0,
        })
    }

    /// Opens a mapper from a byte slice.
    ///
    /// # Arguments
    ///
    /// * `data` - Byte slice to map (must have static lifetime)
    ///
    /// # Safety
    ///
    /// The data must have a valid static lifetime to ensure it outlives
    /// the mapper and any structures that reference it.
    pub fn open_memory(data: &'static [u8]) -> Self {
        Mapper {
            mmap: None,
            borrowed: Some(data),
            position: 0,
        }
    }

    /// Opens a mapper from a byte slice (legacy method).
    ///
    /// # Arguments
    ///
    /// * `data` - Byte slice to map (must have static lifetime)
    ///
    /// # Note
    ///
    /// This method is provided for compatibility. New code should use
    /// `open_memory()` instead.
    pub fn open(data: &'static [u8]) -> Self {
        Self::open_memory(data)
    }

    /// Returns a reference to the underlying data.
    ///
    /// Returns the data from either the memory map or borrowed slice.
    fn data(&self) -> &[u8] {
        self.mmap
            .as_ref()
            .map(|m| &m[..])
            .or(self.borrowed)
            .unwrap_or(&[])
    }

    /// Maps a single value of type T from the current position.
    ///
    /// # Arguments
    ///
    /// * `value` - Mutable reference to store the mapped value
    ///
    /// # Errors
    ///
    /// Returns an error if the mapper is not open or if there's insufficient data.
    ///
    /// # Safety
    ///
    /// This function reads raw bytes into the memory representation of T.
    /// The caller must ensure T is safe to initialize from arbitrary bytes.
    pub fn map<T: Copy>(&mut self, value: &mut T) -> io::Result<()> {
        let data = self.data();
        if data.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "Mapper not open",
            ));
        }

        let size = std::mem::size_of::<T>();
        if self.position + size > data.len() {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Insufficient data to map",
            ));
        }

        let slice = &data[self.position..self.position + size];
        unsafe {
            std::ptr::copy_nonoverlapping(slice.as_ptr(), value as *mut T as *mut u8, size);
        }

        self.position += size;
        Ok(())
    }

    /// Maps and returns a single value of type T from the current position.
    ///
    /// Convenience method that returns the value instead of taking a mutable reference.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapper is not open or if there's insufficient data.
    ///
    /// # Safety
    ///
    /// This function reads raw bytes into the memory representation of T.
    /// The caller must ensure T is safe to initialize from arbitrary bytes.
    pub fn map_value<T: Copy + Default>(&mut self) -> io::Result<T> {
        let mut value = T::default();
        self.map(&mut value)?;
        Ok(value)
    }

    /// Maps a slice of values from the current position.
    ///
    /// # Arguments
    ///
    /// * `values` - Mutable slice to fill with mapped values
    ///
    /// # Errors
    ///
    /// Returns an error if the mapper is not open or if there's insufficient data.
    ///
    /// # Safety
    ///
    /// This function reads raw bytes into the memory representation of `T`.
    /// The caller must ensure T is safe to initialize from arbitrary bytes.
    pub fn map_slice<T: Copy>(&mut self, values: &mut [T]) -> io::Result<()> {
        if values.is_empty() {
            return Ok(());
        }

        let data = self.data();
        if data.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "Mapper not open",
            ));
        }

        let size = std::mem::size_of_val(values);
        if self.position + size > data.len() {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Insufficient data to map",
            ));
        }

        let slice = &data[self.position..self.position + size];
        unsafe {
            std::ptr::copy_nonoverlapping(slice.as_ptr(), values.as_mut_ptr() as *mut u8, size);
        }

        self.position += size;
        Ok(())
    }

    /// Seeks forward by the specified number of bytes.
    ///
    /// # Arguments
    ///
    /// * `size` - Number of bytes to skip
    ///
    /// # Errors
    ///
    /// Returns an error if the mapper is not open or if seeking past the end.
    pub fn seek(&mut self, size: usize) -> io::Result<()> {
        let data = self.data();
        if data.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "Mapper not open",
            ));
        }

        if self.position + size > data.len() {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Seek past end of data",
            ));
        }

        self.position += size;
        Ok(())
    }

    /// Checks if the mapper is open.
    pub fn is_open(&self) -> bool {
        self.mmap.is_some() || self.borrowed.is_some()
    }

    /// Returns the current position.
    pub fn position(&self) -> usize {
        self.position
    }

    /// Returns the total size of mapped data.
    pub fn size(&self) -> usize {
        self.data().len()
    }

    /// Closes the mapper.
    pub fn clear(&mut self) {
        self.mmap = None;
        self.borrowed = None;
        self.position = 0;
    }

    /// Swaps with another mapper.
    pub fn swap(&mut self, other: &mut Mapper) {
        std::mem::swap(&mut self.mmap, &mut other.mmap);
        std::mem::swap(&mut self.borrowed, &mut other.borrowed);
        std::mem::swap(&mut self.position, &mut other.position);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_mapper_new() {
        let mapper = Mapper::new();
        assert!(!mapper.is_open());
        assert_eq!(mapper.position(), 0);
    }

    #[test]
    fn test_mapper_open_memory() {
        static DATA: [u8; 5] = [1, 2, 3, 4, 5];
        let mapper = Mapper::open_memory(&DATA);
        assert!(mapper.is_open());
        assert_eq!(mapper.size(), 5);
        assert_eq!(mapper.position(), 0);
    }

    #[test]
    fn test_mapper_open_file() {
        // Create a temporary file
        let mut temp_file = NamedTempFile::new().unwrap();
        let test_data = vec![1u8, 2, 3, 4, 5];
        temp_file.write_all(&test_data).unwrap();
        temp_file.flush().unwrap();

        let path = temp_file.path().to_str().unwrap();
        let mapper = Mapper::open_file(path).unwrap();

        assert!(mapper.is_open());
        assert_eq!(mapper.size(), 5);
        assert_eq!(mapper.position(), 0);
    }

    #[test]
    fn test_mapper_open_file_not_found() {
        let result = Mapper::open_file("/nonexistent/file.dat");
        assert!(result.is_err());
    }

    #[test]
    fn test_mapper_map_u32() {
        static DATA: [u8; 4] = [0x01, 0x02, 0x03, 0x04];
        let mut mapper = Mapper::open_memory(&DATA);

        let mut value: u32 = 0;
        mapper.map(&mut value).unwrap();

        // Little-endian: 0x04030201
        assert_eq!(value, 0x04030201);
        assert_eq!(mapper.position(), 4);
    }

    #[test]
    fn test_mapper_map_value() {
        static DATA: [u8; 4] = [0x01, 0x02, 0x03, 0x04];
        let mut mapper = Mapper::open_memory(&DATA);

        let value: u32 = mapper.map_value().unwrap();

        // Little-endian: 0x04030201
        assert_eq!(value, 0x04030201);
        assert_eq!(mapper.position(), 4);
    }

    #[test]
    fn test_mapper_map_slice() {
        static DATA: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
        let mut mapper = Mapper::open_memory(&DATA);

        let mut values = [0u8; 4];
        mapper.map_slice(&mut values).unwrap();

        assert_eq!(values, [1, 2, 3, 4]);
        assert_eq!(mapper.position(), 4);

        // Map next 4 bytes
        mapper.map_slice(&mut values).unwrap();
        assert_eq!(values, [5, 6, 7, 8]);
        assert_eq!(mapper.position(), 8);
    }

    #[test]
    fn test_mapper_map_empty_slice() {
        static DATA: [u8; 4] = [1, 2, 3, 4];
        let mut mapper = Mapper::open_memory(&DATA);

        let mut values: [u8; 0] = [];
        mapper.map_slice(&mut values).unwrap();

        assert_eq!(mapper.position(), 0);
    }

    #[test]
    fn test_mapper_seek() {
        static DATA: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
        let mut mapper = Mapper::open_memory(&DATA);

        mapper.seek(4).unwrap();
        assert_eq!(mapper.position(), 4);

        let mut value: u8 = 0;
        mapper.map(&mut value).unwrap();
        assert_eq!(value, 5);
    }

    #[test]
    fn test_mapper_seek_zero() {
        static DATA: [u8; 4] = [1, 2, 3, 4];
        let mut mapper = Mapper::open_memory(&DATA);

        mapper.seek(0).unwrap();
        assert_eq!(mapper.position(), 0);
    }

    #[test]
    fn test_mapper_clear() {
        static DATA: [u8; 4] = [1, 2, 3, 4];
        let mut mapper = Mapper::open_memory(&DATA);

        assert!(mapper.is_open());
        mapper.clear();
        assert!(!mapper.is_open());
        assert_eq!(mapper.position(), 0);
    }

    #[test]
    fn test_mapper_swap() {
        static DATA1: [u8; 3] = [1, 2, 3];
        static DATA2: [u8; 5] = [4, 5, 6, 7, 8];

        let mut mapper1 = Mapper::open_memory(&DATA1);
        let mut mapper2 = Mapper::open_memory(&DATA2);

        mapper1.seek(1).unwrap();
        mapper2.seek(2).unwrap();

        assert_eq!(mapper1.size(), 3);
        assert_eq!(mapper2.size(), 5);
        assert_eq!(mapper1.position(), 1);
        assert_eq!(mapper2.position(), 2);

        mapper1.swap(&mut mapper2);

        assert_eq!(mapper1.size(), 5);
        assert_eq!(mapper2.size(), 3);
        assert_eq!(mapper1.position(), 2);
        assert_eq!(mapper2.position(), 1);
    }

    #[test]
    fn test_mapper_not_open() {
        let mut mapper = Mapper::new();
        let mut value: u32 = 0;

        let result = mapper.map(&mut value);
        assert!(result.is_err());
    }

    #[test]
    fn test_mapper_insufficient_data() {
        static DATA: [u8; 2] = [1, 2];
        let mut mapper = Mapper::open_memory(&DATA);

        let mut value: u32 = 0;
        let result = mapper.map(&mut value);
        assert!(result.is_err());
    }

    #[test]
    fn test_mapper_seek_past_end() {
        static DATA: [u8; 4] = [1, 2, 3, 4];
        let mut mapper = Mapper::open_memory(&DATA);

        let result = mapper.seek(10);
        assert!(result.is_err());
    }

    #[test]
    fn test_mapper_multiple_maps() {
        // Create static data with u32 and u64 values
        static DATA: [u8; 12] = [
            42, 0, 0, 0, // 42 as u32 (little-endian)
            100, 0, 0, 0, 0, 0, 0, 0, // 100 as u64 (little-endian)
        ];

        let mut mapper = Mapper::open_memory(&DATA);

        let mut val_u32: u32 = 0;
        mapper.map(&mut val_u32).unwrap();
        assert_eq!(val_u32, 42);

        let mut val_u64: u64 = 0;
        mapper.map(&mut val_u64).unwrap();
        assert_eq!(val_u64, 100);
    }

    #[test]
    fn test_mapper_default() {
        let mapper = Mapper::default();
        assert!(!mapper.is_open());
    }

    #[test]
    fn test_mapper_file_mapping() {
        // Create a temporary file with some data
        let mut temp_file = NamedTempFile::new().unwrap();
        let test_data = vec![0x01u8, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
        temp_file.write_all(&test_data).unwrap();
        temp_file.flush().unwrap();

        let path = temp_file.path().to_str().unwrap();
        let mut mapper = Mapper::open_file(path).unwrap();

        // Test reading from file-backed mmap
        let mut values = [0u8; 4];
        mapper.map_slice(&mut values).unwrap();
        assert_eq!(values, [1, 2, 3, 4]);

        mapper.map_slice(&mut values).unwrap();
        assert_eq!(values, [5, 6, 7, 8]);
    }
}