Skip to content

Commit

Permalink
add bitmask.Toggle (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
aidenwallis authored Nov 13, 2022
1 parent 173d076 commit 5cc8072
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
8 changes: 8 additions & 0 deletions bitmask/bitmask.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,11 @@ func Remove[T Bit](sum, bit T) T {
func Has[T Bit](sum, bit T) bool {
return (sum & bit) == bit
}

// Toggle will either add or remove bit from sum depending on whether it currently exists in the bitmask.
func Toggle[T Bit](sum, bit T) T {
if Has(sum, bit) {
return Remove(sum, bit)
}
return Add(sum, bit)
}
3 changes: 3 additions & 0 deletions bitmask/bitmask_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,7 @@ func TestBits(t *testing.T) {
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))

assert.Equal(t, a|b, bitmask.Toggle(a, b))
assert.Equal(t, b, bitmask.Toggle(a|b, a))
}

0 comments on commit 5cc8072

Please sign in to comment.