github.com/Nigel2392/go-datastructures@v1.1.5/hashmap/buckets.go (about) 1 package hashmap 2 3 import "github.com/Nigel2392/go-datastructures" 4 5 type bucket[T1 datastructures.Hashable[T1], T2 any] struct { 6 root *bucketNode[T1, T2] 7 _len int 8 } 9 10 func (b *bucket[T1, T2]) insert(hash uint64, k T1, v T2) { 11 12 var key = &keyNode[T1, T2]{ 13 _hash: hash, 14 key: k, 15 value: v, 16 } 17 18 if b.root == nil { 19 var newNode = &bucketNode[T1, T2]{ 20 _hash: hash, 21 next: key, 22 } 23 24 b._len++ 25 b.root = newNode 26 return 27 } 28 29 b.root.insert(key) 30 b._len++ 31 } 32 33 func (b *bucket[T1, T2]) retrieve(k T1) (v T2, ok bool) { 34 var key = &keyNode[T1, T2]{ 35 _hash: k.Hash(), 36 key: k, 37 } 38 39 return b.root.retrieve(key) 40 } 41 42 func (b *bucket[T1, T2]) delete(k T1) (ok bool) { 43 if b.root == nil { 44 return false 45 } 46 47 var key = &keyNode[T1, T2]{ 48 _hash: k.Hash(), 49 key: k, 50 } 51 52 b.root, ok = b.root.delete(key) 53 if ok { 54 b._len-- 55 } 56 return ok 57 } 58 59 func (b *bucket[T1, T2]) deleteIf(predicate func(k T1, v T2) bool) (amountDeleted int) { 60 if b.root == nil { 61 return 62 } 63 64 var newRoot *bucketNode[T1, T2] 65 66 newRoot, amountDeleted = b.root.deleteIf(predicate) 67 b.root = newRoot 68 b._len -= amountDeleted 69 return 70 } 71 72 func (b *bucket[T1, T2]) pop(k T1) (v T2, ok bool) { 73 if b.root == nil { 74 return 75 } 76 77 var key = &keyNode[T1, T2]{ 78 _hash: k.Hash(), 79 key: k, 80 } 81 82 b.root, v, ok = b.root.pop(key) 83 if ok { 84 b._len-- 85 } 86 return 87 } 88 89 func (b *bucket[T1, T2]) traverse(f func(k T1, v T2) bool) (continueLoop bool) { 90 return b.root.traverse(f) 91 } 92 93 func traverseTree[T1 datastructures.Hashable[T1], T2 any](node *bucketNode[T1, T2], f func(*bucketNode[T1, T2]) bool) (continueLoop bool) { 94 if node == nil { 95 return true 96 } 97 98 if !traverseTree(node.left, f) { 99 return false 100 } 101 102 if !f(node) { 103 return false 104 } 105 106 if !traverseTree(node.right, f) { 107 return false 108 } 109 110 return true 111 } 112 113 func (b *bucket[T1, T2]) len() int { 114 return b._len 115 }