forked from kubernetes-sigs/ip-masq-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement pkg/interval in preparation for --to-ports
- Loading branch information
1 parent
abca88e
commit 00206de
Showing
3 changed files
with
398 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
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 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 | ||
} |
Oops, something went wrong.