Skip to content

Commit

Permalink
Add bitmask utils (#15)
Browse files Browse the repository at this point in the history
* Add bitmask utils

* Create README.md
  • Loading branch information
aidenwallis authored Nov 11, 2022
1 parent ae8fff4 commit a39133d
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
3 changes: 3 additions & 0 deletions bitmask/README.md
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.
26 changes: 26 additions & 0 deletions bitmask/bitmask.go
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
}
23 changes: 23 additions & 0 deletions bitmask/bitmask_test.go
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))
}

0 comments on commit a39133d

Please sign in to comment.