animals/
animals.rs

1fn main() {
2    use hashvec::*;
3
4    // Create a new hashvec containing pairs of animal names and species
5    // The hashvec! macro acts like vec!, but with key-value tuple pairs
6    let mut hashvec: HashVec<&'static str, &'static str> = hashvec![
7        ("Doug", "Kobold"),
8        ("Skye", "Hyena"),
9        ("Lee", "Shiba"),
10        ("Sock", "Man"),
11        ("Salad", "Wolf"),
12        ("Finn", "Human")
13    ];
14
15    // Insert a value into the hashvec (HashMap-style)
16    // Inserting overwrites existing keys' entries in-place
17    hashvec.insert("Jake", "Dog");
18
19    // Push a value onto the hashvec (Vector-style)
20    // Pushing overwrites existing keys' entries and moves them to the end
21    hashvec.push(("Susie", "Squid"));
22
23    // Access a value by key
24    match hashvec.get(&"Finn") {
25        Some(value) => {
26            assert_eq!(*value, "Human");
27        },
28        None => {}
29    }
30    
31    // Access an entry by index
32    let lee_value = hashvec[2];
33    assert_eq!(lee_value, ("Lee", "Shiba"));
34    
35    // Get the index of a key
36    let lee_index = hashvec.index(&"Lee").unwrap();
37    assert_eq!(lee_index, 2);
38
39    // Get the length of the hashvec
40    let hashvec_length = hashvec.len();
41    assert_eq!(hashvec_length, 8);
42    
43    // Change an entry's key in-place
44    hashvec.rename(&"Salad", "Caesar");
45    assert_eq!(hashvec[4], ("Caesar", "Wolf"));
46
47    // Mutate a value
48    match hashvec.get_mut(&"Sock") {
49        Some(value) => {
50            *value = "Guinea Pig";
51        },
52        None => {}
53    }
54    assert_eq!(*hashvec.get(&"Sock").unwrap(), "Guinea Pig");
55
56    // Remove an entry
57    hashvec.remove_key(&"Doug");
58    assert_eq!(hashvec.get(&"Doug"), None);
59
60    // Swap the locations of two entries by their keys
61    hashvec.swap_keys(&"Lee", &"Skye");
62    assert_eq!(hashvec.index(&"Lee").unwrap(), 0);
63    assert_eq!(hashvec.index(&"Skye").unwrap(), 1);
64
65    // Now swap them again, by their indices
66    hashvec.swap_indices(0, 1);
67    assert_eq!(hashvec[0], ("Skye", "Hyena"));
68    assert_eq!(hashvec[1], ("Lee", "Shiba"));
69    
70    // Iterate over each of the key-value pairs in the hashvec
71    for (k, v) in hashvec.into_iter() {
72        println!("{} is a {}!", k, v);
73    }
74
75    // Remove an entry from the end of the hashvec
76    let last_entry = hashvec.pop();
77    assert_eq!(last_entry.unwrap(), ("Susie", "Squid"));
78
79    // Clear the hashvec
80    hashvec.clear();
81}