summaryrefslogtreecommitdiff
path: root/dict/dict.go
diff options
context:
space:
mode:
authorJonas Knobloch <jonas.knobloch@t-online.de>2026-09-11 18:38:13 +0200
committerJonas Knobloch <jonas.knobloch@t-online.de>2026-09-11 18:38:13 +0200
commit75e581b3bc19a73d0c1f48b32f2e58121c9741c1 (patch)
tree897e2f24db3374d58ba36dcee67879cc7cd4956c /dict/dict.go
parent330c6387962b197c5ca7a8051d4864feaecc0f25 (diff)
parentf998fee7427403698f9262d1e92d1a307c652094 (diff)
Merge remote-tracking branch 'origin/wip-entropy' into wip-frequency
Diffstat (limited to 'dict/dict.go')
-rw-r--r--dict/dict.go89
1 files changed, 89 insertions, 0 deletions
diff --git a/dict/dict.go b/dict/dict.go
new file mode 100644
index 0000000..f153932
--- /dev/null
+++ b/dict/dict.go
@@ -0,0 +1,89 @@
+package dict
+
+import (
+ "iter"
+ "slices"
+)
+
+type Entry[V any] struct {
+ Key string
+ Val V
+}
+type Dict[V any] struct {
+ s []Entry[V]
+ m map[string]int
+}
+
+func NewDict[V any]() *Dict[V] {
+ return &Dict[V]{
+ s: make([]Entry[V], 0),
+ m: make(map[string]int),
+ }
+}
+
+func (d *Dict[V]) Len() int {
+ return len(d.s)
+}
+
+func (d *Dict[V]) Set(key string, val V) {
+ if i, ok := d.m[key]; ok {
+ d.s[i].Val = val
+
+ return
+ }
+
+ d.s = append(d.s, Entry[V]{
+ Key: key,
+ Val: val,
+ })
+
+ d.m[key] = len(d.s) - 1
+}
+
+func (d *Dict[V]) Get(key string) (V, bool) {
+ i, ok := d.m[key]
+
+ if !ok {
+ var zero V
+
+ return zero, false
+ }
+
+ return d.s[i].Val, true
+}
+
+func (d *Dict[V]) GetBytes(key []byte) (V, bool) {
+ if i, ok := d.m[string(key)]; ok {
+ return d.s[i].Val, true
+ }
+
+ var zero V
+
+ return zero, false
+}
+
+func (d *Dict[V]) Values() iter.Seq2[int, V] {
+ return func(yield func(int, V) bool) {
+ for i, entry := range d.s {
+ if !yield(i, entry.Val) {
+ return
+ }
+ }
+ }
+}
+
+func (d *Dict[V]) Sort(cmp func(a, b Entry[V]) int) {
+ slices.SortFunc(d.s, cmp)
+
+ for i, entry := range d.s {
+ d.m[entry.Key] = i
+ }
+}
+
+// func CmpKey[V any](a, b Entry[V]) int {
+// return strings.Compare(a.Key, b.Key)
+// }
+
+// func CmpVal[V cmp.Ordered](a, b Entry[V]) int {
+// return cmp.Compare(a.Val, b.Val)
+// }