#slab #type-safe #key #tokens #structure #wrapper #data-structures

slab_typesafe

A wrapper for Slab that provides type-safe tokens instead of usize

4 releases

Uses old Rust 2015

0.1.3 Jan 7, 2019
0.1.2 May 31, 2018
0.1.1 Dec 27, 2017
0.1.0 Dec 27, 2017

#439 in Memory management

Download history 253/week @ 2023-12-07 300/week @ 2023-12-14 186/week @ 2023-12-21 128/week @ 2023-12-28 223/week @ 2024-01-04 275/week @ 2024-01-11 245/week @ 2024-01-18 358/week @ 2024-01-25 366/week @ 2024-02-01 465/week @ 2024-02-08 306/week @ 2024-02-15 482/week @ 2024-02-22 321/week @ 2024-02-29 324/week @ 2024-03-07 258/week @ 2024-03-14 297/week @ 2024-03-21

1,264 downloads per month
Used in 6 crates (3 directly)

MIT/Apache

29KB
226 lines

slab_typesafe

A type-safe wrapper from Rust's "slab" data structure

Prevents using slab with obviously wrong keys:

#[macro_use] 
extern crate slab_typesafe;

declare_slab_token!(StringHandle1);
declare_slab_token!(StringHandle2);

let mut slab1 : Slab<StringHandle1, _> = Slab::new();
let mut slab2 : Slab<StringHandle2, _> = Slab::new();

let hello = slab1.insert("hello");
let world = slab2.insert("world");

slab1[world]; // the type `Slab<StringHandle1, _>` cannot be indexed by `StringHandle2`
slab2.remove(hello); // expected struct `StringHandle2`, found struct `StringHandle1`
```rust

lib.rs:

A type-safe wrapper for slab. It implements the same data structure with the same methods, but takes and returns special tokens instead of usize values, preventing you from confusing them with other unrelated usizes, including keys for other Slab instances.

The protection is shallow, as the tokens implement From and Into. Additionally, entire slab may be converted back and forth between wrapped typesafe and unwrapped usize versions.

Based on compactmap::wrapped

Examples

Basic storing and retrieval.

#[macro_use]
extern crate slab_typesafe;
declare_slab_token!(StringHandle);
let mut slab : Slab<StringHandle, &'static str> = Slab::new();

let hello = slab.insert("hello");
let world = slab.insert("world");

assert_eq!(slab[hello], "hello");
assert_eq!(slab[world], "world");

slab[world] = "earth";
assert_eq!(slab[world], "earth");

Error if you confused the handles

#[macro_use]
extern crate slab_typesafe;
declare_slab_token!(StringHandle1);
declare_slab_token!(StringHandle2);
let mut slab1 : Slab<StringHandle1, _> = Slab::new();
let mut slab2 : Slab<StringHandle2, _> = Slab::new();

let hello = slab1.insert("hello");
let world = slab2.insert("world");

slab1[world]; // the type `Slab<StringHandle1, _>` cannot be indexed by `StringHandle2`
slab2.remove(hello); // expected struct `StringHandle2`, found struct `StringHandle1`

See the rest of examples in the original documentation.

The documentation is mostly a copy of the original crate's documentation.

Dependencies

~44KB