Skip to content

Commit

Permalink
Merge pull request #161 from jingyuanliang/int
Browse files Browse the repository at this point in the history
Implement pkg/interval in preparation for --to-ports
  • Loading branch information
k8s-ci-robot authored Oct 15, 2024
2 parents abca88e + cba214a commit 342f661
Show file tree
Hide file tree
Showing 3 changed files with 471 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module k8s.io/ip-masq-agent
go 1.23

require (
github.com/google/go-cmp v0.6.0
k8s.io/apimachinery v0.29.1
k8s.io/component-base v0.29.1
k8s.io/klog/v2 v2.110.1
Expand All @@ -17,7 +18,6 @@ require (
github.com/go-logr/logr v1.3.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
Expand Down
82 changes: 82 additions & 0 deletions pkg/interval/interval.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package interval

import (
"fmt"
"strconv"
"strings"
)

type Interval struct {
First int
Last int
}

func (i Interval) Size() int {
return max(0, i.Last-i.First+1)
}

func (i Interval) String() string {
if i.First < 0 || i.Last < i.First {
return ""
}
if i.First == i.Last {
return strconv.Itoa(i.First)
}
return fmt.Sprintf("%d-%d", i.First, i.Last)
}

func ParseInterval(s string) (Interval, error) {
var i Interval

p := strings.Split(s, "-")
if len(p) > 2 {
return i, fmt.Errorf("invalid interval %q", s)
}

v, err := strconv.Atoi(p[0])
if err != nil {
return i, err
}
i.First = v

if len(p) == 1 {
i.Last = v
return i, nil
}

v, err = strconv.Atoi(p[1])
if err != nil {
return i, err
}
i.Last = v

if i.First > i.Last {
return i, fmt.Errorf("first is greater than last in %q", s)
}
return i, nil
}

type Intervals []Interval

func (i Intervals) Size() int {
var size int
for _, j := range i {
size += j.Size()
}
return size
}

func ParseIntervals(s string) (Intervals, error) {
var is Intervals

for _, p := range strings.Split(s, ",") {
i, err := ParseInterval(p)
if err != nil {
return is, err
}

is = append(is, i)
}

return is, nil
}
Loading

0 comments on commit 342f661

Please sign in to comment.