[#607] network: Sort addresses in AddressGroup.FromIterator method

Implement `sort.Interface` interface on `AddressGroup` and perform sorting
in `AddressGroup.FromIterator` method. Addresses with enabled TLS are "less"
in terms of slice position.

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2021-06-23 12:17:37 +03:00 committed by Leonard Lyubich
parent 1e52e86bbc
commit 149367cab9

View file

@ -2,6 +2,7 @@ package network
import ( import (
"errors" "errors"
"sort"
"github.com/nspcc-dev/neofs-api-go/pkg/netmap" "github.com/nspcc-dev/neofs-api-go/pkg/netmap"
) )
@ -39,6 +40,22 @@ func (x AddressGroup) IterateAddresses(f func(Address) bool) {
} }
} }
// Len returns number of addresses in AddressGroup.
func (x AddressGroup) Len() int {
return len(x)
}
// Less returns true if i-th address in AddressGroup supports TLS
// and j-th one doesn't.
func (x AddressGroup) Less(i, j int) bool {
return x[i].TLSEnabled() && !x[j].TLSEnabled()
}
// Swap swaps i-th and j-th addresses in AddressGroup.
func (x AddressGroup) Swap(i, j int) {
x[i], x[j] = x[j], x[i]
}
// MultiAddressIterator is an interface of network address group. // MultiAddressIterator is an interface of network address group.
type MultiAddressIterator interface { type MultiAddressIterator interface {
// Must iterate over network addresses and pass each one // Must iterate over network addresses and pass each one
@ -50,6 +67,7 @@ type MultiAddressIterator interface {
} }
// FromIterator forms AddressGroup from MultiAddressIterator structure. // FromIterator forms AddressGroup from MultiAddressIterator structure.
// The result is sorted with sort.Sort.
// //
// Returns an error in the absence of addresses or if any of the addresses are incorrect. // Returns an error in the absence of addresses or if any of the addresses are incorrect.
func (x *AddressGroup) FromIterator(iter MultiAddressIterator) (err error) { func (x *AddressGroup) FromIterator(iter MultiAddressIterator) (err error) {
@ -81,6 +99,7 @@ func (x *AddressGroup) FromIterator(iter MultiAddressIterator) (err error) {
}) })
if err == nil { if err == nil {
sort.Sort(as)
*x = as *x = as
} }