bitflags-lite: Lightweight generics-based bitflags
The bitflags-lite crate provides a lightweight, generic bitflags
implementation for Rust.
BitFlags<T, U> is a #[repr(transparent)] wrapper around an integer T
that adds a compile-time tag type U.
The tag distinguishes flag sets that share the same storage type and
describes which bits are valid through the BitFlagsSpec trait.
Flag sets can be defined either through the bitflags! macro, which
generates the trait implementation and named constants from a compact
declaration, or by implementing BitFlagsSpec directly.
Both forms produce the same types and the same runtime behavior.
The crate is no_std and no_alloc compatible, and const-friendly.
When to choose bitflags, bitflags-lite, or enumflags2
- Choose
bitflagsif you want the mature and battle-tested crate, and the ecosystem-standard macro, and the ability to extend each flag set with inherent methods or third-party trait implementations. - Choose
bitflags-liteif you want a reusable genericBitFlags<T, U>with a small, inspectable expansion, optionally generated by a concise macro, and you don't need the ability to extend each flag set with inherent methods or third-party trait implementations. - Choose
enumflags2if you want a single-flag type distinct from the set type, enum-variant-driven definitions, and match/iter over variants.
About
Macro-based bitflags crate generate a distinct struct for every flag
set.
Each invocation re-expands the full method set, and the resulting types
share no common trait or type with one another.
By contrast, bitflags-lite defines BitFlags<T, U> once and asks you to
specialize it through a plain trait implementation.
The provided bitflags! macro is a convenience wrapper that generates
that trait impl and the named constants — it does not generate a new type.
Design Highlights:
- Single-flag vs. set distinction.
BitFlag<T, U>represents one bit index.BitFlags<T, U>represents a set. They convert into each other and interoperate through the usual operators. - Invalid bits are representable. A
BitFlagsvalue may contain bits not set inBitFlagsSpec::VALID_BITS_MASK; they are preserved by raw-bit operations and cleared byBitFlags::truncate,BitFlags::complement, andNot. UseBitFlags::is_validto check. - Const-friendly. Every constructor, accessor, and combinator on the
concrete integer types is a
const fn. The generic equivalents live in theBitFlagsExtandBitFlagExtextension traits. - No allocation. Parsing and formatting work without
alloc. Theallocfeature only enriches error messages with the offending input. - No hidden type generation. Even with the
bitflags!macro, no new type is created per flag set. The macro builds on the same genericBitFlags<T, U>, so all flag sets remain one type family.
Usage
[]
= "0.3.0"
With optional features:
[]
= { = "0.3.0", = [ "serde", "bytemuck" ] }
Examples
With the bitflags! macro
The macro generates the tag type, the flag-set alias, the BitFlagsSpec
implementation, and the named constants from one compact declaration:
use FromStr;
use ;
bitflags!
pub type Permission = ;
pub type Permissions = ;
let rwx = READ | WRITE | EXEC;
assert!;
assert!;
assert!;
assert!;
let read_exec = READ | EXEC;
assert!;
// Combined names participate in parsing.
let parsed = from_str.unwrap;
assert_eq!;
let parsed = from_str.unwrap;
assert_eq!;
// Iteration yields individual BitFlag values.
let flags: = parsed.into_iter.collect;
assert_eq!;
let formatted: = flags.iter.map.collect;
assert_eq!;
let named_only: = flags.iter.filter_map.collect;
assert_eq!;
Without the macro
The same flag set can be written manually. This is what the macro expands to, and it is fully supported as a public API:
use FromStr;
use ;
;
type Permission = ;
type Permissions = ;
// Constructors are `const` for concrete integer types.
const READ: Permission = try_from_bit.unwrap;
const WRITE: Permission = try_from_bit.unwrap;
const EXEC: Permission = try_from_bit.unwrap;
const RWX: Permissions = try_from_bits.unwrap;
Constants can also be defined through an inherent implementation, a trait,
or an associated const on the tag type.
Type-safety across flag sets
The tag type keeps flag sets distinct even when they share a storage type. The following example deliberately fails to compile:
use ;
;
type Perms = ;
;
type KeyboardModifiers = ;
let rwx: Perms = try_from_bits.unwrap;
let keyboard_modifiers: KeyboardModifiers = rwx;
// ^^^
// ❌ error[E0308]: mismatched types
// expected struct `BitFlags<_, KeyboardModifiersTag>`
// found struct `BitFlags<_, test::PermsTag>`
Comparison with Existing Crates
Definition
| Feature | bitflags-lite |
bitflags v2 |
enumflags2 v0.7 |
|---|---|---|---|
| Defined by trait impl | ✅ BitFlagsSpec<T> |
⛔️ No | ⛔️ No |
| Defined by macro | ✅ bitflags! |
✅ bitflags! |
⛔️ No |
| Defined by attribute | ⛔️ No | ⛔️ No | ✅ #[bitflags(...)] |
| Generates a distinct new type | ⛔️ No (generic over U) |
✅ Yes | ⛔️ No (uses user enum) |
Type model
| Feature | bitflags-lite |
bitflags v2 |
enumflags2 v0.7 |
|---|---|---|---|
| Single-flag vs. set distinction | ✅ BitFlag / BitFlags |
⛔️ No | ✅ T / BitFlags |
| Iteration yields | BitFlag<T, U> |
Flags (self, one bit) |
enum T (variant) |
| Match exhaustively on single flag | ⛔️ No | ⛔️ No | ✅ match flag { T::A => ... } |
| Generic over a single flag | ✅ BitFlag<T, U> |
⛔️ No | ✅ enum T |
| Generic over flag sets | ✅ BitFlags<T, U> |
⛔️ No | ✅ BitFlags<T, N> |
Extension
| Feature | bitflags-lite |
bitflags v2 |
enumflags2 v0.7 |
|---|---|---|---|
| Inherent methods | ⛔️ No | ✅ Yes | ⛔️ No |
| Third-party trait impls | ⛔️ No | ✅ Yes | ⛔️ No |
| Local trait impls | ✅ Yes | ✅ Yes | ✅ Yes |
Capabilities
| Feature | bitflags-lite |
bitflags v2 |
enumflags2 v0.7 |
|---|---|---|---|
| Most methods const | ✅ Integer impls | ✅ Targeted codegen | ⚠️ Limited |
| Multi-bit flags | ⚠️ Parse-only | ✅ Format and parse | ⛔️ No |
| Custom display name | ✅ Yes | ✅ #[name] |
⛔️ No |
| Alias names for parsing | ✅ Yes | ⛔️ No | ⛔️ No |
| Format with names | ✅ Yes | ✅ Yes | ✅ Yes |
| Parse from names | ✅ Yes | ✅ Yes | ⛔️ No |
| Case-insensitive parsing | ✅ Configurable | ⛔️ No | ⛔️ No |
| Custom default value | ⛔️ No | ✅ #[default] |
✅ #[default] |
| Only valid bits representable | ⛔️ No | ⛔️ No | ✅ Yes |
| Invalid bits representable | ✅ Yes | ✅ Yes | ⛔️ No |
Documentation
Feature flags
alloc(implied bystd, enabled by default): enriches parse errors with the offending input.std(enabled by default): enables theallocfeature.arbitrary: implementsArbitraryforBitFlag<T, U>andBitFlags<T, U>.serde: implementsserde::Serializeandserde::DeserializeforBitFlag<T, U>andBitFlags<T, U>, round-tripping through flag strings.bytemuck: implementsZeroableandPodforBitFlag<T, U>andBitFlags<T, U>, allowing them to be used in plain-old-data contexts.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.