-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
3 changed files
with
52 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# bitmask | ||
|
||
Simple utilities for working with bitmasks. Built with generics so any form of unsigned or signed integer is supported. |
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,26 @@ | ||
package bitmask | ||
|
||
import "golang.org/x/exp/constraints" | ||
|
||
// Bit is a generic type that exports the supported values that can be used in the bitmask. | ||
// Any form of integer is currently supported. | ||
type Bit interface { | ||
constraints.Integer | ||
} | ||
|
||
// Add adds a given bit to the sum. | ||
func Add[T Bit](sum, bit T) T { | ||
sum |= bit | ||
return sum | ||
} | ||
|
||
// Remove removes bit from the sum. | ||
func Remove[T Bit](sum, bit T) T { | ||
sum &= ^bit | ||
return sum | ||
} | ||
|
||
// Has checks whether a given bit exists in sum. | ||
func Has[T Bit](sum, bit T) bool { | ||
return (sum & bit) == bit | ||
} |
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,23 @@ | ||
package bitmask_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/aidenwallis/go-utils/bitmask" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestBits(t *testing.T) { | ||
t.Parallel() | ||
|
||
const ( | ||
a = 1 << 0 | ||
b = 1 << 1 | ||
c = 1 << 2 | ||
) | ||
|
||
assert.Equal(t, a|b, bitmask.Add(a, b)) | ||
assert.Equal(t, a, bitmask.Remove(a|b, b)) | ||
assert.True(t, bitmask.Has(a|b, b)) | ||
assert.False(t, bitmask.Has(a|b, c)) | ||
} |