bitflags

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2025 License: MIT Imports: 3 Imported by: 0

README

bitflags

Go Reference

This covers a specific use-case for bit flags where:

  • You want the flags themselves defined separately.
  • You want to iterate over set values, and rely on exhaustive-switch linters to make you account for everything.
  • You want generic support for "safety" (convenience), and support any type with constraints.Unsigned storage.

A code block is worth 1000 words:

package main

import (
	"fmt"

	"github.com/coxley/bitflags"
)

type perms uint8

const (
	read perms = 1 << iota
	write
	exec
)

func main() {
	var flags bitflags.Set[perms]
	flags.Add(read, exec)    // alt: bitflags.NewSet(read, exec)
	flags.HasAll(read, exec) // true
	flags.Has(write)         // false

	// Output:
	//   read: set
	//   exec: set
	for flag := range flags.All() {
		switch flag {
		case read:
			fmt.Println("read: set")
		case write:
			fmt.Println("write: set")
		case exec:
			fmt.Println("exec: set")
		}
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidateFlags

func ValidateFlags(enabled bool)

ValidateFlags will panic when flag values are not on bit boundaries when enabled.

Types

type Set

type Set[T constraints.Unsigned] struct {
	// contains filtered or unexported fields
}

Set is a helper for operating over a custom bit flag

The zero value is ready to use

func NewSet

func NewSet[T constraints.Unsigned](flag T, extra ...T) Set[T]

NewSet returns a set with the provided flags set

func (*Set[T]) Add

func (f *Set[T]) Add(flag T, extra ...T)

Add one or more flags to the set

Panics if any value is not on a bit-boundary to protect against misuse.

func (Set[T]) All

func (f Set[T]) All() iter.Seq[T]

All produces each flag that is currently set

func (*Set[T]) Clear

func (f *Set[T]) Clear(flag T, extra ...T)

Clear one or more flags from the set

Panics if any value is not on a bit-boundary to protect against misuse.

func (Set[T]) Empty

func (f Set[T]) Empty() bool

func (Set[T]) Has

func (f Set[T]) Has(flag T) bool

Has the flag been set?

Panics if any value is not on a bit-boundary to protect against misuse.

func (Set[T]) HasAll

func (f Set[T]) HasAll(flag T, extra ...T) bool

HasAll returns true if all provided flags are set

Panics if any value is not on a bit-boundary to protect against misuse.

func (Set[T]) Merge

func (f Set[T]) Merge(flags Set[T]) Set[T]

Merge flags together and return as a new value

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL