@@ -3,6 +3,9 @@ package multiaddr
3
3
import (
4
4
"bytes"
5
5
"encoding/hex"
6
+ "fmt"
7
+ "math"
8
+ "math/rand"
6
9
"testing"
7
10
8
11
"github.com/ipfs/go-cid"
@@ -785,3 +788,50 @@ func TestContains(t *testing.T) {
785
788
require .False (t , Contains (addrs , newMultiaddr (t , "/ip4/4.3.2.1/udp/1234/utp" )))
786
789
require .False (t , Contains (nil , a1 ))
787
790
}
791
+
792
+ func TestUniqueAddrs (t * testing.T ) {
793
+ tcpAddr := StringCast ("/ip4/127.0.0.1/tcp/1234" )
794
+ quicAddr := StringCast ("/ip4/127.0.0.1/udp/1234/quic-v1" )
795
+ wsAddr := StringCast ("/ip4/127.0.0.1/tcp/1234/ws" )
796
+
797
+ type testcase struct {
798
+ in , out []Multiaddr
799
+ }
800
+
801
+ for i , tc := range []testcase {
802
+ {in : nil , out : nil },
803
+ {in : []Multiaddr {tcpAddr }, out : []Multiaddr {tcpAddr }},
804
+ {in : []Multiaddr {tcpAddr , tcpAddr , tcpAddr }, out : []Multiaddr {tcpAddr }},
805
+ {in : []Multiaddr {tcpAddr , quicAddr , tcpAddr }, out : []Multiaddr {tcpAddr , quicAddr }},
806
+ {in : []Multiaddr {tcpAddr , quicAddr , wsAddr }, out : []Multiaddr {tcpAddr , quicAddr , wsAddr }},
807
+ } {
808
+ tc := tc
809
+ t .Run (fmt .Sprintf ("test %d" , i ), func (t * testing.T ) {
810
+ deduped := Unique (tc .in )
811
+ for _ , a := range tc .out {
812
+ require .Contains (t , deduped , a )
813
+ }
814
+ })
815
+ }
816
+ }
817
+
818
+ func BenchmarkUniqueAddrs (b * testing.B ) {
819
+ b .ReportAllocs ()
820
+ var addrs []Multiaddr
821
+ r := rand .New (rand .NewSource (1234 ))
822
+ for i := 0 ; i < 100 ; i ++ {
823
+ tcpAddr := StringCast (fmt .Sprintf ("/ip4/127.0.0.1/tcp/%d" , r .Intn (math .MaxUint16 )))
824
+ quicAddr := StringCast (fmt .Sprintf ("/ip4/127.0.0.1/udp/%d/quic-v1" , r .Intn (math .MaxUint16 )))
825
+ wsAddr := StringCast (fmt .Sprintf ("/ip4/127.0.0.1/tcp/%d/ws" , r .Intn (math .MaxUint16 )))
826
+ addrs = append (addrs , tcpAddr , tcpAddr , quicAddr , quicAddr , wsAddr )
827
+ }
828
+ for _ , sz := range []int {10 , 20 , 30 , 50 , 100 } {
829
+ b .Run (fmt .Sprintf ("%d" , sz ), func (b * testing.B ) {
830
+ items := make ([]Multiaddr , sz )
831
+ for i := 0 ; i < b .N ; i ++ {
832
+ copy (items , addrs [:sz ])
833
+ Unique (items )
834
+ }
835
+ })
836
+ }
837
+ }
0 commit comments