From a39133d370224023932fdd73119c3940db4149cc Mon Sep 17 00:00:00 2001 From: Aiden <12055114+aidenwallis@users.noreply.github.com> Date: Fri, 11 Nov 2022 01:40:09 +0000 Subject: [PATCH] Add bitmask utils (#15) * Add bitmask utils * Create README.md --- bitmask/README.md | 3 +++ bitmask/bitmask.go | 26 ++++++++++++++++++++++++++ bitmask/bitmask_test.go | 23 +++++++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 bitmask/README.md create mode 100644 bitmask/bitmask.go create mode 100644 bitmask/bitmask_test.go diff --git a/bitmask/README.md b/bitmask/README.md new file mode 100644 index 0000000..e1346ac --- /dev/null +++ b/bitmask/README.md @@ -0,0 +1,3 @@ +# bitmask + +Simple utilities for working with bitmasks. Built with generics so any form of unsigned or signed integer is supported. diff --git a/bitmask/bitmask.go b/bitmask/bitmask.go new file mode 100644 index 0000000..4871909 --- /dev/null +++ b/bitmask/bitmask.go @@ -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 +} diff --git a/bitmask/bitmask_test.go b/bitmask/bitmask_test.go new file mode 100644 index 0000000..03a2b1c --- /dev/null +++ b/bitmask/bitmask_test.go @@ -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)) +}