Skip to content

Commit

Permalink
client: imp code
Browse files Browse the repository at this point in the history
  • Loading branch information
schzhn committed May 6, 2024
1 parent 54212e9 commit 7faddd8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 17 deletions.
19 changes: 7 additions & 12 deletions internal/client/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,14 +337,13 @@ func (ci *Index) Range(f func(c *Persistent) (cont bool)) {
}
}

// SortedRange is like [Index.Range] but sorts the keys before iterating
// ensuring a predictable order.
func (ci *Index) SortedRange(
s func(a, b *Persistent) (n int),
f func(c *Persistent) (cont bool),
) {
// RangeByName is like [Index.Range] but sorts the persistent clients by name
// before iterating ensuring a predictable order.
func (ci *Index) RangeByName(f func(c *Persistent) (cont bool)) {
cs := maps.Values(ci.uidToClient)
slices.SortFunc(cs, s)
slices.SortFunc(cs, func(a, b *Persistent) (n int) {
return strings.Compare(a.Name, b.Name)
})

for _, c := range cs {
if !f(c) {
Expand All @@ -355,12 +354,8 @@ func (ci *Index) SortedRange(

// CloseUpstreams closes upstream configurations of persistent clients.
func (ci *Index) CloseUpstreams() (err error) {
sortFunc := func(a, b *Persistent) (n int) {
return strings.Compare(a.Name, b.Name)
}

var errs []error
ci.SortedRange(sortFunc, func(c *Persistent) (cont bool) {
ci.RangeByName(func(c *Persistent) (cont bool) {
err = c.CloseUpstreams()
if err != nil {
errs = append(errs, err)
Expand Down
8 changes: 3 additions & 5 deletions internal/client/index_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,12 @@ func TestClientIndex(t *testing.T) {
})

t.Run("sorted_range", func(t *testing.T) {
sortFunc := func(a, b *Persistent) (n int) {
slices.SortFunc(clients, func(a, b *Persistent) (n int) {
return strings.Compare(a.Name, b.Name)
}

slices.SortFunc(clients, sortFunc)
})

got := []*Persistent{}
ci.SortedRange(sortFunc, func(c *Persistent) (cont bool) {
ci.RangeByName(func(c *Persistent) (cont bool) {
got = append(got, c)

return true
Expand Down

0 comments on commit 7faddd8

Please sign in to comment.