// expect: run // result: 42 // phase: 6 // spec: docs/spec/16-standard-library.md ยง2.14 // grant: heap=mem.alloc:1024 module test.hashmap import std.hashmap; import std.option; fn opened) -> u64 effects [], E: fn(ref, ref) -> bool effects []>(capacity: usize, heap: cap) -> std.hashmap.HashMap effects [mem.alloc] { match std.hashmap.new::(capacity, heap) { std.hashmap.NewResult::::ok(map) => { return move map; } std.hashmap.NewResult::::err(error) => { trap; } } } fn inserted(result: std.hashmap.InsertResult) -> void effects [] { match move result { std.hashmap.InsertResult::::inserted => {}, std.hashmap.InsertResult::::full(value) => { trap; }, std.hashmap.InsertResult::::replaced(value) => { trap; } } } fn extracted(value: std.option.Option) -> T effects [] { match move value { std.option.Option::::some(item) => { return move item; }, std.option.Option::::none => { trap; } } } fn released) -> u64 effects [], E: fn(ref, ref) -> bool effects []>(map: std.hashmap.HashMap) -> void effects [] { match std.hashmap.free::(move map) { std.hashmap.FreeResult::::ok => {}, std.hashmap.FreeResult::::not_empty(value) => { trap; } } } struct Key { id: u64 } fn hash(key: ref) -> u64 effects [] { return 3; } fn equal(a: ref, b: ref) -> bool effects [] { return a.id == b.id; } fn main(heap: cap) -> u64 effects [mem.alloc] { let map = opened::(2, heap); { mut q = map; inserted::(std.hashmap.insert::(q, Key { id: 1 }, 11)); inserted::(std.hashmap.insert::(q, Key { id: 2 }, 22)); match std.hashmap.insert::(q, Key { id: 3 }, 33) { std.hashmap.InsertResult::::full(entry) => { assert(entry.key.id == 3u64); assert(entry.value == 33u64); }, std.hashmap.InsertResult::::inserted => { trap; }, std.hashmap.InsertResult::::replaced(old) => { trap; } } match std.hashmap.insert::(q, Key { id: 2 }, 42) { std.hashmap.InsertResult::::replaced(old) => { assert(old.key.id == 2u64); assert(old.value == 22u64); }, std.hashmap.InsertResult::::inserted => { trap; }, std.hashmap.InsertResult::::full(entry) => { trap; } } let key = Key { id: 1 }; let removed = extracted::>(std.hashmap.remove::(q, ref key)); assert(removed.key.id == 1u64); assert(removed.value == 11u64); inserted::(std.hashmap.insert::(q, Key { id: 3 }, 33)); match std.hashmap.reserve::(q, 4, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } } } { ref q = map; let key = Key { id: 2 }; assert(std.hashmap.contains::(q, ref key)); assert(extracted::(std.hashmap.get::(q, ref key)) == 42u64); assert(std.hashmap.len::(q) == 2usize); assert(std.hashmap.capacity::(q) == 4usize); } { mut q = map; let last = extracted::>(std.hashmap.pop::(q)); assert(last.key.id == 3u64); let first = extracted::>(std.hashmap.pop::(q)); assert(first.value == 42u64); } released::(move map); return 42; }