set: Allow nil/expired items

Fixes #397
This commit is contained in:
mik2k2 2021-07-03 19:37:09 +02:00 committed by GitHub
parent 7413539965
commit 7628a47c4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 18 deletions

View File

@ -12,9 +12,6 @@ var ErrCollision = errors.New("key already exists")
// Returned when a requested item does not exist in the set.
var ErrMissing = errors.New("item does not exist")
// Returned when a nil item is added. Nil values are considered expired and invalid.
var ErrNil = errors.New("item value must not be nil")
// ZeroValue can be used when we only care about the key, not about the value.
var ZeroValue = struct{}{}
@ -100,7 +97,7 @@ func (s *Set) Get(key string) (Item, error) {
func (s *Set) cleanup(key string) {
s.Lock()
item, ok := s.lookup[key]
if ok && item == nil {
if ok && item.Value() == nil {
delete(s.lookup, key)
}
s.Unlock()
@ -108,9 +105,6 @@ func (s *Set) cleanup(key string) {
// Add item to this set if it does not exist already.
func (s *Set) Add(item Item) error {
if item.Value() == nil {
return ErrNil
}
key := s.normalize(item.Key())
s.Lock()
@ -127,9 +121,6 @@ func (s *Set) Add(item Item) error {
// Set item to this set, even if it already exists.
func (s *Set) Set(item Item) error {
if item.Value() == nil {
return ErrNil
}
key := s.normalize(item.Key())
s.Lock()
@ -156,9 +147,6 @@ func (s *Set) Remove(key string) error {
// Replace oldKey with a new item, which might be a new key.
// Can be used to rename items.
func (s *Set) Replace(oldKey string, item Item) error {
if item.Value() == nil {
return ErrNil
}
newKey := s.normalize(item.Key())
oldKey = s.normalize(oldKey)

View File

@ -21,14 +21,23 @@ func TestSetExpiring(t *testing.T) {
t.Error("not len 1 after set")
}
item := &ExpiringItem{nil, time.Now().Add(-time.Nanosecond * 1)}
item := Expire(StringItem("asdf"), -time.Nanosecond).(*ExpiringItem)
if !item.Expired() {
t.Errorf("ExpiringItem a nanosec ago is not expiring")
}
if err := s.Add(item); err != nil {
t.Error("Error adding expired item to set: ", err)
}
if s.In("asdf") {
t.Error("Expired item in set")
}
if s.Len() != 1 {
t.Error("not len 1 after expired item")
}
item = &ExpiringItem{nil, time.Now().Add(time.Minute * 5)}
if item.Expired() {
t.Errorf("ExpiringItem in 2 minutes is expiring now")
t.Errorf("ExpiringItem in 5 minutes is expiring now")
}
item = Expire(StringItem("bar"), time.Minute*5).(*ExpiringItem)
@ -42,11 +51,13 @@ func TestSetExpiring(t *testing.T) {
if err := s.Add(item); err != nil {
t.Fatalf("failed to add item: %s", err)
}
_, ok := s.lookup["bar"]
itemInLookup, ok := s.lookup["bar"]
if !ok {
t.Fatalf("expired bar added to lookup")
t.Fatalf("bar not present in lookup even though it's not expired")
}
if itemInLookup != item {
t.Fatalf("present item %#v != %#v original item", itemInLookup, item)
}
s.lookup["bar"] = item
if !s.In("bar") {
t.Errorf("not matched after timed set")