Fix couple nasty bugs in collection.go, safer type assertions.

This commit is contained in:
eleksir
2026-03-30 23:49:06 +03:00
parent 9bea626f7c
commit 63f1a142d8

View File

@@ -7,7 +7,6 @@ import (
// Collection is sync.Map, that stores arbitrary data. // Collection is sync.Map, that stores arbitrary data.
type Collection struct { type Collection struct {
items sync.Map items sync.Map
close chan struct{}
} }
// Item just interface for stoing any data. // Item just interface for stoing any data.
@@ -17,9 +16,7 @@ type item struct {
// NewCollection creates new instance of "collection". // NewCollection creates new instance of "collection".
func NewCollection() *Collection { func NewCollection() *Collection {
c := &Collection{ //nolint:exhaustruct c := &Collection{}
close: make(chan struct{}),
}
return c return c
} }
@@ -32,9 +29,12 @@ func (collection *Collection) Get(key any) (any, bool) {
return nil, false return nil, false
} }
item := obj.(item) it, ok := obj.(item)
if !ok {
return nil, false
}
return item.data, true return it.data, true
} }
// Set saves value to given "collection". // Set saves value to given "collection".
@@ -47,9 +47,12 @@ func (collection *Collection) Set(key any, value any) {
// Range apply function f to all keys/values in collection. Retuns immediatly on first error. // Range apply function f to all keys/values in collection. Retuns immediatly on first error.
func (collection *Collection) Range(f func(key, value any) bool) { func (collection *Collection) Range(f func(key, value any) bool) {
fn := func(key, value any) bool { fn := func(key, value any) bool {
item := value.(item) it, ok := value.(item)
if !ok {
return true
}
return f(key, item.data) return f(key, it.data)
} }
collection.items.Range(fn) collection.items.Range(fn)
@@ -62,7 +65,6 @@ func (collection *Collection) Delete(key any) {
// Close frees memory occupied by collection and deletes collection itself. // Close frees memory occupied by collection and deletes collection itself.
func (collection *Collection) Close() { func (collection *Collection) Close() {
collection.close <- struct{}{}
collection.items = sync.Map{} collection.items = sync.Map{}
} }