Skip to content
/ flagged Public

Overthinking per-bool size overhead? Turn bool-heavy structs into compact, typed bitflags for Go — fast, zero-alloc, and go:generate–friendly.

License

Notifications You must be signed in to change notification settings

asmsh/flagged

Repository files navigation

flagged is a lightweight, fast, and zero-alloc Go library for working with typed, compact bitflags.

PkgGoDev Go Report Card Tests Go Coverage

It provides a minimal, extensible API for manipulating and inspecting compact bitflags, while remaining dependency-free and allocation-free.

It’s ideal for scenarios where you need efficient and compact boolean state representation — whether for generated flags, boolean configurations, or packed state machines.

Features:

  • Exposes typed wrappers for uint types: BitFlags8, BitFlags16, BitFlags32, BitFlags64 (matching uint8, uint16, uint32, uint64, respectively).
  • Unified interface: all exposed types implement a common BitFlags interface
  • Core bit operations, using only the bit index (normal integers, with no shifting required for inputs).
  • Pure Go implementation, no reflection, no dependencies, suitable for any application, in any environment.
  • go:generate–friendly: easy to use directly or as a backend for code generators (check genflagged).

Installation:

go get github.com/asmsh/flagged

Usage:

Import the package:

import "github.com/asmsh/flagged"

Choose a bit width depending on your needs:

var flags flagged.BitFlags16
flags.Set(3)
if flags.Is(3) {
    fmt.Println("flags[3] is set")
}
flags.Reset(3)
if !flags.Is(3) {
    fmt.Println("flags[3] is not set")
}

Or work with the interface:

var f flagged.BitFlags = flagged.New(flagged.BitFlags32(0))
f.Set(1)
f.Set(5)
f.Toggle(1)
fmt.Println(f) // 00000000000000000000000000100000

Example:

package main

import (
	"fmt"

	"github.com/asmsh/flagged"
)

const (
	permissionReadBitIndex flagged.BitIndex = iota
	permissionWriteBitIndex
	permissionExecBitIndex
)

func main() {
	var permFlags flagged.BitFlags8
	permFlags.Set(permissionReadBitIndex)
	permFlags.Set(permissionExecBitIndex)

	fmt.Println(permFlags.Is(permissionReadBitIndex))  // true
	fmt.Println(permFlags.Is(permissionWriteBitIndex)) // false

	permFlags.Toggle(permissionWriteBitIndex)
	fmt.Println(permFlags.Is(permissionWriteBitIndex)) // true

	fmt.Println(permFlags) // 00000111
}

About

Overthinking per-bool size overhead? Turn bool-heavy structs into compact, typed bitflags for Go — fast, zero-alloc, and go:generate–friendly.

Topics

Resources

License

Stars

Watchers

Forks

Languages