constant-time lookups for tag inserts

This commit is contained in:
David 2021-10-09 16:47:01 -04:00
parent dca7ed3387
commit 866111f54c

View File

@ -11,20 +11,24 @@ type Tag struct {
Value string 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 { type Tags struct {
kv map[string]int // quick lookups for inserts
tags []Tag tags []Tag
} }
func (t *Tags) Insert(new Tag) { func (t *Tags) Insert(new Tag) {
for i := range t.tags { if t.kv == nil {
if t.tags[i].Key == new.Key { t.kv = map[string]int{}
}
i, ok := t.kv[new.Key]
if ok {
t.tags[i] = new t.tags[i] = new
return } 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 { func (t *Tags) GetSlice() []Tag {
return t.tags return t.tags