deferred-map 0.4.0

High-performance generational arena using handle-based deferred insertion with O(1) operations
Documentation
# deferred-map

[![Crates.io](https://img.shields.io/crates/v/deferred-map.svg)](https://crates.io/crates/deferred-map)
[![Documentation](https://docs.rs/deferred-map/badge.svg)](https://docs.rs/deferred-map)
[![License](https://img.shields.io/crates/l/deferred-map.svg)](https://github.com/shaogme/deferred-map#license)

[English]README.md | [中文]README_CN.md

A high-performance generational arena (slotmap) with **handle-based deferred insertion** for Rust.

## Features

- **O(1) Operations**: Constant-time insertion, lookup, and removal
- **Memory Safety**: Generational indices prevent use-after-free bugs
- **Deferred Insertion**: Separate handle allocation from value insertion
- **Memory Efficient**: Union-based slot storage optimizes memory usage
- **Type Safe**: Handles cannot be cloned, ensuring single-use semantics
- **Zero-Copy**: Direct access to stored values without copying

## Why Deferred Insertion?

Traditional slot maps require you to have the value ready when allocating space. `DeferredMap` separates these concerns:

1. **Allocate Handle** - Reserve a slot and get a handle (cheap, no value needed)
2. **Insert Value** - Later, use the handle to insert the actual value

This is particularly useful when:
- Building complex data structures with circular references
- Need to know the key before constructing the value
- Want to reserve capacity before expensive computation
- Coordinating multi-step initialization processes

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
deferred-map = "0.4"
```

## Quick Start

```rust
use deferred_map::DeferredMap;

fn main() {
    let mut map = DeferredMap::new();
    
    // Step 1: Allocate a handle (reserves a slot)
    let handle = map.alloc();
    
    // Step 2: Get the key before inserting
    let key = handle.key();
    
    // Step 3: Insert value using the handle
    map.insert(handle, "Hello, World!");
    
    // Access the value
    assert_eq!(map.get(key), Some(&"Hello, World!"));
    
    // Remove the value
    assert_eq!(map.remove(key), Some("Hello, World!"));
}
```

## Usage Examples

### Basic Operations

```rust
use deferred_map::DeferredMap;

let mut map = DeferredMap::new();

// Allocate and insert
let handle = map.alloc();
let key = handle.key();
map.insert(handle, 42);

// Get immutable reference
assert_eq!(map.get(key), Some(&42));

// Get mutable reference
if let Some(value) = map.get_mut(key) {
    *value = 100;
}
assert_eq!(map.get(key), Some(&100));

// Check existence
assert!(map.contains_key(key));

// Remove value
assert_eq!(map.remove(key), Some(100));
assert_eq!(map.get(key), None);
```

### Building Self-Referential Structures

```rust
use deferred_map::{DeferredMap, DefaultKey};

struct Node {
    value: i32,
    next: Option<DefaultKey>, // Key to next node
}

let mut graph = DeferredMap::new();

// Allocate handles first
let handle1 = graph.alloc();
let handle2 = graph.alloc();

// Get the keys before inserting
let key1 = handle1.key();
let key2 = handle2.key();

// Now we can create nodes that reference each other
let node1 = Node { value: 1, next: Some(key2) };
let node2 = Node { value: 2, next: Some(key1) };

// Insert the nodes
graph.insert(handle1, node1);
graph.insert(handle2, node2);
```

### Iteration

```rust
use deferred_map::DeferredMap;

let mut map = DeferredMap::new();

for i in 0..5 {
    let handle = map.alloc();
    map.insert(handle, i * 10);
}

// Iterate over all entries
for (key, value) in map.iter() {
    println!("Key: {:?}, Value: {}", key, value);
}

// Mutable iteration
for (_, value) in map.iter_mut() {
    *value *= 2;
}
```

### Releasing Unused Handles

```rust
use deferred_map::DeferredMap;

let mut map = DeferredMap::<String>::new();

// Allocate a handle
let handle = map.alloc();

// Decide not to use it
map.release_handle(handle);

// The slot is returned to the free list
```

### Secondary Map

`SecondaryMap` allows you to associate additional data with keys from a `DeferredMap` without modifying the original map or key structure.

```rust
use deferred_map::{DeferredMap, SecondaryMap};

let mut map = DeferredMap::new();
let mut sec = SecondaryMap::new();
sec.bind_to(&map).expect("secondary map binding should succeed");

let h1 = map.alloc();
let k1 = h1.key();
map.insert(h1, "Player 1");

// Associate extra data
sec.insert(k1, 100).expect("secondary map insertion should succeed"); // Health points

assert_eq!(sec.get(k1), Some(&100));

// Removing a key from the main map does not automatically remove its
// SecondaryMap data.
map.remove(k1);
assert_eq!(sec.get(k1), Some(&100));
// ... later ...
let h2 = map.alloc(); // Reuses slot
let k2 = h2.key();
map.insert(h2, "Player 2");

// k1 is stale in the main map, but still matches the old generation in sec.
assert_eq!(sec.get(k1), Some(&100));
// k2 is valid in the main map, but empty in sec until inserted.
assert_eq!(sec.get(k2), None);

sec.insert(k2, 200).expect("secondary map insertion should succeed");
assert_eq!(sec.get(k2), Some(&200));
// Writing the newer generation invalidates the old secondary key.
assert_eq!(sec.get(k1), None);
```

`SecondaryMap::insert` returns `Result<Option<T>, SecondaryMapInsertError>`.
Handle the error when a sparse key index cannot be represented or allocated.

`Handle` is runtime-only and intentionally does not implement serde serialization.
It contains the primary map's runtime identity and may represent a reserved slot,
so deserializing it could not restore a valid insertion token.

When serde-deserializing a `SecondaryMap`, call `bind_to(&map)` before using its
values. Serialization stores a stable association token in both `DeferredMap`
and `SecondaryMap`; binding rejects a different primary map instead of silently
accepting it. Runtime map identity is still regenerated after deserialization,
and the serialized element count is checked against the occupied slots. Older
payloads without the association token are rejected because their ownership
cannot be validated.

Key-taking methods panic when the key belongs to a different `DeferredMap` instance.
Keys from the same map that are stale or refer to an unoccupied slot return `None`
(`false` for `contains_key`).

You can find more complete examples in the `examples/` directory.

To run the examples:

```bash
cargo run --example basic
cargo run --example secondary
```

## API Overview

### Core Types

- **`DeferredMap<T>`**: The main map structure
- **`Handle`**: A one-time token for deferred insertion (cannot be cloned)

### Main Methods

#### Creating a Map

```rust
DeferredMap::new() -> Self
DeferredMap::with_capacity(capacity: usize) -> Self
```

#### Handle Operations

```rust
alloc(&mut self) -> Handle
insert(&mut self, handle: Handle, value: T)
release_handle(&mut self, handle: Handle)
```

#### Handle Methods

```rust
handle.key() -> K             // Get the key (before insertion)
handle.index() -> u32         // Get the index part
handle.generation() -> Generation // Get the generation part
```

#### Value Access

```rust
get(&self, key: K) -> Option<&T>
get_mut(&mut self, key: K) -> Option<&mut T>
remove(&mut self, key: K) -> Option<T>
contains_key(&self, key: K) -> bool
```

#### Metadata & Iteration

```rust
len(&self) -> usize
is_empty(&self) -> bool
capacity(&self) -> usize
clear(&mut self)
iter(&self) -> impl Iterator<Item = (K, &T)>
iter_mut(&mut self) -> impl Iterator<Item = (K, &mut T)>
```

## How It Works

### Slot States

Each slot in the map can be in one of four states:

1. **Vacant** (0b00): Empty slot, part of the free list
2. **Reserved** (0b01): Handle allocated, awaiting value insertion
3. **Retired** (0b10): Generation exhausted, never reused
4. **Occupied** (0b11): Contains a valid value

### Generational Indices

Keys contain a 64-bit raw value and a runtime-only map identity. The raw value encodes:
- **Lower 32 bits**: Slot index
- **Upper 32 bits**: Generation value
- **Map identity**: Distinguishes keys from different map instances and is not persisted

The slot `Version` is an internal value. Its state bits are not stored in a public
key; `DefaultKey::raw()` contains only the slot index and generation.

This prevents the ABA problem: if you remove a value and reuse the slot, the generation increments, invalidating old keys.
When a slot reaches `Generation::MAX`, it is retired permanently instead of
wrapping to generation 1; later allocations use a different slot index.

### Memory Layout

Slots use a union for memory efficiency:

```rust
union SlotUnion<T> {
    value: ManuallyDrop<T>,  // When occupied
    next_free: u32,           // When vacant (free list pointer)
}
```

## Performance Characteristics

- **Insertion**: O(1) - Pop from free list
- **Lookup**: O(1) - Direct array indexing with generation check
- **Removal**: O(1) - Push to free list
- **Memory**: Slots are reused, minimal allocation overhead
- **Cache Friendly**: Contiguous memory layout

## Safety Guarantees

- **No Use-After-Free**: Generational indices ensure old keys are rejected
- **No Double-Use**: Handles are consumed on use (move semantics)
- **No Leaks**: Proper `Drop` implementation for occupied slots
- **Map Ownership**: Keys and handles are verified to belong to the correct map instance in every build
- **Memory Safe**: All unsafe code is carefully encapsulated and documented

## Comparison with Other Crates

| Feature | deferred-map | slotmap | slab |
|---------|--------------|---------|------|
| Deferred Insertion | Yes | No | No |
| Generational Indices | Yes | Yes | No |
| O(1) Operations | Yes | Yes | Yes |
| Handle-based API | Yes | No | No |
| Memory Efficient | Yes | Yes | Yes |

## Minimum Supported Rust Version (MSRV)

Rust 1.88 or later (edition 2024)

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT]LICENSE-MIT or http://opensource.org/licenses/MIT)

at your option.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Author

ShaoG <shaog.rs@gmail.com>

## Links

- [Repository]https://github.com/shaogme/deferred-map
- [Documentation]https://docs.rs/deferred-map
- [Crates.io]https://crates.io/crates/deferred-map