From b73fc2dd314b63759e6449fd7e5fa1cbdd57a405 Mon Sep 17 00:00:00 2001 From: Sergey Elantsev Date: Wed, 1 Nov 2023 17:01:59 +0300 Subject: [PATCH] added method to check if key is present in ring --- ring.go | 10 ++++++++++ ring_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/ring.go b/ring.go index 0aef9ab..d4c2cdf 100644 --- a/ring.go +++ b/ring.go @@ -142,6 +142,16 @@ func (r *Ring) Get(v Item) Item { return item.(*point).bucket.item } +func (r *Ring) Has(x Item) bool { + d := r.digest(x) + + r.ringMu.RLock() + defer r.ringMu.RUnlock() + + _, has := r.buckets[d] + return has +} + func (r *Ring) update(x Item, w float64) error { id := r.digest(x) diff --git a/ring_test.go b/ring_test.go index e1e9fa2..7b88996 100644 --- a/ring_test.go +++ b/ring_test.go @@ -551,6 +551,30 @@ func TestRingCollisions(t *testing.T) { } } +func TestRingHas(t *testing.T) { + var ring Ring + + if ring.Has(StringItem("server01")) { + t.Error("has server on empty ring") + } + + ring.Insert(StringItem("server01"), 1.0) + if !ring.Has(StringItem("server01")) { + t.Error("failed to find server") + } + if ring.Has(StringItem("key")) { + t.Error("ring has not inserted key") + } + + ring.Insert(StringItem("key"), 1.0) + if !ring.Has(StringItem("server01")) { + t.Error("failed to find server") + } + if !ring.Has(StringItem("key")) { + t.Error("failed to find key") + } +} + func applyActions(t testing.TB, r *Ring, actions ...ringAction) { for _, a := range actions { if err := a.apply(r); err != nil {