github.com/database64128/shadowsocks-go@v1.10.2-0.20240315062903-143a773533f1/portset/range_test.go (about) 1 package portset 2 3 import ( 4 "strconv" 5 "testing" 6 ) 7 8 func TestPortRangeContains(t *testing.T) { 9 r := PortRange{From: 16384, To: 32768} 10 for i := uint(1); i < 16384; i++ { 11 if r.Contains(uint16(i)) { 12 t.Errorf("contains unexpected port %d", i) 13 } 14 } 15 for i := uint(16384); i <= 32768; i++ { 16 if !r.Contains(uint16(i)) { 17 t.Errorf("expected port %d to be in range", i) 18 } 19 } 20 for i := uint(32769); i < 65536; i++ { 21 if r.Contains(uint16(i)) { 22 t.Errorf("contains unexpected port %d", i) 23 } 24 } 25 } 26 27 // portRangeSetContains is a test helper function that uses linear search and 28 // [PortRange.Contains] to determine whether the given port is in the port range set. 29 func portRangeSetContains(s PortRangeSet, port uint16) bool { 30 for _, r := range s.ranges { 31 if r.Contains(port) { 32 return true 33 } 34 } 35 return false 36 } 37 38 func testPortRangeSetContains(t *testing.T, s PortRangeSet) { 39 for i := uint(1); i < 65536; i++ { 40 binarySearchContains := s.Contains(uint16(i)) 41 linearSearchContains := portRangeSetContains(s, uint16(i)) 42 if binarySearchContains != linearSearchContains { 43 t.Errorf("mismatched results for port %d: binary search says %t, linear search says %t", i, binarySearchContains, linearSearchContains) 44 } 45 } 46 } 47 48 func TestPortRangeSetContains(t *testing.T) { 49 testPortRangeSets := [...]PortRangeSet{ 50 {}, 51 {ranges: []PortRange{{From: 4096, To: 8192}}}, 52 {ranges: []PortRange{{From: 4096, To: 8192}, {From: 12288, To: 16384}}}, 53 {ranges: []PortRange{{From: 4096, To: 8192}, {From: 12288, To: 16384}, {From: 20480, To: 24576}}}, 54 {ranges: []PortRange{{From: 4096, To: 8192}, {From: 12288, To: 16384}, {From: 20480, To: 24576}, {From: 28672, To: 32768}}}, 55 } 56 for i, s := range testPortRangeSets { 57 t.Run(strconv.Itoa(i), func(t *testing.T) { 58 testPortRangeSetContains(t, s) 59 }) 60 } 61 }