Add IsNarrowerThan() function to socketmask abstraction

k3s-v1.15.3
Kevin Klues 2019-05-30 04:15:36 -07:00
parent cdb59d3c7a
commit 0a43d21c26
2 changed files with 57 additions and 0 deletions

View File

@ -31,6 +31,7 @@ type SocketMask interface {
IsEqual(mask SocketMask) bool
IsEmpty() bool
IsSet(socket int) bool
IsNarrowerThan(mask SocketMask) bool
String() string
Count() int
GetSockets() []int
@ -116,6 +117,20 @@ func (s *socketMask) IsEqual(mask SocketMask) bool {
return *s == *mask.(*socketMask)
}
// IsNarrowerThan checks if one mask is narrower than another.
//
// A mask is said to be "narrower" than another if it has lets bits set. If the
// same number of bits are set in both masks, then the mask with more
// lower-numbered bits set wins out.
func (s *socketMask) IsNarrowerThan(mask SocketMask) bool {
if s.Count() == mask.Count() {
if *s < *mask.(*socketMask) {
return true
}
}
return s.Count() < mask.Count()
}
//String converts mask to string
func (s *socketMask) String() string {
str := ""

View File

@ -288,3 +288,45 @@ func TestGetSockets(t *testing.T) {
}
}
}
func TestIsNarrowerThan(t *testing.T) {
tcases := []struct {
name string
firstMask []int
secondMask []int
expectedFirstNarrower bool
}{
{
name: "Check narrowness of masks with unequal bits set 1/2",
firstMask: []int{0},
secondMask: []int{0, 1},
expectedFirstNarrower: true,
},
{
name: "Check narrowness of masks with unequal bits set 2/2",
firstMask: []int{0, 1},
secondMask: []int{0},
expectedFirstNarrower: false,
},
{
name: "Check narrowness of masks with equal bits set 1/2",
firstMask: []int{0},
secondMask: []int{1},
expectedFirstNarrower: true,
},
{
name: "Check narrowness of masks with equal bits set 2/2",
firstMask: []int{1},
secondMask: []int{0},
expectedFirstNarrower: false,
},
}
for _, tc := range tcases {
firstMask, _ := NewSocketMask(tc.firstMask...)
secondMask, _ := NewSocketMask(tc.secondMask...)
expectedFirstNarrower := firstMask.IsNarrowerThan(secondMask)
if expectedFirstNarrower != tc.expectedFirstNarrower {
t.Errorf("Expected value to be %v, got %v", tc.expectedFirstNarrower, expectedFirstNarrower)
}
}
}