Documentation ¶
Overview ¶
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.
func (t T) Has(m T) bool func (t T) Set(m T) T func (t T) Clear(m T) T func (t T) Toggle(m T) T func (t T) String() string
The file is created in the same package and directory as the package that defines T. It has helpful defaults designed for use with go generate.
Bitmasker works with constants that are consecutive values created using bit-shifted iota.
For example, given this snippet,
package mental type State uint const ( Unconscious State = 0 Conscious State = (1 << iota) Meditative Distracted Entertained = Distracted )
running this command
bitmasker -type=State
in the same directory will create the file state_bitmask.go, in package mental, containing a definition of the following:
type IState interface { Has(m State) bool Set(m State) State Clear(m State) State Toggle(m State) State String() string } func (t State) Has(m State) bool func (t State) Set(m State) State func (t State) Clear(m State) State func (t State) Toggle(m State) State func (t State) String() string
The Has method will return true if the State t has the bitmask given as m.
The Add method will return a new State mask that includes the original mask combined with the given mask m.
The Rem method will return a new State mask that has the original mask with the given mask m removed from it's combined value.
The String method will translate the value of a State constant to the string representation of the respective constant name, satisfying the fmt.Stringer interface. A call to fmt.Print(mental.Entertained) will print the string "Distracted".
Typically this process would be run using go generate, like this:
//go:generate bitmasker -type=State
If multiple constants have the same value, the lexically first matching name will be used (in the example, Entertained will print as "Distracted").
With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.
The -type flag accepts a comma-separated list of types so a single run can generate methods for multiple types. The default output file is t_bitmask.go, where t is the lower-cased name of the first type listed. It can be overridden with the -output flag.