Implementation of a hash map container whose content lives in memory.
Inserts a key-value pair into the map.
key
:[K]
- The key to which the value is paired.value
:[V]
- The value to be stored.
use sway_hashmap::HashMap;
fn foo(ref mut map: HashMap<u64, bool>) {
let key = 5_u64;
let value = true;
map.insert(key, value);
let retrieved_value = map.get(key).unwrap();
assert(value == retrieved_value);
}
Retrieves the entry stored at key
, regardless of whether a value is actually stored at that location or not.
key
:[K]
- The key to which the value is paired.
[Option<V>]
- The value stored atkey
if any.
use sway_hashmap::HashMap;
fn foo(ref mut map: HashMap<u64, bool>) {
let key = 5_u64;
let value = true;
map.insert(key, value);
let retrieved_value = map.get(key).unwrap();
assert(value == retrieved_value);
}
Clears a value previously stored using a key
key
:[K]
- The key to which the value is paired.
[bool]
- Indicates whether there was a value previously stored atkey
.
use sway_hashmap::HashMap;
fn foo(ref mut map: HashMap<u64, bool>) {
let key = 5_u64;
let value = true;
map.insert(key, value);
let removed = map.remove(key);
assert(removed);
assert(map.get(key).is_none());
}
Inserts a key-value pair into the map if a value does not already exist for the key.
key
:[K]
- The key to which the value is paired.value
:[V]
- The value to be stored.
[Result<V, HashMapError<V>>]
-Result::Ok(value)
if the value was inserted, orResult::Err(HashMapError::OccupiedError(pre_existing_value))
if a value already existed for the key.
use sway_hashmap::{HashMap, HashMapError};
fn foo(ref mut map: HashMap<u64, bool>) {
let key = 5_u64;
let value = true;
map.insert(key, value);
let new_value = false;
let result = map.try_insert(key, new_value);
assert(result == Result::Err(HashMapError::OccupiedError(value))); // The old value is returned.
let retrieved_value = map.get(key).unwrap();
assert(value == retrieved_value); // New value was not inserted, as a value already existed.
let key2 = 10_u64;
let returned_value = map.try_insert(key2, new_value);
assert(returned_value == Result::Ok(new_value)); // New value is returned.
}