Strongly-typed, zero-cost indexes wrapping integers.
This crate is just one macro: new
. It creates a wrapper around usize
to make
type-safe indexes. That is, the indexes for your clients that you use to retrieve information
efficiently from the vector of client information do not have the same type as the indexes for
the files you have about your clients. The example below illustrates this crate in
that context.
The index type created implements
Deref
andFrom
forusize
,Debug
,Default
,Clone
,Copy
,PartialOrd
,Ord
,PartialEq
,Eq
,Hash
andDisplay
.
If you are experiencing problems upgrading from a version < 0.9.17
, make sure you read the
changelog.
Usage
The most basic use of new
is just to wrap something:
safe_index::new!{
/// Arity.
Arity
}
assert_eq! { core::mem::size_of::<Arity>(), core::mem::size_of::<usize>() }
This is not very useful however, there's nothing for our index to index. Thankfully new
can provide more types. After the mandatory identifier Idx
for the type of indexes, you can
add these:
map <Map>
: creates a wrapper named<Map>
around a vector, indexed byIdx
.btree set <Set>
: alias type for a binary tree set ofIdx
s.btree map <Map>
: alias type for a binary tree map fromIdx
to something.
See the examples
module and the example below for illustrations of the new
macro.
Example
All the code for this example is in examples::clients
. Say we have a Data
structure that
stores some clients in a vector. It also stores files about these clients. A client can be
associated to several files, and a file can be about several clients. Let's handle everything
by indexes:
# use BTreeSet;
/// Client information.
/// File information.
/// Aggregates clients and files info.
Now, implementing Data
's functionalities is going to be painful. Client and file indexes are
both usize
, terrible things are bound to happen.
So let's instead create an index type for each.
/// Indices.
use *;
# use BTreeSet;
/// Client information.
/// File information.
/// Aggregates clients and files info.
The full code is available here, and you can see it used in the documentation of
examples::clients
. Here are a few functions on Data
to (hopefully) show that Client
and
File
behave as (and in fact are) usize
indexes.
# use ;
/// Aggregates clients and files info.