chore: a better fix to portunion

This commit is contained in:
Haruue 2024-11-05 01:30:44 +09:00
parent a9422e63be
commit 9a21e2e8c6
No known key found for this signature in database
GPG key ID: F6083B28CBCBC148
2 changed files with 13 additions and 7 deletions

View file

@ -1,7 +1,6 @@
package utils
import (
"math"
"sort"
"strconv"
"strings"
@ -75,7 +74,7 @@ func (u PortUnion) Normalize() PortUnion {
normalized := PortUnion{u[0]}
for _, current := range u[1:] {
last := &normalized[len(normalized)-1]
if current.Start <= last.End+1 {
if uint32(current.Start) <= uint32(last.End)+1 {
if current.End > last.End {
last.End = current.End
}
@ -90,11 +89,8 @@ func (u PortUnion) Normalize() PortUnion {
func (u PortUnion) Ports() []uint16 {
var ports []uint16
for _, r := range u {
for i := r.Start; i <= r.End; i++ {
ports = append(ports, i)
if i == math.MaxUint16 {
break
}
for i := uint32(r.Start); i <= uint32(r.End); i++ {
ports = append(ports, uint16(i))
}
}
return ports

View file

@ -52,6 +52,16 @@ func TestParsePortUnion(t *testing.T) {
s: "5678,1200-1236,9100-9012,1234-1240",
want: PortUnion{{1200, 1240}, {5678, 5678}, {9012, 9100}},
},
{
name: "multiple ports and ranges with 65535 (reversed, unsorted, overlapping)",
s: "5678,1200-1236,65531-65535,65532-65534,9100-9012,1234-1240",
want: PortUnion{{1200, 1240}, {5678, 5678}, {9012, 9100}, {65531, 65535}},
},
{
name: "multiple ports and ranges with 65535 (reversed, unsorted, overlapping) 2",
s: "5678,1200-1236,65532-65535,65531-65534,9100-9012,1234-1240",
want: PortUnion{{1200, 1240}, {5678, 5678}, {9012, 9100}, {65531, 65535}},
},
{
name: "invalid 1",
s: "1234-",