Bit Field
A type-safe bit field implementation for efficient flag operations.
This class provides a zero-cost abstraction over integer bit operations while maintaining type safety through Kotlin's inline value classes. It's designed to work with enum classes that represent bit flags, ensuring compile-time safety and runtime efficiency.
Key Features:
Zero runtime overhead through inline value classes
Type-safe flag operations with enum constraints
Immutable by default with functional operations
Comprehensive operator overloading for natural syntax
Full interoperability with integer types when needed
Usage Examples:
enum class FilePermissions(val bit: Int) {
READ(1 shl 0),
WRITE(1 shl 1),
EXECUTE(1 shl 2);
companion object : BitFieldEnum<FilePermissions> {
override fun fromValue(value: ULong): FilePermissions? {
return entries.find { it.bit.toULong() == value }
}
override fun BitFieldEnum.Companion.allFlags(): BitField<FilePermissions> {
return BitField(entries.fold(0UL) { acc, perm -> acc or perm.bit.toULong() })
}
}
}
// Create and manipulate bit fields
val permissions = BitField<FilePermissions>()
.setFlag(FilePermissions.READ)
.setFlag(FilePermissions.WRITE)
if (permissions.hasFlag(FilePermissions.READ)) {
println("Has read permission")
}
val combined = permissions or BitField(FilePermissions.EXECUTE)
val readOnly = permissions and BitField(FilePermissions.READ)Parameters
The enum type representing individual flags
Functions
Returns the number of flags set in this bit field.
Iterates over all set flags in this bit field.
Returns the union of this bit field and another (logical OR).
Returns the symmetric difference of this bit field and another (logical XOR).
Returns the complement of this bit field (logical NOT). Note: This inverts all bits, which may include more than just the enum values.
Returns a list of all flags that are set in this bit field.
Checks if all flags in the other BitField are set.
Checks if any of the flags in the other BitField are set.
Returns the position of the highest set bit (0-based).
Checks if this bit field is not empty (has flags set).
Returns the position of the lowest set bit (0-based).
Creates a sequence of all set flags.
Returns a string representation showing the binary value.
Returns a detailed string representation with set flags.
Toggles the specified flag in this bit field.
Returns a hexadecimal string representation.