]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/mod.rs
doc: remove incomplete sentence
[rust.git] / src / libstd / collections / mod.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Collection types.
12 //!
13 //! Rust's standard collection library provides efficient implementations of the most common
14 //! general purpose programming data structures. By using the standard implementations,
15 //! it should be possible for two libraries to communicate without significant data conversion.
16 //!
17 //! To get this out of the way: you should probably just use `Vec` or `HashMap`. These two
18 //! collections cover most use cases for generic data storage and processing. They are
19 //! exceptionally good at doing what they do. All the other collections in the standard
20 //! library have specific use cases where they are the optimal choice, but these cases are
21 //! borderline *niche* in comparison. Even when `Vec` and `HashMap` are technically suboptimal,
22 //! they're probably a good enough choice to get started.
23 //!
24 //! Rust's collections can be grouped into four major categories:
25 //!
26 //! * Sequences: `Vec`, `RingBuf`, `DList`, `BitV`
27 //! * Maps: `HashMap`, `BTreeMap`, `VecMap`
28 //! * Sets: `HashSet`, `BTreeSet`, `BitVSet`
29 //! * Misc: `BinaryHeap`
30 //!
31 //! # When Should You Use Which Collection?
32 //!
33 //! These are fairly high-level and quick break-downs of when each collection should be
34 //! considered. Detailed discussions of strengths and weaknesses of individual collections
35 //! can be found on their own documentation pages.
36 //!
37 //! ### Use a `Vec` when:
38 //! * You want to collect items up to be processed or sent elsewhere later, and don't care about
39 //! any properties of the actual values being stored.
40 //! * You want a sequence of elements in a particular order, and will only be appending to
41 //! (or near) the end.
42 //! * You want a stack.
43 //! * You want a resizable array.
44 //! * You want a heap-allocated array.
45 //!
46 //! ### Use a `RingBuf` when:
47 //! * You want a `Vec` that supports efficient insertion at both ends of the sequence.
48 //! * You want a queue.
49 //! * You want a double-ended queue (deque).
50 //!
51 //! ### Use a `DList` when:
52 //! * You want a `Vec` or `RingBuf` of unknown size, and can't tolerate inconsistent
53 //! performance during insertions.
54 //! * You are *absolutely* certain you *really*, *truly*, want a doubly linked list.
55 //!
56 //! ### Use a `HashMap` when:
57 //! * You want to associate arbitrary keys with an arbitrary value.
58 //! * You want a cache.
59 //! * You want a map, with no extra functionality.
60 //!
61 //! ### Use a `BTreeMap` when:
62 //! * You're interested in what the smallest or largest key-value pair is.
63 //! * You want to find the largest or smallest key that is smaller or larger than something
64 //! * You want to be able to get all of the entries in order on-demand.
65 //! * You want a sorted map.
66 //!
67 //! ### Use a `VecMap` when:
68 //! * You want a `HashMap` but with known to be small `uint` keys.
69 //! * You want a `BTreeMap`, but with known to be small `uint` keys.
70 //!
71 //! ### Use the `Set` variant of any of these `Map`s when:
72 //! * You just want to remember which keys you've seen.
73 //! * There is no meaningful value to associate with your keys.
74 //! * You just want a set.
75 //!
76 //! ### Use a `BitV` when:
77 //! * You want to store an unbounded number of booleans in a small space.
78 //! * You want a bitvector.
79 //!
80 //! ### Use a `BitVSet` when:
81 //! * You want a `VecSet`.
82 //!
83 //! ### Use a `BinaryHeap` when:
84 //! * You want to store a bunch of elements, but only ever want to process the "biggest"
85 //! or "most important" one at any given time.
86 //! * You want a priority queue.
87 //!
88 //! # Correct and Efficient Usage of Collections
89 //!
90 //! Of course, knowing which collection is the right one for the job doesn't instantly
91 //! permit you to use it correctly. Here are some quick tips for efficient and correct
92 //! usage of the standard collections in general. If you're interested in how to use a
93 //! specific collection in particular, consult its documentation for detailed discussion
94 //! and code examples.
95 //!
96 //! ## Capacity Management
97 //!
98 //! Many collections provide several constructors and methods that refer to "capacity".
99 //! These collections are generally built on top of an array. Optimally, this array would be
100 //! exactly the right size to fit only the elements stored in the collection, but for the
101 //! collection to do this would be very inefficient. If the backing array was exactly the
102 //! right size at all times, then every time an element is inserted, the collection would
103 //! have to grow the array to fit it. Due to the way memory is allocated and managed on most
104 //! computers, this would almost surely require allocating an entirely new array and
105 //! copying every single element from the old one into the new one. Hopefully you can
106 //! see that this wouldn't be very efficient to do on every operation.
107 //!
108 //! Most collections therefore use an *amortized* allocation strategy. They generally let
109 //! themselves have a fair amount of unoccupied space so that they only have to grow
110 //! on occasion. When they do grow, they allocate a substantially larger array to move
111 //! the elements into so that it will take a while for another grow to be required. While
112 //! this strategy is great in general, it would be even better if the collection *never*
113 //! had to resize its backing array. Unfortunately, the collection itself doesn't have
114 //! enough information to do this itself. Therefore, it is up to us programmers to give it
115 //! hints.
116 //!
117 //! Any `with_capacity` constructor will instruct the collection to allocate enough space
118 //! for the specified number of elements. Ideally this will be for exactly that many
119 //! elements, but some implementation details may prevent this. `Vec` and `RingBuf` can
120 //! be relied on to allocate exactly the requested amount, though. Use `with_capacity`
121 //! when you know exactly how many elements will be inserted, or at least have a
122 //! reasonable upper-bound on that number.
123 //!
124 //! When anticipating a large influx of elements, the `reserve` family of methods can
125 //! be used to hint to the collection how much room it should make for the coming items.
126 //! As with `with_capacity`, the precise behavior of these methods will be specific to
127 //! the collection of interest.
128 //!
129 //! For optimal performance, collections will generally avoid shrinking themselves.
130 //! If you believe that a collection will not soon contain any more elements, or
131 //! just really need the memory, the `shrink_to_fit` method prompts the collection
132 //! to shrink the backing array to the minimum size capable of holding its elements.
133 //!
134 //! Finally, if ever you're interested in what the actual capacity of the collection is,
135 //! most collections provide a `capacity` method to query this information on demand.
136 //! This can be useful for debugging purposes, or for use with the `reserve` methods.
137 //!
138 //! ## Iterators
139 //!
140 //! Iterators are a powerful and robust mechanism used throughout Rust's standard
141 //! libraries. Iterators provide a sequence of values in a generic, safe, efficient
142 //! and convenient way. The contents of an iterator are usually *lazily* evaluated,
143 //! so that only the values that are actually needed are ever actually produced, and
144 //! no allocation need be done to temporarily store them. Iterators are primarily
145 //! consumed using a `for` loop, although many functions also take iterators where
146 //! a collection or sequence of values is desired.
147 //!
148 //! All of the standard collections provide several iterators for performing bulk
149 //! manipulation of their contents. The three primary iterators almost every collection
150 //! should provide are `iter`, `iter_mut`, and `into_iter`. Some of these are not
151 //! provided on collections where it would be unsound or unreasonable to provide them.
152 //!
153 //! `iter` provides an iterator of immutable references to all the contents of a
154 //! collection in the most "natural" order. For sequence collections like `Vec`, this
155 //! means the items will be yielded in increasing order of index starting at 0. For ordered
156 //! collections like `BTreeMap`, this means that the items will be yielded in sorted order.
157 //! For unordered collections like `HashMap`, the items will be yielded in whatever order
158 //! the internal representation made most convenient. This is great for reading through
159 //! all the contents of the collection.
160 //!
161 //! ```
162 //! let vec = vec![1u, 2, 3, 4];
163 //! for x in vec.iter() {
164 //!    println!("vec contained {}", x);
165 //! }
166 //! ```
167 //!
168 //! `iter_mut` provides an iterator of *mutable* references in the same order as `iter`.
169 //! This is great for mutating all the contents of the collection.
170 //!
171 //! ```
172 //! let mut vec = vec![1u, 2, 3, 4];
173 //! for x in vec.iter_mut() {
174 //!    *x += 1;
175 //! }
176 //! ```
177 //!
178 //! `into_iter` transforms the actual collection into an iterator over its contents
179 //! by-value. This is great when the collection itself is no longer needed, and the
180 //! values are needed elsewhere. Using `extend` with `into_iter` is the main way that
181 //! contents of one collection are moved into another. Calling `collect` on an iterator
182 //! itself is also a great way to convert one collection into another. Both of these
183 //! methods should internally use the capacity management tools discussed in the
184 //! previous section to do this as efficiently as possible.
185 //!
186 //! ```
187 //! let mut vec1 = vec![1u, 2, 3, 4];
188 //! let vec2 = vec![10u, 20, 30, 40];
189 //! vec1.extend(vec2.into_iter());
190 //! ```
191 //!
192 //! ```
193 //! use std::collections::RingBuf;
194 //!
195 //! let vec = vec![1u, 2, 3, 4];
196 //! let buf: RingBuf<uint> = vec.into_iter().collect();
197 //! ```
198 //!
199 //! Iterators also provide a series of *adapter* methods for performing common tasks to
200 //! sequences. Among the adapters are functional favorites like `map`, `fold`, `skip`,
201 //! and `take`. Of particular interest to collections is the `rev` adapter, that
202 //! reverses any iterator that supports this operation. Most collections provide reversible
203 //! iterators as the way to iterate over them in reverse order.
204 //!
205 //! ```
206 //! let vec = vec![1u, 2, 3, 4];
207 //! for x in vec.iter().rev() {
208 //!    println!("vec contained {}", x);
209 //! }
210 //! ```
211 //!
212 //! Several other collection methods also return iterators to yield a sequence of results
213 //! but avoid allocating an entire collection to store the result in. This provides maximum
214 //! flexibility as `collect` or `extend` can be called to "pipe" the sequence into any
215 //! collection if desired. Otherwise, the sequence can be looped over with a `for` loop. The
216 //! iterator can also be discarded after partial use, preventing the computation of the unused
217 //! items.
218 //!
219 //! ## Entries
220 //!
221 //! The `entry` API is intended to provide an efficient mechanism for manipulating
222 //! the contents of a map conditionally on the presence of a key or not. The primary
223 //! motivating use case for this is to provide efficient accumulator maps. For instance,
224 //! if one wishes to maintain a count of the number of times each key has been seen,
225 //! they will have to perform some conditional logic on whether this is the first time
226 //! the key has been seen or not. Normally, this would require a `find` followed by an
227 //! `insert`, effectively duplicating the search effort on each insertion.
228 //!
229 //! When a user calls `map.entry(key)`, the map will search for the key and then yield
230 //! a variant of the `Entry` enum.
231 //!
232 //! If a `Vacant(entry)` is yielded, then the key *was not* found. In this case the
233 //! only valid operation is to `set` the value of the entry. When this is done,
234 //! the vacant entry is consumed and converted into a mutable reference to the
235 //! the value that was inserted. This allows for further manipulation of the value
236 //! beyond the lifetime of the search itself. This is useful if complex logic needs to
237 //! be performed on the value regardless of whether the value was just inserted.
238 //!
239 //! If an `Occupied(entry)` is yielded, then the key *was* found. In this case, the user
240 //! has several options: they can `get`, `set`, or `take` the value of the occupied
241 //! entry. Additionally, they can convert the occupied entry into a mutable reference
242 //! to its value, providing symmetry to the vacant `set` case.
243 //!
244 //! ### Examples
245 //!
246 //! Here are the two primary ways in which `entry` is used. First, a simple example
247 //! where the logic performed on the values is trivial.
248 //!
249 //! #### Counting the number of times each character in a string occurs
250 //!
251 //! ```
252 //! use std::collections::btree_map::{BTreeMap, Occupied, Vacant};
253 //!
254 //! let mut count = BTreeMap::new();
255 //! let message = "she sells sea shells by the sea shore";
256 //!
257 //! for c in message.chars() {
258 //!     match count.entry(c) {
259 //!         Vacant(entry) => { entry.set(1u); },
260 //!         Occupied(mut entry) => *entry.get_mut() += 1,
261 //!     }
262 //! }
263 //!
264 //! assert_eq!(count.get(&'s'), Some(&8));
265 //!
266 //! println!("Number of occurences of each character");
267 //! for (char, count) in count.iter() {
268 //!     println!("{}: {}", char, count);
269 //! }
270 //! ```
271 //!
272 //! When the logic to be performed on the value is more complex, we may simply use
273 //! the `entry` API to ensure that the value is initialized, and perform the logic
274 //! afterwards.
275 //!
276 //! #### Tracking the inebriation of customers at a bar
277 //!
278 //! ```
279 //! use std::collections::btree_map::{BTreeMap, Occupied, Vacant};
280 //!
281 //! // A client of the bar. They have an id and a blood alcohol level.
282 //! struct Person { id: u32, blood_alcohol: f32 };
283 //!
284 //! // All the orders made to the bar, by client id.
285 //! let orders = vec![1,2,1,2,3,4,1,2,2,3,4,1,1,1];
286 //!
287 //! // Our clients.
288 //! let mut blood_alcohol = BTreeMap::new();
289 //!
290 //! for id in orders.into_iter() {
291 //!     // If this is the first time we've seen this customer, initialize them
292 //!     // with no blood alcohol. Otherwise, just retrieve them.
293 //!     let person = match blood_alcohol.entry(id) {
294 //!         Vacant(entry) => entry.set(Person{id: id, blood_alcohol: 0.0}),
295 //!         Occupied(entry) => entry.into_mut(),
296 //!     };
297 //!
298 //!     // Reduce their blood alcohol level. It takes time to order and drink a beer!
299 //!     person.blood_alcohol *= 0.9;
300 //!
301 //!     // Check if they're sober enough to have another beer.
302 //!     if person.blood_alcohol > 0.3 {
303 //!         // Too drunk... for now.
304 //!         println!("Sorry {}, I have to cut you off", person.id);
305 //!     } else {
306 //!         // Have another!
307 //!         person.blood_alcohol += 0.1;
308 //!     }
309 //! }
310 //! ```
311
312 #![experimental]
313
314 pub use core_collections::{BinaryHeap, Bitv, BitvSet, BTreeMap, BTreeSet};
315 pub use core_collections::{DList, RingBuf, VecMap};
316
317 /// Deprecated: Moved to collect-rs: https://github.com/Gankro/collect-rs/
318 #[deprecated = "Moved to collect-rs: https://github.com/Gankro/collect-rs/"]
319 pub use core_collections::EnumSet;
320
321 pub use core_collections::{binary_heap, bitv, bitv_set, btree_map, btree_set};
322 pub use core_collections::{dlist, ring_buf, vec_map};
323
324 /// Deprecated: Moved to collect-rs: https://github.com/Gankro/collect-rs/
325 #[deprecated = "Moved to collect-rs: https://github.com/Gankro/collect-rs/"]
326 pub use core_collections::enum_set;
327
328 pub use self::hash_map::HashMap;
329 pub use self::hash_set::HashSet;
330
331 mod hash;
332
333 pub mod hash_map {
334     //! A hashmap
335     pub use super::hash::map::*;
336 }
337
338 pub mod hash_set {
339     //! A hashset
340     pub use super::hash::set::*;
341 }