Skip to content

Commit

Permalink
fix for deleting the last element
Browse files Browse the repository at this point in the history
  • Loading branch information
hurd54 committed Dec 14, 2023
1 parent 7825400 commit 6f663b0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
26 changes: 17 additions & 9 deletions ring.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions ring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 6f663b0

Please sign in to comment.