# Crate im[−][src]

# Immutable Data Structures for Rust

This library implements several of the more commonly useful immutable data structures for Rust.

## Why Would I Want This?

While immutable data structures can be a game changer for other programming languages, the most obvious benefit - avoiding the accidental mutation of data - is already handled so well by Rust's type system that it's just not something a Rust programmer needs to worry about even when using data structures that would send a conscientious Clojure programmer into a panic.

Immutable data structures offer other benefits, though, some of
which are useful even in a language like Rust. The most prominent
is *structural sharing*, which means that if two data structures
are mostly copies of each other, most of the memory they take up
will be shared between them. This implies that making copies of an
immutable data structure is cheap: it's really only a matter of
copying a pointer and increasing a reference counter, where in the
case of `Vec`

you have to allocate the same
amount of memory all over again and make a copy of every element
it contains. For immutable data structures, extra memory isn't
allocated until you modify either the copy or the original, and
then only the memory needed to record the difference.

Another goal of this library has been the idea that you shouldn't
even have to think about what data structure to use in any given
situation, until the point where you need to start worring about
optimisation - which, in practice, often never comes. Beyond the
shape of your data (ie. whether to use a list or a map), it should
be fine not to think too carefully about data structures - you can
just pick the one that has the right shape and it should have
acceptable performance characteristics for every operation you
might need. Specialised data structures will always be faster at
what they've been specialised for, but `im`

aims to provide the
data structures which deliver the least chance of accidentally
using them for the wrong thing.

For instance, `Vec`

beats everything at memory
usage, indexing and operations that happen at the back of the
list, but is terrible at insertion and removal, and gets worse the
closer to the front of the list you get.
`VecDeque`

adds a little bit of
complexity in order to make operations at the front as efficient
as operations at the back, but is still bad at insertion and
especially concatenation. `Vector`

adds another
bit of complexity, and could never match `Vec`

at
what it's best at, but in return every operation you can throw at
it can be completed in a reasonable amount of time - even normally
expensive operations like copying and especially concatenation are
reasonably cheap when using a `Vector`

.

It should be noted, however, that because of its simplicity,
`Vec`

actually beats Vector
even at its strongest operations at small sizes, just because
modern CPUs are hyperoptimised for things like copying small
chunks of contiguous memory - you actually need to go past a
certain size (usually in the vicinity of one or two hundred
elements) before you get to the point where `Vec`

isn't always going to be the fastest choice.
Vector attempts to overcome this by basically
just being a couple of `Vec`

s at small sizes, until it grows big
enough to warrant a more traditional immutable tree structure, but
even this involves a little bit of overhead.

The maps - `HashMap`

and
`OrdMap`

- generally perform similarly to their
equivalents in the standard library, but tend to run a bit slower
on the basic operations (`HashMap`

is almost
neck and neck with its counterpart, while
`OrdMap`

currently tends to run 2-3x slower). On
the other hand, they offer the cheap copy and structural sharing
between copies that you'd expect from immutable data structures.

In conclusion, the aim of this library is to provide a safe default choice for the most common kinds of data structures, allowing you to defer careful thinking about the right data structure for the job until you need to start looking for optimisations - and you may find, especially for larger data sets, that immutable data structures are still the right choice.

## Data Structures

We'll attempt to provide a comprehensive guide to the available data structures below.

### Performance Notes

"Big O notation" is the standard way of talking about the time complexity of data structure operations. If you're not familiar with big O notation, here's a quick cheat sheet:

*O(1)* means an operation runs in constant time: it will take the
same time to complete regardless of the size of the data
structure.

*O(n)* means an operation runs in linear time: if you double the
size of your data structure, the operation will take twice as long
to complete; if you quadruple the size, it will take four times as
long, etc.

*O(log n)* means an operation runs in logarithmic time: for
*log _{2}*, if you double the size of your data structure,
the operation will take one step longer to complete; if you
quadruple the size, it will need two steps more; and so on.
However, the data structures in this library generally run in

*log*time, meaning you have to make your data structure 64 times bigger to need one extra step, and 4096 times bigger to need two steps. This means that, while they still count as O(log n), operations on all but really large data sets will run at near enough to O(1) that you won't usually notice.

_{64}*O(n log n)* is the most expensive operation you'll see in this
library: it means that for every one of the *n* elements in your
data structure, you have to perform *log n* operations. In our
case, as noted above, this is often close enough to O(n) that it's
not usually as bad as it sounds, but even O(n) isn't cheap and the
cost still increases logarithmically, if slowly, as the size of
your data increases. O(n log n) basically means "are you sure you
need to do this?"

*O(1)** means 'amortised O(1),' which means that an operation
usually runs in constant time but will occasionally be more
expensive: for instance,
`Vector::push_back`

, if called in
sequence, will be O(1) most of the time but every 64th time it
will be O(log n), as it fills up its tail chunk and needs to
insert it into the tree. Please note that the O(1) with the
asterisk attached is not a common notation; it's just a convention
I've used in these docs to save myself from having to type
'amortised' everywhere.

### Lists

Lists are sequences of single elements which maintain the order in
which you inserted them. The only list in this library is
`Vector`

, which offers the best all round
performance characteristics: it's pretty good at everything, even
if there's always another kind of list that's better at something.

Type | Algorithm | Constraints | Order | Push | Pop | Split | Append | Lookup |
---|---|---|---|---|---|---|---|---|

`Vector<A>` | RRB tree | `Clone` | insertion | O(1)* | O(1)* | O(log n) | O(log n) | O(log n) |

### Maps

Maps are mappings of keys to values, where the most common read operation is to find the value associated with a given key. Maps may or may not have a defined order. Any given key can only occur once inside a map, and setting a key to a different value will overwrite the previous value.

Type | Algorithm | Key Constraints | Order | Insert | Remove | Lookup |
---|---|---|---|---|---|---|

`HashMap<K, V>` | HAMT | `Clone` + `Hash` + `Eq` | undefined | O(log n) | O(log n) | O(log n) |

`OrdMap<K, V>` | B-tree | `Clone` + `Ord` | sorted | O(log n) | O(log n) | O(log n) |

### Sets

Sets are collections of unique values, and may or may not have a defined order. Their crucial property is that any given value can only exist once in a given set.

Type | Algorithm | Constraints | Order | Insert | Remove | Lookup |
---|---|---|---|---|---|---|

`HashSet<A>` | HAMT | `Clone` + `Hash` + `Eq` | undefined | O(log n) | O(log n) | O(log n) |

`OrdSet<A>` | B-tree | `Clone` + `Ord` | sorted | O(log n) | O(log n) | O(log n) |

## In-place Mutation

All of these data structures support in-place copy-on-write
mutation, which means that if you're the sole user of a data
structure, you can update it in place without taking the
performance hit of making a copy of the data structure before
modifying it (this is about an order of magnitude faster than
immutable operations, almost as fast as
`std::collections`

's mutable data structures).

Thanks to `Rc`

's reference counting, we are able to
determine whether a node in a data structure is being shared with
other data structures, or whether it's safe to mutate it in place.
When it's shared, we'll automatically make a copy of the node
before modifying it. The consequence of this is that cloning a
data structure becomes a lazy operation: the initial clone is
instant, and as you modify the cloned data structure it will clone
chunks only where you change them, so that if you change the
entire thing you will eventually have performed a full clone.

This also gives us a couple of other optimisations for free:
implementations of immutable data structures in other languages
often have the idea of local mutation, like Clojure's transients
or Haskell's `ST`

monad - a managed scope where you can treat an
immutable data structure like a mutable one, gaining a
considerable amount of performance because you no longer need to
copy your changed nodes for every operation, just the first time
you hit a node that's sharing structure. In Rust, we don't need to
think about this kind of managed scope, it's all taken care of
behind the scenes because of our low level access to the garbage
collector (which, in our case, is just a simple
`Rc`

).

## Re-exports

`pub use hashmap::HashMap;` |

`pub use hashset::HashSet;` |

`pub use ordmap::OrdMap;` |

`pub use ordset::OrdSet;` |

`pub use vector::Vector;` |

## Modules

hashmap |
An unordered map. |

hashset |
An unordered set. |

iter |
Iterators over immutable data. |

ordmap |
An ordered map. |

ordset |
An ordered set. |

vector |
A persistent vector. |

## Macros

get_in |
Get a value inside multiple levels of data structures. |

hashmap |
Construct a hash map from a sequence of key/value pairs. |

hashset |
Construct a set from a sequence of values. |

ordmap |
Construct a map from a sequence of key/value pairs. |

ordset |
Construct a set from a sequence of values. |

update_in |
Update a value inside multiple levels of data structures. |

vector |
Construct a vector from a sequence of elements. |