Skip to content

Commit

Permalink
Refactor for a simplified implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
thegeekyasian authored Feb 9, 2023
1 parent 15bcaa6 commit ee0e2ad
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions round_robin.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,30 @@ import (
// ErrorNoObjectsProvided is the error that occurs when no objects are provided.
var ErrorNoObjectsProvided = errors.New("no objects provided")

// RoundRobin is an interface for representing round-robin balancing.
type RoundRobin[O any] interface {
Next() *O
}

type roundrobin[O any] struct {
type RoundRobin[O any] struct {
objects []*O
next uint32
}

// New returns RoundRobin implementation with roundrobin.
func New[O any](objects ...*O) (RoundRobin[O], error) {
func New[O any](objects ...*O) (*RoundRobin[O], error) {
if len(objects) == 0 {
return nil, ErrorNoObjectsProvided
}

return &roundrobin[O]{
return &RoundRobin[O]{
objects: objects,
}, nil
}

// Next returns the next object.
func (r *roundrobin[O]) Next() *O {
func (r *RoundRobin[O]) Next() *O {
n := atomic.AddUint32(&r.next, 1)

if int(n) > len(r.objects) {
atomic.StoreUint32(&r.next, 0)
n = 1
}
return r.objects[(int(n)-1)%len(r.objects)]
}

0 comments on commit ee0e2ad

Please sign in to comment.