|
| 1 | +# Bit Flags |
| 2 | + |
| 3 | +A simple package to store up to 64 boolean flags in one uint field. |
| 4 | + |
| 5 | +Requires Go version 1.18+ (uses generics) |
| 6 | + |
| 7 | +For usage example see [example dir](example) |
| 8 | + |
| 9 | +```go |
| 10 | +import ( |
| 11 | + "strings" |
| 12 | + |
| 13 | + bf "github.com/goiste/bit_flags" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + Messages = 1 << iota // 1 |
| 18 | + Replies // 2 |
| 19 | + Likes // 4 |
| 20 | + NewArticles // ... powers of 2 |
| 21 | + News |
| 22 | + |
| 23 | + ByEmail |
| 24 | + BySms |
| 25 | + ByTelegram |
| 26 | + |
| 27 | + AllNotifications = Messages | Replies | Likes | NewArticles | News |
| 28 | + AllMethods = ByEmail | BySms | ByTelegram |
| 29 | +) |
| 30 | + |
| 31 | +type Notification struct { |
| 32 | + SomeOtherFields string |
| 33 | + Flags bf.BitFlags[uint8] |
| 34 | +} |
| 35 | + |
| 36 | +func New() *Notification { ... } |
| 37 | + |
| 38 | +func (n *Notification) SetDefaultFlags() { |
| 39 | + n.Flags.Set(Messages | Replies | Likes | ByEmail) |
| 40 | +} |
| 41 | + |
| 42 | +func (n *Notification) SetAll() { |
| 43 | + n.Flags.Set(AllNotifications | AllMethods) |
| 44 | +} |
| 45 | + |
| 46 | +func (n *Notification) SetNone() { |
| 47 | + n.Flags.Reset() |
| 48 | +} |
| 49 | + |
| 50 | +... |
| 51 | +``` |
| 52 | +[full notification.go](example/notification.go) |
| 53 | +```go |
| 54 | +func main() { |
| 55 | + ntf := notification.New() |
| 56 | + fmt.Println(ntf.Flags.Get()) // 39 |
| 57 | + fmt.Println(ntf.FlagsToString()) // Messages, Replies, Likes, By email |
| 58 | + |
| 59 | + ntf.Flags.Add(notification.News | notification.BySms) |
| 60 | + ntf.Flags.Remove(notification.Replies | notification.Likes) |
| 61 | + fmt.Println(ntf.FlagsToString()) // Messages, News, By email, By sms |
| 62 | + fmt.Println(ntf.HasFlag(notification.Messages)) // true |
| 63 | + fmt.Println(ntf.HasFlag(notification.Likes)) // false |
| 64 | + |
| 65 | + ntf.Flags.Reset() |
| 66 | + fmt.Println(ntf.Flags.Get()) // 0 |
| 67 | + fmt.Println(ntf.GetFlagsNames()) // [] |
| 68 | + |
| 69 | + ntf.SetAll() |
| 70 | + fmt.Println(ntf.Flags.Get()) // 255 |
| 71 | + fmt.Println(ntf.FlagsToString()) // Messages, Replies, Likes, New articles, News, By email, By sms, By telegram |
| 72 | +} |
| 73 | +``` |
| 74 | +[full main.go](example/main.go) |
0 commit comments