From 6f663b0bc1d9fcc6bbdfbb37c28d912ee267d98b Mon Sep 17 00:00:00 2001 From: Alexander Demidenko Date: Thu, 14 Dec 2023 14:45:46 +0300 Subject: [PATCH] fix for deleting the last element --- ring.go | 26 +++++++++++++++++--------- ring_test.go | 11 +++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/ring.go b/ring.go index 38dc2b5..3408b47 100644 --- a/ring.go +++ b/ring.go @@ -14,9 +14,9 @@ import ( const DefaultMagicFactor = 1020 -type Item interface { - io.WriterTo -} +// this will allow you to have multiple hashring implementations +// in a third-party project +type Item = io.WriterTo // Ring is a consistent hashing hashring. // It is goroutine safe. Ring instances must not be copied. @@ -329,19 +329,27 @@ func (r *Ring) deletePoint(tree avl.Tree, p *point) (_ avl.Tree, removed bool) { return tree, true } -func (r *Ring) magicFactor() int { +func (r *Ring) magicFactor() float64 { if m := r.MagicFactor; m > 0 { - return m + return float64(m) } return DefaultMagicFactor } // r.mu must be held. -func (r *Ring) rebuild() { - numPoints := line( - r.maxWeight, float64(r.magicFactor()), - r.minWeight, math.Ceil(float64(r.magicFactor())*(r.minWeight/r.maxWeight)), +func (r *Ring) numPoints() func(float64) int { + if r.maxWeight == 0 { + return func(float64) int { return 0 } + } + return line( + r.maxWeight, r.magicFactor(), + r.minWeight, math.Ceil(r.magicFactor())*(r.minWeight/r.maxWeight), ) +} + +// r.mu must be held. +func (r *Ring) rebuild() { + numPoints := r.numPoints() r.ringMu.RLock() root := r.ring diff --git a/ring_test.go b/ring_test.go index 7b88996..6e29781 100644 --- a/ring_test.go +++ b/ring_test.go @@ -321,6 +321,17 @@ func TestRingDeleteNotExisting(t *testing.T) { } } +func TestRingInsertDelete(t *testing.T) { + var r Ring + x := StringItem("foo") + if err := r.Insert(x, 1); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if err := r.Delete(x); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + func TestRingUpdateNotExisting(t *testing.T) { var r Ring x := StringItem("foo")