// 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, owner: own } fn hash(key: ref) -> u64 effects [] { return 3; } fn equal(a: ref, b: ref) -> bool effects [] { return a.id == b.id; } fn consumed(entry: std.hashmap.Entry>) -> u64 effects [] { let (key, value) = struct.unpack(move entry); let (id, owner) = struct.unpack(move key); assert(own.take(move owner) == id); return own.take(move value); } fn main(heap: cap) -> u64 effects [mem.alloc] { let map = opened::, fn hash, fn equal>(2, heap); { mut q = map; let k1 = Key { id: 1, owner: own.new(1u64, heap) or trap }; let v1 = own.new(11u64, heap) or trap; inserted::>(std.hashmap.insert::, fn hash, fn equal>(q, move k1, move v1)); let k2 = Key { id: 2, owner: own.new(2u64, heap) or trap }; let v2 = own.new(22u64, heap) or trap; inserted::>(std.hashmap.insert::, fn hash, fn equal>(q, move k2, move v2)); let query = Key { id: 1, owner: own.new(1u64, heap) or trap }; assert(consumed(extracted::>>(std.hashmap.remove::, fn hash, fn equal>(q, ref query))) == 11u64); let (id, owner) = struct.unpack(move query); own.take(move owner); match std.hashmap.reserve::, fn hash, fn equal>(q, 3, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } } assert(consumed(extracted::>>(std.hashmap.pop::, fn hash, fn equal>(q))) == 22u64); } released::, fn hash, fn equal>(move map); return 42; }