memmap3 0.1.0

Safe, zero-copy memory-mapped I/O. Drop-in replacement for memmap2 with persistent structs and zero unsafe in user code.
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
# memmap3

[![Crates.io](https://img.shields.io/crates/v/memmap3.svg)](https://crates.io/crates/memmap3)
[![docs.rs](https://docs.rs/memmap3/badge.svg)](https://docs.rs/memmap3)

Safe memory-mapped I/O with zero-copy persistent data structures.

**memmap3** is a complete drop-in replacement for [memmap2](https://docs.rs/memmap2) that adds a
huge additional list of 'safe' features. All memmap2 functionality is available, plus powerful new
APIs that eliminate unsafe code while providing automatic persistence.

## 🎯 Core Features Summary

- **🔄 Auto-Persistence**: Changes persist automatically via memory mapping
- **🔒 Zero Unsafe**: Safe Rust APIs for all operations
- **⚡ Thread-Safe**: Atomic fields work across processes
- **🎭 Convenience Operators**: `<<` for intuitive data manipulation
- **📏 Fixed-Size + Unlimited**: Fixed layouts + segmented growth when needed
- **🧩 Rich Type System**: Primitives, atomics, strings, collections, nested structs
- **📊 Multidimensional**: N-dimensional arrays for join-like operations
- **🔌 Drop-in Compatible**: All memmap2 code works unchanged

## Quick Start

Add to your `Cargo.toml`:

```toml
[dependencies]
memmap3 = "0.1"
```

Create persistent data structures:

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct Counter {
    #[mmap(atomic)]
    value: u64,
    name: [u8; 32],
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create persistent data
    let mut counter = MmapStruct::<Counter>::create("/tmp/counter.mmap")?;
    &mut counter.name << "my_counter";
    
    // Atomic operations work across processes
    let old_value = counter.value.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    println!("Counter: {} -> {}", old_value, old_value + 1);
    
    Ok(())
}
```

## Key Features

### 🔒 Safe API

- **Zero unsafe code** required in user applications
- **Compile-time validation** through `#[mmap_struct]` macro
- **Runtime bounds checking** for all operations
- **UTF-8 validation** for string operations

### ⚡ High Performance

- **Zero-copy access** to persistent data
- **OS-level caching** through memory mapping
- **Atomic operations** for thread-safe access
- **Minimal overhead** with direct memory access

### 🧩 Drop-in Compatibility

```rust
// Just change your import:
use memmap2::{Mmap, MmapOptions};  // From this
use memmap3::{Mmap, MmapOptions};  // To this
// All existing memmap2 code works unchanged!
```

## 🔧 The #[mmap_struct] Macro

Transform regular Rust structs into persistent, memory-mapped types:

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct MyData {
    // Regular fields (primitives, enums)
    id: u64,
    active: bool,
    
    // Atomic fields (thread-safe across processes)
    #[mmap(atomic)]
    counter: u64,
    
    // Auto-detected strings (default for [u8; N])
    name: [u8; 32],
    
    // Explicit raw binary data
    #[mmap(raw)]
    key: [u8; 32],
    
    // Fixed-capacity vectors  
    #[mmap(vec)]
    scores: [u32; 10],
    
    // String arrays
    #[mmap(string_array)]
    tags: [[u8; 16]; 5],
    
    // Unlimited growth storage
    #[mmap(segmented)]
    events: [u64; 0],
}
```

## 🎭 Convenience Operators

Smooth, intuitive syntax for common operations:

```rust
// String assignment
&mut my_string << "Hello";

// Vector append  
&mut my_vec << item;

// HashMap insertion
&mut my_map << ("key", "value");

// HashMap key assignment using macro
hashmap_index!(my_map["key"] << "value");

// Segmented append
&mut my_segmented << item;
```

## 📊 Complete Type System

### Primitive Types (Native Support)

- **Integers**: u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, usize, isize
- **Floats**: f32, f64
- **Bool**: bool
- **Char**: char (stored as u32)
- **C-style Enums**: Any enum with `#[repr(C)]`

### Atomic Types (`#[mmap(atomic)]`)

Transform any primitive to thread-safe atomic:

- `u64``MmapAtomicU64` (fetch_add, compare_exchange, etc.)
- `bool``MmapAtomicBool` (load, store, etc.)
- Plus all integer types + usize/isize

### String Types

- **Auto-detected**: `[u8; N]``MmapString<N>` (default behavior)
- **Explicit**: `#[mmap(string)]` to force string behavior
- **Raw binary**: `#[mmap(raw)]` to keep as byte array

### Collection Types

- **Vectors**: `#[mmap(vec)]` transforms `[T; N]``MmapVec<T, N>`
- **String Arrays**: `#[mmap(string_array)]` transforms `[[u8; LEN]; N]``MmapStringArray<N, LEN>`
- **Hash Maps**: `MmapHashMap<K, V>` for key-value storage

### Advanced Types

- **Segmented**: `#[mmap(segmented)]` for unlimited growth (breaks fixed-size constraint)
- **Nested Structs**: Full support for complex nested structures
- **Multidimensional Arrays**: `[[[u8; X]; Y]; Z]` for N-dimensional data
- **Serde Integration**: Store any `Serialize/Deserialize` type

## 🔗 Multidimensional & Join-like Operations

Create sophisticated data structures for complex queries:

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct BitIndex {
    // 3D lookup table for fast joins
    index: [[[u8; 256]; 256]; 256],
    
    // User data indexed by multiple dimensions  
    users_by_age_location: [[u64; 100]; 50], // [age][location] → user_id
    
    // Unlimited growth using segmented
    #[mmap(segmented)]
    overflow_data: [u64; 0],
}
```

## 🏗️ Fixed-Size Constraint + Segmented Growth

- **Most types**: Fixed size at compile time for predictable layout
- **Exception**: `#[mmap(segmented)]` allows unlimited growth
- **Benefit**: Known memory layout enables direct pointer arithmetic

## ⚙️ How Auto-Persistence Works

1. **Memory Mapping**: File mapped into process memory
2. **Direct Access**: Struct fields map directly to file bytes
3. **OS Sync**: Operating system handles sync to disk
4. **Cross-Process**: Multiple processes can share same file safely

## Core Types

### MmapStruct<T>

Safe wrapper for memory-mapped structs with automatic file management:

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct GameState {
    level: u32,
    score: u64,
    player_name: [u8; 32],
}

let mut game = MmapStruct::<GameState>::create("game.mmap")?;
game.level = 5;
game.score = 12345;
&mut game.player_name << "Player1";
```

### Atomic Fields

Thread-safe operations across processes:

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct Metrics {
    #[mmap(atomic)]
    requests: u64,
    #[mmap(atomic)]
    errors: u64,
}

let metrics = MmapStruct::<Metrics>::create("metrics.mmap")?;
metrics.requests.fetch_add(1, Ordering::SeqCst);
```

### Collections

Persistent data structures with dynamic sizing:

```rust
use memmap3::prelude::*;

// Persistent hash map
let mut cache = MmapHashMap::<&str, &str>::create("cache.mmap")?;
cache.insert("key1", "value1")?;

// Multiple assignment syntaxes available:
&mut cache << ("key2", "value2");           // Tuple insertion
hashmap_index!(cache["key3"] << "value3");  // Index-style assignment
cache.set("key4", "value4")?;               // Direct set method

// Persistent vector
let mut log = MmapVec::<u64, 1000>::new();
log.push(1234567890); // timestamp

// Persistent string
let mut name = MmapString::<64>::new();
&mut name << "Alice";
```

## Supported Types

### Primitive Types (no attribute needed)

- **Integers**: u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, usize, isize
- **Floats**: f32, f64
- **Bool**: bool
- **Char**: char (stored as u32)
- **C-style Enums**: Any enum with `#[repr(C)]`

### Transformed Types (via attributes)

#### Atomic Types (`#[mmap(atomic)]`)

Transforms regular types to atomic equivalents for thread-safe access:

- `u8``MmapAtomicU8`, `u16``MmapAtomicU16`, etc.
- `bool``MmapAtomicBool`

#### Strings (`#[mmap(string)]`)

Transforms byte arrays to UTF-8 strings with helper methods:

- `[u8; N]``MmapString<N>`
- Provides `.set()`, `<<` operator, `.as_str()`, `.clear()`

#### Vectors (`#[mmap(vec)]`)

Transforms arrays to fixed-capacity vectors:

- `[T; N]``MmapVec<T, N>`
- Provides `.push()`, `.pop()`, `.len()`, `.iter()`, indexing

#### String Arrays (`#[mmap(string_array)]`)

Transforms 2D byte arrays to arrays of strings:

- `[[u8; LEN]; N]``MmapStringArray<N, LEN>`
- Provides indexed access to multiple strings

## Running Examples

See the `examples/` directory for complete working examples:

```bash
cargo run --example 01-002_macro_usage
cargo run --example 03-001_atomic_operations  
cargo run --example 02-002_string_operations
cargo run --example 04-003_event_log
cargo run --example 14_hashmap
```

## Examples

### Simple Configuration Storage

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct Config {
    max_connections: u32,
    timeout_ms: u32,
    debug_mode: bool,
    server_name: [u8; 64],
}

let mut config = MmapStruct::<Config>::create("app.config")?;
config.max_connections = 1000;
config.timeout_ms = 5000;
&mut config.server_name << "production-server";
// Configuration persists across application restarts
```

### Inter-Process Communication

```rust
use memmap3::prelude::*;
use std::sync::atomic::Ordering;

#[mmap_struct]
struct SharedData {
    #[mmap(atomic)]
    message_count: u64,
    #[mmap(atomic)]
    worker_status: u32,
    shared_buffer: [u8; 1024],
}

// Process A
let shared = MmapStruct::<SharedData>::create("/tmp/ipc.mmap")?;
shared.message_count.store(42, Ordering::SeqCst);

// Process B can read the same data
let shared = MmapStruct::<SharedData>::open("/tmp/ipc.mmap")?;
let count = shared.message_count.load(Ordering::SeqCst);
println!("Messages: {}", count); // Prints: Messages: 42
```

### Persistent Analytics

```rust
use memmap3::prelude::*;
use std::sync::atomic::Ordering;

#[mmap_struct]
struct Analytics {
    #[mmap(atomic)]
    page_views: u64,
    #[mmap(atomic)]
    unique_visitors: u64,
    #[mmap(atomic)]
    conversion_rate: u64, // Fixed-point arithmetic
}

let analytics = MmapStruct::<Analytics>::create("analytics.mmap")?;

// Record events
analytics.page_views.fetch_add(1, Ordering::SeqCst);
analytics.unique_visitors.fetch_add(1, Ordering::SeqCst);

// Calculate conversion rate (example: 2.5% as 250 basis points)
let rate = (conversions * 10000) / page_views;
analytics.conversion_rate.store(rate, Ordering::SeqCst);
```

## How It Works

The `#[mmap_struct]` attribute macro:

1. Automatically adds `#[repr(C)]` for predictable memory layout
2. Transforms annotated fields to thread-safe types
3. Generates trait implementations for memory mapping
4. Handles file creation, opening, and validation

## Thread Safety

- **Regular fields**: Single writer, multiple readers (protected by OS page cache)
- **Atomic fields**: Multiple concurrent writers and readers
- **String fields**: Single writer with UTF-8 validation

### Using with Arc for Shared Access

You can wrap `MmapStruct` in `Arc` for safe sharing across threads:

```rust
use memmap3::prelude::*;
use std::sync::Arc;
use std::sync::atomic::Ordering;

#[mmap_struct]
struct Config {
    port: u16,
    #[mmap(atomic)]
    counter: u64,
}

// Single-threaded use
let mut data = MmapStruct::<Config>::create("config.mmap")?;
data.port = 8080;  // Can modify all fields

// Multi-threaded use with Arc
let shared = Arc::new(MmapStruct::<Config>::create("config.mmap")?);

// Clone for each thread
let thread_data = shared.clone();
std::thread::spawn(move || {
    // Atomic fields can be modified safely
    thread_data.counter.fetch_add(1, Ordering::Relaxed);
    
    // Regular fields are read-only when shared via Arc
    println!("Port: {}", thread_data.port);
});
```

**Access Patterns:**

- **No Arc**: Full read/write access to all fields (single-threaded)
- **With Arc**: Atomic fields writable, regular fields read-only (multi-threaded)
- **With Arc<Mutex<...>>**: If you need to modify regular fields from multiple threads

## String Handling

Automatic string operations for byte arrays:

```rust
use memmap3::prelude::*;

#[mmap_struct]
struct User {
    id: u64,
    name: [u8; 32],    // Automatically treated as string
    email: [u8; 128],  // Automatically treated as string
}

let mut user = MmapStruct::<User>::create("user.mmap")?;
user.id = 12345;

// Write strings using << operator
&mut user.name << "Alice Smith";
&mut user.email << "alice@example.com";

// Read strings back
println!("User: {} ({})", user.name.as_str(), user.email.as_str());
```

## Feature Flags

Enable additional functionality:

```toml
[dependencies]
memmap3 = { version = "0.1", features = ["serde"] }
```

- `serde` - Serialize/deserialize support for complex types

## Documentation

- **[API Reference]https://docs.rs/memmap3** - Complete API documentation
- **[Cookbook Examples]cookbooks/** - Real-world usage patterns
- **[Migration Guide]https://github.com/deepbrainspace/memmap3#migration-from-memmap2** -
  Upgrading from memmap2

## Use Cases

- **Inter-process communication** - Shared configuration and state
- **Event logging** - High-performance ring buffers
- **ML model weights** - Instant loading of large models
- **Game save states** - Fast persistence and loading
- **Database indexes** - Memory-mapped B-trees

## Performance

memmap3 provides zero-copy access with minimal overhead:

- **Direct memory access** - No serialization/deserialization
- **OS page cache integration** - Automatic memory management
- **Lazy loading** - Only accessed pages are loaded
- **Cross-process sharing** - Efficient memory usage

## Safety Guarantees

Multiple layers of safety validation:

1. **Compile-time validation** - `#[mmap_struct]` macro checks
2. **Runtime bounds checking** - All array/collection access
3. **Memory layout verification** - Struct compatibility validation
4. **UTF-8 validation** - String operation safety
5. **Atomic operation safety** - Cross-process synchronization

## License

This project is licensed under the MIT OR Apache-2.0 license.

## Contributing

Contributions are welcome! Please see our
[GitHub repository](https://github.com/deepbrainspace/memmap3) for guidelines.