Crate id_collections

Crate id_collections 

Source
Expand description

Index-oriented programming in Rust.

It is common in Rust to define custom wrapper types (sometimes called “newtypes”) around integer types, in order to better communicate the intended meaning of those types, and to catch mistakes arising from mixing up integer values with different meanings. For example, one might define two different types representing “user ids” and “group ids”:

struct UserId(u32);
struct GroupId(u32);

The id_collections crate provides data structures designed to work with these kinds of strongly-typed wrappers around integer types:

  • The IdVec<I, T> type is a vector which uses a custom index type I instead of usize.
  • The IdMap<I, T> type is a map backed by a vector. It’s similar to IdVec<I, T>, except that its set of keys is not required to occupy a contiguous range, so you can fill in its entries out of order.
  • The Count<I> type provides a type-safe way to represent the size of a range of custom ids.

To use the structures in this library with your application’s id types, your id types need to implement the Id trait. The easiest way to implement the Id trait is to use the #[id_type] attribute macro:

use id_collections::id_type;

#[id_type]
struct UserId(u32);

#[id_type]
struct GroupId(u32);

After you’ve implemented Id, you can use your custom id type as the index type for an IdVec:

use id_collections::IdVec;

let mut users: IdVec<UserId, &str> = IdVec::new();
let alice_id: UserId = users.push("Alice");
let bob_id: UserId = users.push("Bob");

assert_eq!(users[alice_id], "Alice");
assert_eq!(users[bob_id], "Bob");

Using IdVec prevents you from accidentally mixing up different id types:

let group = GroupId(1);
let name = users[group]; // error: expected 'UserId', found 'GroupId'!

If you need a collection which supports discontiguous keys, you can use IdMap:

use id_collections::IdMap;

let mut users: IdMap<UserId, &str> = IdMap::new();
users.insert(UserId(5), "Alice");
users.insert(UserId(10), "Bob");
assert_eq!(users[UserId(5)], "Alice");
assert_eq!(users[UserId(10)], "Bob");

Modules§

count
The Count<I> structure and related types.
id
The Id trait and related traits.
id_map
The IdMap<I, T> structure and related types.
id_vec
The IdVec<I, T> structure and related types.

Structs§

Count
A range of strongly-typed indices, starting from zero.
IdMap
A map-like data structure with strongly-typed integer keys, backed by a vector.
IdVec
A vector-like data structure with strongly-typed indices.

Traits§

Id
A trait for custom strongly-typed wrappers around integer types.

Attribute Macros§

id_type
Easily define custom Id types.

Derive Macros§

Id
Derive Id for custom types.