65 lines
902 B
Go
65 lines
902 B
Go
package types
|
|
|
|
/*
|
|
See https://yourbasic.org/golang/bitmask-flag-set-clear/ for more information.
|
|
To use this, set constants like thus:
|
|
|
|
const (
|
|
OPT1 types.MaskBit = 1 << iota
|
|
OPT2
|
|
OPT3
|
|
// ...
|
|
)
|
|
|
|
type Object struct {
|
|
Opts BitMask
|
|
}
|
|
|
|
o := Object{
|
|
BitMask: uint8(0)
|
|
}
|
|
|
|
o.AddFlag(OPT1)
|
|
o.AddFlag(OPT3)
|
|
|
|
|
|
This would return true:
|
|
o.HasFlag(OPT1)
|
|
As would this:
|
|
o.HasFlag(OPT3)
|
|
But this would return false:
|
|
o.HasFlag(OPT2)
|
|
|
|
*/
|
|
type BitMask interface {
|
|
HasFlag(bit MaskBit) bool
|
|
AddFlag(bit MaskBit)
|
|
ClearFlag(bit MaskBit)
|
|
ToggleFlag(bit MaskBit)
|
|
}
|
|
|
|
// BitMasks
|
|
type MaskBit uint8
|
|
|
|
func (f MaskBit) HasFlag(flag MaskBit) (r bool) {
|
|
if f&flag != 0 {
|
|
r = true
|
|
}
|
|
return
|
|
}
|
|
|
|
func (f *MaskBit) AddFlag(flag MaskBit) {
|
|
*f |= flag
|
|
return
|
|
}
|
|
|
|
func (f *MaskBit) ClearFlag(flag MaskBit) {
|
|
*f &= flag
|
|
return
|
|
}
|
|
|
|
func (f *MaskBit) ToggleFlag(flag MaskBit) {
|
|
*f ^= flag
|
|
return
|
|
}
|