Build a Lean HashMap from pre-built key-value pairs. Lean's Std.HashMap structure (with unboxing): - HashMap α β unboxes through DHashMap to Raw - Raw = { size : Nat, buckets : Array (AssocList α β) } - Field 0 = size (Nat), Field 1 = buckets (Array) AssocList α β = nil | cons (key : α) (value : β) (tail : AssocList α β)
( pairs: Vec<(LeanOwned, LeanOwned, u64)>, // (key_obj, val_obj, hash) )
| 25 | /// |
| 26 | /// AssocList α β = nil | cons (key : α) (value : β) (tail : AssocList α β) |
| 27 | pub fn build_hashmap_from_pairs( |
| 28 | pairs: Vec<(LeanOwned, LeanOwned, u64)>, // (key_obj, val_obj, hash) |
| 29 | ) -> LeanOwned { |
| 30 | let size = pairs.len(); |
| 31 | let bucket_count = (size * 4 / 3 + 1).next_power_of_two().max(8); |
| 32 | |
| 33 | // Create array of AssocLists (initially all nil = boxed 0) |
| 34 | let buckets = LeanArray::alloc(bucket_count); |
| 35 | let nil = LeanOwned::box_usize(0); |
| 36 | for i in 0..bucket_count { |
| 37 | buckets.set(i, nil.clone()); // nil |
| 38 | } |
| 39 | |
| 40 | // Insert entries |
| 41 | for (key_obj, val_obj, hash) in pairs { |
| 42 | let bucket_idx = |
| 43 | usize::try_from(hash).expect("hash overflows usize") % bucket_count; |
| 44 | |
| 45 | // Get current bucket (AssocList) |
| 46 | let current_tail = buckets.get(bucket_idx).to_owned_ref(); |
| 47 | |
| 48 | // cons (key : α) (value : β) (tail : AssocList α β) -- tag 1 |
| 49 | let cons = LeanCtor::alloc(1, 3, 0); |
| 50 | cons.set(0, key_obj); |
| 51 | cons.set(1, val_obj); |
| 52 | cons.set(2, current_tail); |
| 53 | |
| 54 | buckets.set(bucket_idx, cons); |
| 55 | } |
| 56 | |
| 57 | // Build Raw { size : Nat, buckets : Array } |
| 58 | // Due to unboxing, this IS the HashMap directly |
| 59 | // Field 0 = size, Field 1 = buckets (2 object fields, no scalars) |
| 60 | let size_obj = LeanOwned::box_usize(size); |
| 61 | |
| 62 | let raw = LeanCtor::alloc(0, 2, 0); |
| 63 | raw.set(0, size_obj); |
| 64 | raw.set(1, buckets); |
| 65 | raw.into() |
| 66 | } |
| 67 | |
| 68 | // ============================================================================= |
| 69 | // Environment Building / Decoding |