Skip to content

Option to generate bitfield types #264

Open
@jonathangjertsen

Description

@jonathangjertsen

Hi, thanks for this very useful library.

I have a use case where I needed a bitfield/bitset type associated with the enum, as shown in the example below. This seems like something that could be generated automatically. Would it be in scope for this project?

Example

Given

//go:generate go-enum --bitfield

// ENUM(Read, Write, Admin)
type Permission int

generate the following additional code:

func (p Permission) Bitmask() PermissionBits {
	return 1 << PermissionBits(p)
}

type PermissionBits uint

func (pb *PermissionBits) Set(p Permission) {
	*pb |= p.Bitmask()
}

func (pb *PermissionBits) Clear(p Permission) {
	*pb &= ^p.Bitmask()
}

func (pb PermissionBits) Get(p Permission) bool {
	return pb&p.Bitmask() != 0
}

func (pb PermissionBits) Values() []Permission {
	out := []Permission{}
	for _, p := range PermissionValues() {
		if pb.Get(p) {
			out = append(out, p)
		}
	}
	return out
}

func (pb PermissionBits) Map() map[Permission]bool {
	out := map[Permission]bool{}
	for _, p := range PermissionValues() {
		out[p] = pb.Get(p)
	}
	return out
}

Details:

  • If all enum values are less than 32, use uint. If there are enum values 32-63, use uint64. If there are more than 64 values, do not support this feature (for now).
  • I considered doing this with generics, but it's too ugly and only works for sequential enums

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions