How to do it...

  1. Open the Cargo.toml file that has been generated earlier for you.

  2. Under [dependencies], add the following line:
slab = "0.4.0"
  1. If you want, you can go to slab's crates.io page (https://crates.io/crates/slab) to check for the newest version, and use that one instead.
  2. In the folder bin, create a file called slab.rs.

  3. Add the following code, and run it with cargo run --bin slab:

1   extern crate slab;
2 use slab::{Slab, VacantEntry};
3
4 fn main() {
5 // A slab is meant to be used as a limited buffer
6 // As such, you should initialize it with a pre-
7 // defined capacity
8 const CAPACITY: usize = 1024;
9 let mut slab = Slab::with_capacity(CAPACITY);
10
11 // You cannot simply access a slab's entry by
12 // index or by searching it. Instead, every
13 // insert gives you a key that you can use to
14 // access its entry
15 let hello_key = slab.insert("hello");
16 let world_key = slab.insert("world");
17
18 println!("hello_key -> '{}'", slab[hello_key],);
19 println!("world_key -> '{}'", slab[world_key],);
20
21
22 // You can pass an "empty spot" around
23 // in order to be filled
24 let data_key = {
25 let entry = slab.vacant_entry();
26 fill_some_data(entry)
27 };
28 println!("data_key -> '{}'", slab[data_key],);
29
30 // When iterating, you get a key-value pair
31 for (key, val) in &slab {
32 println!("{} -> {}", key, val);
33 }
34
35 // If you want to keep your slab at a constant
36 // capacity, you have to manually check its
37 // length before inserting data
38 if slab.len() != slab.capacity() {
39 slab.insert("the slab is not at capacity yet");
40 }
41 }
42
43
44 fn fill_some_data(entry: VacantEntry<&str>) -> usize {
45 let data = "Some data";
46 // insert() consumes the entry
47 // so we need to get the key before
48 let key = entry.key();
49 entry.insert(data);
50 key
51 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.46.69