Bitmasker is a tool used to automate the creation of helper methods when dealing with bitmask-type constant flags. Given the name of an unsigned integer type T that has constants defined, bitmasker will create a new self-contained Go source file implementing the BitMask and fmt.Stringer interfaces.
To get up and running, follow the normal go install procedure:
go install github.com/go-curses/bitmasker
Bitmasker is intended to be used with go:generate but can operated standalone as well. For example:
Given this snippet:
package mental
//go:generate bitmasker -type=State
type State uint
const (
Unconscious State = 0
Conscious State = 1 << iota
Meditative
Distracted
Entertained = Distracted
)
Standalone usage:
bitmasker -type=State
Using go-generate
go generate
In both cases a new file named "state_bitmask.go" will be created with the following contents:
// Code generated by "bitmasker -type=State"; DO NOT EDIT.
package mental
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the bitmasker command to generate them again.
var x [1]struct{}
_ = x[Unconscious-0]
_ = x[Conscious-2]
_ = x[Meditative-4]
_ = x[Distracted-8]
}
const (
_State_name_0 = "Unconscious"
_State_name_1 = "Conscious"
_State_name_2 = "Meditative"
_State_name_3 = "Distracted"
)
func (i State) String() (value string) {
update := func(t State, n string) {
if i.Has(t) {
if len(value) > 0 {
value += " | "
}
value += n
}
}
update(State(0), _State_name_0)
update(State(2), _State_name_1)
update(State(4), _State_name_2)
update(State(8), _State_name_3)
if value == "" {
return "State(" + strconv.FormatInt(int64(i), 10) + ")"
}
return
}
// Has returns TRUE if the given flag is present in the bitmask
func (i State) Has(m State) bool {
if i == m {
return true
}
return i&m != 0
}
// Set returns the bitmask with the given flag set
func (i State) Set(m State) State {
return i | m
}
// Clear returns the bitmask with the given flag removed
func (i State) Clear(m State) State {
return i &^ m
}
// Toggle returns the bitmask with the given flag toggled
func (i State) Toggle(m State) State {
return i ^ m
}
Unit tests are provided and can be invoked using the normal Go pattern:
go test
This project is licensed under the LGPL (specifically v3) - see the LICENSE.md file for details.
- Thanks to Golang.org for the stringer program that bitmasker sources are derived from.