constant-time lookups for tag inserts

This commit is contained in:
David 2021-10-09 16:47:01 -04:00
parent dca7ed3387
commit 866111f54c
1 changed files with 11 additions and 7 deletions

View File

@ -11,19 +11,23 @@ type Tag struct {
Value string
}
// Tags is an key-order-preserving, last-insert-wins slice
// Tags is an key-order-preserving, last-insert-wins "set" of Tag
type Tags struct {
kv map[string]int // quick lookups for inserts
tags []Tag
}
func (t *Tags) Insert(new Tag) {
for i := range t.tags {
if t.tags[i].Key == new.Key {
t.tags[i] = new
return
}
if t.kv == nil {
t.kv = map[string]int{}
}
i, ok := t.kv[new.Key]
if ok {
t.tags[i] = new
} else {
t.kv[new.Key] = len(t.tags)
t.tags = append(t.tags, new)
}
t.tags = append(t.tags, new)
}
func (t *Tags) GetSlice() []Tag {