Overview / Foundation

bits

Bit manipulation: basic operations, masks, packing, scanning, Morton codes and a bit-level read and write stream.

Always compiled: part of the core build.Include #include <ethereal/cpp/bits/bits_inc.hpp>C layer

bits_inc.hpp

#include <ethereal/cpp/bits/bits_inc.hpp>

bitcore.hpp

#include <ethereal/cpp/bits/bitcore.hpp>
function

BitCeil

Ethereal::Bit#
inline constexpr ETL_UINT64 BitCeil( ETL_UINT64 v ) noexcept

Computes the smallest power of two greater than or equal to a value.

Returns the smallest power-of-two number that is greater than or equal to the input value. If the input is already a power of two, it is returned unchanged. If the input value is zero, the function returns '1'.

This operation is commonly used in memory allocators, hash tables, and capacity growth algorithms.

v
Input value.
Smallest power of two greater than or equal to 'v'.
function

BitFloor

Ethereal::Bit#
inline constexpr ETL_UINT64 BitFloor( ETL_UINT64 v ) noexcept

Computes the largest power of two less than or equal to a value.

Returns the greatest power-of-two number that is less than or equal to the input value. If the input value is zero, the function returns '0'.

This operation is frequently used in memory alignment, bucket sizing, and spatial partitioning.

v
Input value.
Largest power of two less than or equal to 'v'.
function

CountBits

Ethereal::Bit#
inline constexpr ETL_UINT8 CountBits( ETL_UINT8 v ) noexcept

Counts the number of bits set to 1 in an 8-bit unsigned integer.

Computes the population count (Hamming weight) of the input value. The result represents how many bits are set in the binary representation of the value.

When available, this function uses @std::popcount from. Otherwise it falls back to the compiler intrinsic '__builtin_popcount' for maximum performance.

v
The 8-bit value whose set bits will be counted.
The number of bits set to 1 in the input value.
function

CountBits

Ethereal::Bit#
inline constexpr ETL_UINT16 CountBits( ETL_UINT16 v ) noexcept

Counts the number of bits set to 1 in a 16-bit unsigned integer.

Computes the population count (Hamming weight) of the input value. The result corresponds to the total number of bits set in the binary representation of the 16-bit value.

If available, the implementation uses @std::popcount. Otherwise it relies on the compiler intrinsic '__builtin_popcount' for optimal performance.

v
The 16-bit value whose set bits will be counted.
The number of bits set to 1 in the input value.
function

CountBits

Ethereal::Bit#
inline constexpr ETL_UINT64 CountBits( ETL_UINT64 v ) noexcept

Counts the number of set bits (population count) in a 64-bit value.

Returns the number of bits set to '1' in the binary representation of the input value. When available, this function uses optimized CPU instructions such as POPCNT through standard C++ bit utilities or compiler intrinsics. A portable fallback implementation is used when intrinsics are not available.

v
Input value.
Number of bits set to '1'.
function

CountLeadingZeros

Ethereal::Bit#
inline constexpr ETL_INT32 CountLeadingZeros( ETL_UINT64 v ) noexcept

Counts the number of leading zero bits in a 64-bit value.

Determines how many zero bits appear before the most significant set bit in the binary representation of the value. When the input value is zero, the result is defined as '64'. This function uses C++20 bit utilities when available, otherwise it derives the result using bit scanning.

v
Input value.
Number of leading zero bits.
function

CountTrailingZeros32

Ethereal::Bit#
inline constexpr ETL_UINT32 CountTrailingZeros32( ETL_UINT32 v ) noexcept

Counts the number of trailing zero bits in a 32-bit value (32-bit version).

Returns the number of consecutive zero bits starting from the least significant bit (LSB) of the input value. If the input value is zero, the function returns '32', which corresponds to the full width of the type. The implementation selects the most efficient intrinsic available:

  • C++20: std::countr_zero
  • GCC/Clang: __builtin_ctz or _tzcnt_u32
  • MSVC/BMI: _tzcnt_u32
  • Fallback: own loop, no external dependency

This operation is commonly used in bitboards, bitsets, allocators, schedulers, and other low-level systems that rely on fast bit scans.

v
32-bit value to analyze.
Number of trailing zero bits. Returns '32' if 'v == 0'.
function

CountTrailingZeros64

Ethereal::Bit#
inline constexpr ETL_UINT32 CountTrailingZeros64( ETL_UINT64 v ) noexcept

Counts the number of trailing zero bits in a 64-bit value (64-bit version).

Returns the number of consecutive zero bits starting from the least significant bit (LSB) of the input value. If the input value is zero, the function returns '64', matching the bit width of the type. The implementation uses platform-specific intrinsics when available for optimal performance:

  • C++20: std::countr_zero
  • GCC/Clang: __builtin_ctzll or _tzcnt_u64
  • MSVC/BMI: _tzcnt_u64
  • Fallback: own loop, no external dependency

This function is frequently used in bit manipulation algorithms, sparse bitset iteration, schedulers, and low-level data structures.

v
64-bit value to analyze.
Number of trailing zero bits. Returns '64' if 'v == 0'.
function

BitCountRange

Ethereal::Bit#
inline constexpr ETL_UINT32 BitCountRange( ETL_UINT64 value, ETL_UINT32 offset, ETL_UINT32 count ) noexcept

Counts the number of set bits within a specified bit range.

Computes the population count ('popcount') of a subset of bits within the input value. The range begins at the specified bit offset and spans the requested number of bits.

Internally this operation masks the desired bit range and applies the standard bit counting routine ('CountBits'). This function is useful for analyzing partial bit fields, bitset segments, compression formats, and packed data layouts.

value
Source value.
offset
Starting bit position.
count
Number of bits to analyze.
Number of bits set to '1' within the specified range.
The mask is built here instead of coming from @CreateMask64 in 'bitmask.hpp'. This header is the base layer of the Bit module and cannot depend on bitmask.hpp, which depends on @CountLeadingZeros from here. The two used to include each other and, with include guards, the one included second compiled against an empty file. The valid order is bitcore <- bitmask <- bitscan.
function

BitReverse32

Ethereal::Bit#
inline constexpr ETL_UINT32 BitReverse32( ETL_UINT32 v ) noexcept

Reverses the bit order of a 32-bit integer.

Reorders the bits of the input value so that the least significant bit becomes the most significant one and vice versa. The operation is implemented using a sequence of efficient bit-swapping masks.

v
Input value.
Value with reversed bit order.
function

BitReverse64

Ethereal::Bit#
inline constexpr ETL_UINT64 BitReverse64( ETL_UINT64 v ) noexcept

Reverses the bit order of a 64-bit integer.

Produces a value where the least significant bit becomes the most significant bit and vice versa. This operation is useful in bitboard algorithms, signal processing, and certain hashing techniques.

v
Input value.
Value with reversed bit order.
function

RotateLeft32

Ethereal::Bit#
inline constexpr ETL_UINT32 RotateLeft32( ETL_UINT32 v, ETL_INT32 shift ) noexcept

Performs a left bit rotation on a 32-bit value.

Rotates the bits of the value to the left by the specified shift amount. Bits shifted out from the most significant side are reintroduced on the least significant side.

v
Input value.
shift
Rotation amount.
Rotated value.
function

RotateRight32

Ethereal::Bit#
inline constexpr ETL_UINT32 RotateRight32( ETL_UINT32 v, ETL_INT32 shift ) noexcept

Performs a right bit rotation on a 32-bit value.

Rotates the bits of the value to the right by the specified shift amount. Bits shifted out from the least significant side are reintroduced on the most significant side.

v
Input value.
shift
Rotation amount.
Rotated value.
function

RotateLeft64

Ethereal::Bit#
inline constexpr ETL_UINT64 RotateLeft64( ETL_UINT64 v, ETL_INT32 shift ) noexcept

Performs a left bit rotation on a 64-bit value.

Rotates the bits of the value to the left by the specified shift amount while preserving all bits through wrap-around.

v
Input value.
shift
Rotation amount.
Rotated value.
function

RotateRight64

Ethereal::Bit#
inline constexpr ETL_UINT64 RotateRight64( ETL_UINT64 v, ETL_INT32 shift ) noexcept

Performs a right bit rotation on a 64-bit value.

Rotates the bits of the value to the right by the specified shift amount while preserving all bits through wrap-around.

v
Input value.
shift
Rotation amount.
Rotated value.
function

Parity

Ethereal::Bit#
inline constexpr bool Parity( ETL_UINT64 v ) noexcept

Computes the parity of a 64-bit value.

Determines whether the number of set bits in the value is odd or even. The implementation uses a fast bit folding technique to collapse the bit pattern before applying a small lookup mask.

v
Input value.
True if the number of set bits is odd, otherwise false.

bitmask.hpp

#include <ethereal/cpp/bits/bitmask.hpp>
function

CreateMask32

Ethereal::Bit#
inline constexpr ETL_UINT32 CreateMask32( ETL_INT32 bits ) noexcept

Creates a 32-bit mask with a specified number of lower bits set.

Generates a mask where the least significant bits are set to 1. If bits is zero or negative, the result is '0'. If bits exceeds the width of the 32-bit type, the mask is fully set.

bits
Number of bits to set.
32-bit mask with the specified number of lower bits set.
function

CreateMask64

Ethereal::Bit#
inline constexpr ETL_UINT64 CreateMask64( ETL_INT32 bits ) noexcept

Creates a bit mask with a specified number of lower bits set.

Generates a mask where the least significant bits are set to 1. If bits is zero or negative, the result is '0'. If bits exceeds the width of the type, the mask is fully set.

bits
Number of bits to set.
Bit mask with the specified number of lower bits set.
function

TestBit

Ethereal::Bit#
inline constexpr bool TestBit( ETL_UINT64 value, ETL_INT32 bit ) noexcept

Tests whether a specific bit is set.

Checks if the bit at the specified position is set to '1'.

value
Input value.
bit
Bit index.
True if the bit is set, otherwise false.
function

SetBit

Ethereal::Bit#
inline constexpr ETL_UINT64 SetBit( ETL_UINT64 value, ETL_INT32 bit ) noexcept

Sets a specific bit in a value.

Returns a new value where the specified bit position is forced to '1'.

value
Input value.
bit
Bit index.
Value with the specified bit set.
function

ClearBit

Ethereal::Bit#
inline constexpr ETL_UINT64 ClearBit( ETL_UINT64 value, ETL_INT32 bit ) noexcept

Clears a specific bit in a value.

Returns a new value where the specified bit position is forced to '0'.

value
Input value.
bit
Bit index.
Value with the specified bit cleared.
function

ToggleBit

Ethereal::Bit#
inline constexpr ETL_UINT64 ToggleBit( ETL_UINT64 value, ETL_INT32 bit ) noexcept

Toggles a specific bit in a value.

Flips the state of the specified bit, changing '1' to '0' or '0' to '1'.

value
Input value.
bit
Bit index.
Value with the specified bit toggled.
function

BitWidth

Ethereal::Bit#
inline constexpr ETL_UINT32 BitWidth( ETL_UINT64 v ) noexcept

Computes the number of bits required to represent a value.

Returns the position of the highest set bit plus one. Effectively equivalent to 'floor(log2(v)) + 1'.

v
Input value.
Number of bits required to represent the value.
function

RoundUpToMultiple

Ethereal::Bit#
inline constexpr ETL_UINT64 RoundUpToMultiple( ETL_UINT64 value, ETL_UINT64 multiple ) noexcept

Rounds a value up to the nearest multiple.

Returns the smallest multiple of 'multiple' that is greater than or equal to the input value.

value
Input value.
multiple
Alignment multiple.
Rounded value.
function

ExtractLowestBit

Ethereal::Bit#
inline constexpr ETL_UINT64 ExtractLowestBit( ETL_UINT64 v ) noexcept

Extracts the lowest set bit.

Returns a value containing only the least significant bit that is set in the input.

v
Input value.
Isolated lowest set bit.
function

ClearLowestBit

Ethereal::Bit#
inline constexpr ETL_UINT64 ClearLowestBit( ETL_UINT64 v ) noexcept

Clears the lowest set bit.

Removes the least significant bit set to '1' in the value while leaving all other bits unchanged.

v
Input value.
Value with the lowest set bit cleared.
function

BitMaskRange

Ethereal::Bit#
inline constexpr ETL_UINT64 BitMaskRange( ETL_UINT32 offset, ETL_UINT32 count ) noexcept

Creates a bit mask covering a specific range.

Generates a mask with 'count' consecutive bits set starting at the specified offset. Example: BitMaskRange(4,3) -> 0001110000

offset
Starting bit position.
count
Number of bits.
Generated bit mask.
function

BitHasAny

Ethereal::Bit#
inline constexpr bool BitHasAny( ETL_UINT64 value, ETL_UINT64 mask ) noexcept

Tests whether any bit from a mask is present.

value
Source value.
mask
Bit mask.
True if any bit overlaps.
function

BitHasAll

Ethereal::Bit#
inline constexpr bool BitHasAll( ETL_UINT64 value, ETL_UINT64 mask ) noexcept

Tests whether all bits from a mask are present.

value
Source value.
mask
Bit mask.
True if all bits are present.
If mask is zero, this function always returns true (vacuously satisfied).

bitpack.hpp

#include <ethereal/cpp/bits/bitpack.hpp>
function

WriteBits

Ethereal::Bit#
inline constexpr void WriteBits( ETL_UINT64 & buffer, ETL_UINT64 value, ETL_UINT32 offset, ETL_UINT32 bits ) noexcept

Writes a bit field into an existing buffer.

Clears the target region and writes the specified number of bits from the input value into the buffer.

buffer
Target buffer.
value
Value to write.
offset
Bit offset.
bits
Number of bits.
function

BitExtractRange

Ethereal::Bit#
inline constexpr ETL_UINT64 BitExtractRange( ETL_UINT64 value, ETL_UINT32 offset, ETL_UINT32 count ) noexcept

Extracts a contiguous range of bits.

Retrieves 'count' bits starting at 'offset' and returns the result right-aligned. This function is equivalent to: '(value >> offset) & mask', but expressed as a dedicated helper for clarity.

value
Source value.
offset
Starting bit position.
count
Number of bits.
Extracted bit sequence.
function

BitInsertRange

Ethereal::Bit#
inline constexpr ETL_UINT64 BitInsertRange( ETL_UINT64 base, ETL_UINT64 value, ETL_UINT32 offset, ETL_UINT32 count ) noexcept

Inserts a bit field into a value.

Replaces a range of bits in the target value with bits taken from the input value. The inserted bits are masked to ensure only the requested range is affected.

base
Target value.
value
Bits to insert.
offset
Starting bit position.
count
Number of bits.
Updated value containing the inserted bit field.
function

ExtractBits32

Ethereal::Bit#
inline constexpr ETL_UINT32 ExtractBits32( ETL_UINT32 value, ETL_UINT32 mask ) noexcept

Extracts selected bits from a 32-bit value using a mask and packs them contiguously.

Collects the bits from 'value' indicated by the set bits in 'mask' and compresses them into the lower bits of the result. When the CPU supports BMI2 instructions, the function uses the @_pext_u32 intrinsic for a hardware-accelerated parallel bit extract. Otherwise, it falls back to a portable SWAR implementation that iterates through the set bits of the mask.

The order of extraction follows the mask from least significant bit to most significant bit.

value
Source value from which bits will be extracted.
mask
Bit mask indicating which bits should be extracted.
Extracted bit sequence.
function

ExtractBits64

Ethereal::Bit#
inline constexpr ETL_UINT64 ExtractBits64( ETL_UINT64 value, ETL_UINT64 mask ) noexcept

Extracts bits from a value according to a mask.

Compacts selected bits from the input value into contiguous lower bits. When supported by the CPU, the operation maps directly to the 'PEXT' instruction. Otherwise, it falls back to a portable SWAR implementation that iterates through the set bits of the mask.

value
Source value from which bits will be extracted.
mask
Bit mask indicating which bits should be extracted.
Extracted bit sequence.
function

DepositBits

Ethereal::Bit#
inline constexpr ETL_UINT64 DepositBits( ETL_UINT64 value, ETL_UINT64 mask ) noexcept

Deposits bits into positions defined by a mask.

Expands bits from the input value and places them into positions defined by the mask. When supported, this maps directly to the 'PDEP' instruction.

value
Source value.
mask
Target bit mask.
Value with deposited bits.
function

BitScatter

Ethereal::Bit#
inline constexpr ETL_UINT64 BitScatter( ETL_UINT64 value, ETL_UINT64 mask ) noexcept

Scatters bits of a value into positions defined by a mask.

Inserts bits from the source value into the positions specified by the mask, filling them sequentially from least significant bit.

value
Source bits.
mask
Target mask.
Scattered bit value.
function

NextBitPermutation

Ethereal::Bit#
inline constexpr ETL_UINT64 NextBitPermutation( ETL_UINT64 v ) noexcept

Computes the next lexicographical bit permutation.

Generates the next permutation of the input bit pattern that contains the same number of set bits. This operation is commonly used when iterating combinations represented as bit masks. For example: 00101100 -> 00110001

If no higher permutation exists, the behavior wraps according to the underlying bit arithmetic.

v
Input bit pattern.
Next bit permutation with the same number of set bits, or 0 if invalid.

bitscan.hpp

#include <ethereal/cpp/bits/bitscan.hpp>
function

FindFirstSet32

Ethereal::Bit#
ETL_INT32 FindFirstSet32( const ETL_UINT32 v ) /*noexcept*/

Finds the index of the least significant set bit in a 32-bit value.

Returns the position of the lowest bit set to 1 in the input value. Bit indexing starts at 0 from the least significant bit (LSB). If the input value is zero, the function returns '-1' to indicate that no bits are set.

The implementation uses compiler or CPU intrinsics when available for maximum performance:

  • MSVC: _BitScanForward
  • GCC/Clang: __builtin_ctz or _tzcnt_u32
  • Fallback: std::countr_zero (C++20) or __builtin_ctz
v
32-bit value to analyze.
Index of the least significant set bit, or '-1' if the value is zero.
function

FindFirstSet64

Ethereal::Bit#
ETL_INT32 FindFirstSet64( const ETL_UINT64 v ) /*noexcept*/

Finds the index of the least significant set bit in a 64-bit value.

Returns the position of the lowest bit set to 1 in the input value. Bit indexing starts at 0 from the least significant bit (LSB). If the input value is zero, the function returns '-1' to indicate that no bits are set.

The implementation uses platform-specific intrinsics when available for optimal performance:

  • MSVC: _BitScanForward64 (for x64 builds)
  • GCC/Clang: __builtin_ctzll or _tzcnt_u64
  • Fallback: std::countr_zero (C++20) or __builtin_ctzll
v
64-bit value to analyze.
Index of the least significant set bit, or '-1' if the value is zero.
function

NextSetBit32

Ethereal::Bit#
ETL_INT32 NextSetBit32( ETL_UINT32 value, ETL_INT32 start ) /*noexcept*/

Finds the next set bit after a specified position (32-bit version).

Searches for the next bit set to '1' starting immediately after the specified bit position. If no further set bits exist, or if the start position is invalid, returns '-1'. Useful for iterating over sparse bitsets in 32-bit masks.

value
32-bit input bit mask.
start
Bit position to start searching from (0..31).
Index of the next set bit (0..31), or '-1' if none exists or invalid start.
function

NextSetBit64

Ethereal::Bit#
ETL_INT32 NextSetBit64( ETL_UINT64 value, ETL_INT32 start ) /*noexcept*/

Finds the next set bit after a specified position (64-bit version).

Searches for the next bit set to '1' starting immediately after the specified bit position. If no further set bits exist, the function returns '-1'. This function is useful for iterating sparse bitsets and bitboard structures.

value
Input bit mask.
start
Bit position to start searching from.
Index of the next set bit, or '-1' if none exists.
function

FindLastSet32

Ethereal::Bit#
ETL_INT32 FindLastSet32( ETL_UINT32 v ) /*noexcept*/

Finds the index of the most significant set bit in a 32-bit value.

Returns the position of the highest bit set to 1 in the input value. Bit indexing starts at 0 from the least significant bit (LSB). If the input value is zero, the function returns '-1' to indicate that no bits are set.

The implementation uses compiler or CPU intrinsics when available for maximum performance:

  • MSVC: _BitScanReverse
  • GCC/Clang: __builtin_clz or _lzcnt_u32
  • Fallback: std::countl_zero (C++20) or __builtin_clz
v
32-bit value to analyze.
Index of the most significant set bit, or '-1' if the value is zero.
function

FindLastSet64

Ethereal::Bit#
ETL_INT32 FindLastSet64( const ETL_UINT64 v ) /*noexcept*/

Finds the index of the most significant set bit in a 64-bit value.

Returns the position of the highest bit set to 1 in the input value. Bit indexing starts at 0 from the least significant bit (LSB). If the input value is zero, the function returns '-1' to indicate that no bits are set.

The implementation uses platform-specific intrinsics when available to achieve optimal performance:

  • MSVC: _BitScanReverse64 (for x64 builds)
  • GCC/Clang: __builtin_clzll or _lzcnt_u64
  • Fallback: std::countl_zero (C++20) or __builtin_clzll
v
64-bit value to analyze.
Index of the most significant set bit, or '-1' if the value is zero.
function

PrevSetBit

Ethereal::Bit#
ETL_INT32 PrevSetBit( ETL_UINT64 value, ETL_INT32 start ) /*noexcept*/

Finds the previous set bit before a specified position.

Searches for the nearest bit set to '1' that occurs before the specified bit index. If no such bit exists, the function returns '-1'. This function is commonly used in reverse bit iteration and bitboard algorithms.

value
Input bit mask.
start
Bit position to search before.
Index of the previous set bit, or '-1' if none exists.
function

ForEachSetBit

Ethereal::Bit#
template< typename Func > inline constexpr void ForEachSetBit( ETL_UINT64 mask, Func && fn )
function

ForEachSetBitReverse

Ethereal::Bit#
template< typename Func > inline constexpr void ForEachSetBitReverse( ETL_UINT64 mask, Func && fn )
function

BitPopLowest32

Ethereal::Bit#
inline constexpr ETL_INT32 BitPopLowest32( ETL_UINT32 & mask ) noexcept

Extracts and removes the lowest set bit from a 32-bit mask (32-bit version).

Identifies the least significant bit set to 1 in the mask, returns its index, and clears that bit from the mask. Bit indices follow the conventional numbering where the least significant bit (LSB) is index 0. If the mask is zero, the function returns '-1' and the mask remains unchanged.

This helper is useful for efficiently iterating through bitsets or flag masks without scanning all bits, commonly used in schedulers, allocators, and bitboard-style algorithms.

mask
Reference to the bit mask. The lowest set bit will be cleared.
Index of the extracted bit, or '-1' if the mask was zero.
function

BitPopLowest64

Ethereal::Bit#
inline constexpr ETL_INT32 BitPopLowest64( ETL_UINT64 & mask ) noexcept

Extracts and removes the lowest set bit using a branchless method (64-bit version).

Identifies the least significant bit set to '1', removes it from the mask, and returns its index. This implementation isolates the lowest set bit using the expression 'mask & ( ~mask + 1u )', the two's complement of the mask, which produces a value containing only that bit. The isolated bit is then removed from the mask using XOR and its position is determined through @CountTrailingZeros64.

Compared to alternative implementations, this version avoids an explicit conditional branch and can map directly to efficient CPU instructions on modern processors.

This function is commonly used for iterating sparse bitsets, entity masks, scheduler queues, and networking flags.

mask
Bit mask to process (modified in-place).
Index of the extracted bit, or '-1' if the mask is empty.
function

BitRank

Ethereal::Bit#
inline constexpr ETL_UINT32 BitRank( ETL_UINT64 value, ETL_UINT32 pos ) noexcept

Counts the number of set bits up to a given position.

Computes the population count of all bits below the specified index. The bit at 'pos' is not included.

value
Input value.
pos
Bit position.
Number of bits set below the position.
function

BitPrefixSum

Ethereal::Bit#
inline constexpr ETL_UINT32 BitPrefixSum( ETL_UINT64 value, ETL_UINT32 pos ) noexcept

Computes the inclusive prefix population count.

Returns the number of set bits from bit 0 up to and including the specified position.

value
Input value.
pos
Bit position.
Number of bits set up to the position.
function

BitSelect

Ethereal::Bit#
inline constexpr ETL_INT32 BitSelect( ETL_UINT64 mask, ETL_UINT32 index ) noexcept

Selects the index of the N-th set bit in a mask.

Returns the index of the N-th bit set to '1' in the input mask, counting from the least significant bit (LSB). The first set bit corresponds to 'index = 0'. If the requested index exceeds the number of set bits, the function returns '-1'.

mask
Bit mask to search.
index
Zero-based index of the set bit to select.
Bit position of the selected set bit, or '-1' if it does not exist.
function

BitSelectFast

Ethereal::Bit#
inline constexpr ETL_INT32 BitSelectFast( ETL_UINT64 mask, ETL_UINT32 index ) noexcept

Selects the index of the N-th set bit using BMI2 instructions.

Uses the PDEP instruction to isolate the N-th set bit. Falls back to BitSelect when BMI2 is unavailable.

mask
Bit mask.
index
Zero-based index.
Bit index or '-1' if not found.
function

BitSelectPrefix

Ethereal::Bit#
inline constexpr ETL_INT32 BitSelectPrefix( ETL_UINT64 value, ETL_UINT32 target ) noexcept

Finds the position where the prefix population count reaches a value.

Returns the bit index where the number of set bits equals the requested prefix count.

value
Bit mask.
target
Desired prefix count.
Bit index or '-1' if not found.
function

BitCountLeadingOnes

Ethereal::Bit#
inline constexpr ETL_UINT32 BitCountLeadingOnes( ETL_UINT64 value ) noexcept

Counts leading one bits.

Returns the number of consecutive bits set to '1' starting from the most significant bit.

value
Input value.
Number of leading ones.
function

BitRunLength

Ethereal::Bit#
inline constexpr ETL_UINT32 BitRunLength( ETL_UINT64 value, ETL_UINT32 offset ) noexcept

Computes the length of a run of identical bits starting at a position.

Counts how many consecutive bits (either 0 or 1 depending on the bit at the starting position) continue from the given offset.

value
Source value.
offset
Starting bit position.
Length of the bit run.
function

BitFindZeroRun

Ethereal::Bit#
inline constexpr ETL_INT32 BitFindZeroRun( ETL_UINT64 value, ETL_UINT32 count ) noexcept

Finds the first run of zero bits with a given length.

Searches for the first contiguous region of zero bits of the requested size.

value
Bit mask.
count
Number of consecutive zero bits required.
Starting index of the zero run, or '-1' if not found.

bitspatial.hpp

#include <ethereal/cpp/bits/bitspatial.hpp>
function

BitSpread2D

Ethereal::Bit::Encode#
inline constexpr ETL_UINT64 BitSpread2D( ETL_UINT32 v ) /*noexcept*/

Expands a 32-bit value into a 64-bit Morton pattern (2D interleaving).

Spreads the bits of the input value so that each bit occupies every other position in the result (even bit positions: 0,2,4,...). This is commonly used to build 2D Morton (Z-order) codes by interleaving X and Y coordinates. When BMI2 is available, the function uses @_pdep_u64 for hardware accelerated bit deposition. Otherwise, a SWAR-based fallback is used.

v
32-bit value to expand.
64-bit value with bits spread into even positions.
function

BitSpread3D

Ethereal::Bit::Encode#
inline constexpr ETL_UINT64 BitSpread3D( ETL_UINT32 v ) /*noexcept*/

Expands a 32-bit value into a 64-bit Morton pattern (3D interleaving).

Spreads the bits of the input value so that each bit occupies every third position in the result (positions: 0,3,6,...). This is used to construct 3D Morton (Z-order) codes by interleaving X, Y, and Z coordinates. The input is limited to 21 bits to fit within a 64-bit Morton layout (21 * 3 = 63 bits). A sanity check ensures this constraint. When BMI2 is available, @_pdep_u64 is used for optimal performance. Otherwise, a SWAR-based fallback implementation is used.

v
32-bit value to expand (must be <= 21 bits).
64-bit value with bits spread into 3D Morton layout.
function

Morton2D

Ethereal::Bit::Encode#
inline constexpr ETL_UINT64 Morton2D( ETL_UINT32 x, ETL_UINT32 y ) /*noexcept*/

Encodes 2D coordinates into a 64-bit Morton (Z-order) code.

Interleaves the bits of the X and Y coordinates to produce a Morton-encoded value, where X occupies even bit positions (0,2,4,...) and Y occupies odd bit positions (1,3,5,...). This encoding preserves spatial locality and is commonly used in quadtrees, spatial hashing, tile maps, and cache-friendly data layouts. When BMI2 is available, @_pdep_u64 is used for hardware accelerated bit interleaving. Otherwise, a SWAR-based fallback using @BitSpread2D is applied.

x
X coordinate.
y
Y coordinate.
64-bit Morton code representing the (x, y) position.
function

Morton3D

Ethereal::Bit::Encode#
inline constexpr ETL_UINT64 Morton3D( ETL_UINT32 x, ETL_UINT32 y, ETL_UINT32 z ) /*noexcept*/

Encodes 3D coordinates into a 64-bit Morton (Z-order) code.

Interleaves the bits of the X, Y, and Z coordinates to produce a Morton-encoded value, where:

  • X occupies bits 0,3,6,...
  • Y occupies bits 1,4,7,...
  • Z occupies bits 2,5,8,...

This encoding improves spatial locality and is widely used in octrees, voxel engines, sparse 3D grids, and spatial indexing. Each coordinate is limited to 21 bits (21 * 3 = 63 bits total), and sanity checks enforce this constraint. When BMI2 is available, @_pdep_u64 is used for optimal performance. Otherwise, a SWAR-based fallback using @BitSpread3D is used.

x
X coordinate (must be <= 21 bits).
y
Y coordinate (must be <= 21 bits).
z
Z coordinate (must be <= 21 bits).
64-bit Morton code representing the (x, y, z) position.
function

QuantizeFloatToUInt32

Ethereal::Bit::Encode#
inline constexpr ETL_UINT32 QuantizeFloatToUInt32( float v ) noexcept

Quantizes a floating-point value into a full 32-bit unsigned integer range.

Clamps the input value to the [0, 1] range and scales it to the full 32-bit integer domain [0, 0xFFFFFFFF]. NaN inputs are safely handled and return 0.

This function is commonly used for high-precision normalization, encoding, and conversion of floating-point values into integer representations for storage or bit manipulation.

v
Input floating-point value.
Quantized 32-bit unsigned integer.
function

QuantizeFloatTo21Bits

Ethereal::Bit::Encode#
inline constexpr ETL_UINT32 QuantizeFloatTo21Bits( float v ) noexcept

Quantizes a floating-point value into a 21-bit unsigned integer range.

Clamps the input value to the [0, 1] range and scales it to the 21-bit integer domain [0, 0x1FFFFF]. NaN inputs are safely handled and return 0. This function is typically used for Morton encoding in 3D space, where each axis must fit within 21 bits (21 * 3 = 63 bits total).

v
Input floating-point value.
Quantized 21-bit unsigned integer.
function

Morton2D_FromFloat

Ethereal::Bit::Encode#
inline constexpr ETL_UINT64 Morton2D_FromFloat( float x, float y ) noexcept

Encodes 2D floating-point coordinates into a 64-bit Morton code.

Converts normalized floating-point inputs (expected in [0, 1]) into 32-bit integers using @QuantizeFloatToUInt32, then encodes them into a Morton (Z-order) code via @Morton2D. This enables spatial indexing of floating-point coordinates while preserving locality in memory.

x
X coordinate (float, expected in [0, 1]).
y
Y coordinate (float, expected in [0, 1]).
64-bit Morton code representing the (x, y) position.
function

Morton3D_FromFloat

Ethereal::Bit::Encode#
inline constexpr ETL_UINT64 Morton3D_FromFloat( float x, float y, float z ) noexcept

Encodes 3D floating-point coordinates into a 64-bit Morton code.

Converts normalized floating-point inputs (expected in [0, 1]) into 21-bit integers using @QuantizeFloatTo21Bits, then encodes them into a Morton (Z-order) code via @Morton3D. This ensures that all three axes fit within a 64-bit Morton layout (21 bits per axis, total 63 bits). This function is commonly used in voxel engines, octrees, spatial indexing, and GPU-friendly data layouts.

x
X coordinate (float, expected in [0, 1]).
y
Y coordinate (float, expected in [0, 1]).
z
Z coordinate (float, expected in [0, 1]).
64-bit Morton code representing the (x, y, z) position.
function

BitCompact2D

Ethereal::Bit::Decode#
inline constexpr ETL_UINT32 BitCompact2D( ETL_UINT64 v ) noexcept

Compacts interleaved 2D bits from a Morton-encoded value.

Extracts the bits located in even positions (0,2,4,...) from a 64-bit Morton (Z-order) code and compacts them into a contiguous 32-bit value. This effectively reverses the operation performed by @BitSpread2D, allowing recovery of one coordinate (typically X) from an interleaved Morton representation. When BMI2 is available, @_pext_u64 is used for hardware accelerated bit extraction. Otherwise, a SWAR-based fallback is used.

v
64-bit Morton-encoded value.
32-bit compacted value containing the extracted bits.
function

BitCompact3D

Ethereal::Bit::Decode#
inline constexpr ETL_UINT32 BitCompact3D( ETL_UINT64 v ) noexcept

Compacts interleaved 3D bits from a Morton-encoded value.

Extracts the bits located in positions (0,3,6,...) from a 64-bit Morton (Z-order) code and compacts them into a contiguous 32-bit value. This reverses the operation of @BitSpread3D, allowing recovery of one coordinate (typically X) from a 3D Morton encoding. Only 21 bits are reconstructed, matching the constraints of 64-bit Morton 3D layouts (21 bits per axis). When BMI2 is available, @_pext_u64 is used for optimal performance. Otherwise, a SWAR-based fallback implementation is applied.

v
64-bit Morton-encoded value.
32-bit compacted value (up to 21 bits).
function

Morton2D

Ethereal::Bit::Decode#
inline constexpr void Morton2D( ETL_UINT64 code, ETL_UINT32 & x, ETL_UINT32 & y ) noexcept

Decodes a 64-bit Morton (Z-order) code into 2D coordinates.

Extracts the interleaved X and Y components from a Morton-encoded value and writes them into the provided references. The decoding reverses the Morton interleaving process:

  • X is reconstructed from even bit positions (0,2,4,...)
  • Y is reconstructed from odd bit positions (1,3,5,...)

When BMI2 is available, @_pext_u64 is used for hardware accelerated extraction. Otherwise, a SWAR-based fallback using @BitCompact2D is applied.

code
64-bit Morton-encoded value.
x
Output X coordinate.
y
Output Y coordinate.
function

Morton3D

Ethereal::Bit::Decode#
inline constexpr void Morton3D( ETL_UINT64 code, ETL_UINT32 & x, ETL_UINT32 & y, ETL_UINT32 & z ) noexcept

Decodes a 64-bit Morton (Z-order) code into 3D coordinates.

Extracts the interleaved X, Y, and Z components from a Morton encoded value and writes them into the provided references. The decoding reverses the Morton interleaving process:

  • X is reconstructed from bits (0,3,6,...)
  • Y is reconstructed from bits (1,4,7,...)
  • Z is reconstructed from bits (2,5,8,...)

Each axis is limited to 21 bits, matching the 64-bit Morton layout (21 * 3 = 63 bits total). When BMI2 is available, @_pext_u64 is used for optimal performance. Otherwise, a SWAR-based fallback using @BitCompact3D is used.

code
64-bit Morton-encoded value.
x
Output X coordinate.
y
Output Y coordinate.
z
Output Z coordinate.
function

Morton2D_ToFloat

Ethereal::Bit::Decode#
inline constexpr void Morton2D_ToFloat( ETL_UINT64 code, float & x, float & y ) noexcept

Decodes a 64-bit Morton code into normalized 2D floating-point coordinates.

Extracts the integer X and Y components from a Morton encoded value and converts them back into normalized floating-point values in the range [0, 1]. The conversion is performed by scaling the extracted 32-bit integers using the inverse of the full 32-bit range (1 / 0xFFFFFFFF). This function is the inverse of @Morton2D_FromFloat, allowing reconstruction of approximate floating-point coordinates from a Morton representation.

code
64-bit Morton-encoded value.
x
Output X coordinate (normalized float).
y
Output Y coordinate (normalized float).
function

Morton3D_ToFloat

Ethereal::Bit::Decode#
inline constexpr void Morton3D_ToFloat( ETL_UINT64 code, float & x, float & y, float & z ) noexcept

Decodes a 64-bit Morton code into normalized 3D floating-point coordinates.

Extracts the integer X, Y, and Z components from a Morton-encoded value and converts them back into normalized floating-point values in the range [0, 1]. Each axis is reconstructed from 21-bit precision integers and scaled using the inverse of the maximum 21-bit value (1 / 0x1FFFFF). This function is the inverse of @Morton3D_FromFloat, enabling recovery of approximate floating-point positions from a Morton code.

code
64-bit Morton-encoded value.
x
Output X coordinate (normalized float).
y
Output Y coordinate (normalized float).
z
Output Z coordinate (normalized float).
function

Morton2D_Min

Ethereal::Bit#
inline constexpr ETL_UINT64 Morton2D_Min( ETL_UINT64 a, ETL_UINT64 b ) noexcept
function

Morton2D_Max

Ethereal::Bit#
inline constexpr ETL_UINT64 Morton2D_Max( ETL_UINT64 a, ETL_UINT64 b ) noexcept

Computes the component-wise maximum between two 2D Morton codes.

Decodes both Morton codes into their X and Y components, computes the maximum for each axis independently, and re-encodes the result back into a Morton code. This function is commonly used in spatial queries, bounding volume calculations, and Morton-based indexing systems.

a
First Morton code.
b
Second Morton code.
Morton code representing the component-wise maximum.
function

Morton3D_Min

Ethereal::Bit#
inline constexpr ETL_UINT64 Morton3D_Min( ETL_UINT64 a, ETL_UINT64 b ) noexcept

Computes the component-wise minimum between two 3D Morton codes.

Decodes both Morton codes into their X, Y, and Z components, computes the minimum for each axis independently, and re-encodes the result into a Morton code. This is typically used in spatial algorithms such as octree bounds, voxel region calculations, and 3D indexing systems.

a
First Morton code.
b
Second Morton code.
Morton code representing the component-wise minimum.
function

Morton3D_Max

Ethereal::Bit#
inline constexpr ETL_UINT64 Morton3D_Max( ETL_UINT64 a, ETL_UINT64 b ) noexcept

Computes the component-wise maximum between two 3D Morton codes.

Decodes both Morton codes into their X, Y, and Z components, computes the maximum for each axis independently, and re-encodes the result into a Morton code. This operation is useful for spatial bounds, merging regions, and working with Morton-encoded volumetric data.

a
First Morton code.
b
Second Morton code.
Morton code representing the component-wise maximum.
function

Morton2D_Neighbor

Ethereal::Bit#
inline constexpr ETL_UINT64 Morton2D_Neighbor( ETL_UINT64 code, ETL_INT32 dx, ETL_INT32 dy ) /*noexcept*/

Computes a neighboring 2D Morton code using integer offsets.

Decodes the Morton code into X and Y coordinates, applies the specified offsets, and re-encodes the result into a new Morton (Z-order) code. The operation is performed in integer space to ensure correctness, and bounds are validated to prevent overflow or underflow. This approach is commonly used in grid traversal, spatial queries, tile navigation, and neighbor lookup operations.

code
Original Morton code.
dx
Offset to apply along the X axis.
dy
Offset to apply along the Y axis.
Morton code of the neighboring position.
function

Morton3D_Neighbor

Ethereal::Bit#
inline constexpr ETL_UINT64 Morton3D_Neighbor( ETL_UINT64 code, ETL_INT32 dx, ETL_INT32 dy, ETL_INT32 dz ) /*noexcept*/

Computes a neighboring 3D Morton code using integer offsets.

Decodes the Morton code into X, Y, and Z coordinates, applies the specified offsets, and re-encodes the result into a new Morton (Z-order) code. Each axis is validated to remain within the valid 21-bit range (0 to 0x1FFFFF), ensuring compatibility with the 64-bit Morton layout. This function is typically used in voxel traversal, octree navigation, and spatial neighbor queries in 3D space.

code
Original Morton code.
dx
Offset to apply along the X axis.
dy
Offset to apply along the Y axis.
dz
Offset to apply along the Z axis.
Morton code of the neighboring position.

bitstream.hpp

#include <ethereal/cpp/bits/bitstream.hpp>
class

CBitStream

Ethereal::Bit#

Bit-level serialization stream for reading and writing variable-length bit sequences.

class CBitStream final

CBitStream provides a high-performance mechanism for writing and reading arbitrary numbers of bits to and from a memory buffer. It is designed primarily for network protocols, binary serialization, compression algorithms, and other systems where fine-grained bit packing is required.

The stream maintains independent read and write cursors, allowing data to be written and then read without recreating the stream.

The stream may either: • operate on user-provided external memory • allocate and manage its own internal buffer

Optional automatic buffer growth can be enabled when the stream owns its memory.

This class is not thread-safe. Synchronization must be handled externally.
This class must not be inherited from.
enum

EMode

#
C++
enum class EMode : ETL_UINT8
{
    ReadOnly,
    WriteOnly,
    ReadWrite
};
constructor

CBitStream

#
CBitStream() noexcept;
constructor

CBitStream

#
explicit CBitStream(ETL_UINT32 initialBytes);
constructor

CBitStream

#
CBitStream(void* pBuffer, ETL_UINT32 byteSize, EMode mode = EMode::ReadWrite) noexcept;
constructor

CBitStream

#
CBitStream(const void* pBuffer, ETL_UINT32 byteSize) noexcept;
constructor

CBitStream

#
CBitStream(CBitStream&& other) noexcept;
operator

operator=

#
CBitStream& operator=(CBitStream&& other) noexcept;
function

WriteBits

#
bool WriteBits(const void* data, ETL_UINT32 bitCount) noexcept;
function

Write

#
template<typename T> bool Write(const T& value) noexcept

Writes a trivially copyable value, bit by bit.

The template members must be defined in the header. They used to be only declared, with the definition in the .cpp, so they only existed for the types the .cpp itself instantiated. Any 'Write< ETL_UINT32 >' in a client project became an unresolved external symbol, and the static library still built without complaint.

function

WriteAligned

#
template<typename T> bool WriteAligned(const T& value) noexcept

Aligns the write position to a byte, then writes the value.

function

WriteBool

#
bool WriteBool(bool value) noexcept;
function

WriteBytes

#
bool WriteBytes(const void* data, ETL_UINT32 bytes) noexcept;
function

ReadBits

#
bool ReadBits(void* data, ETL_UINT32 bitCount) noexcept;
function

Read

#
template<typename T> bool Read(T& value) noexcept

Reads a trivially copyable value, bit by bit.

function

ReadAligned

#
template<typename T> bool ReadAligned(T& value) noexcept

Aligns the read position to a byte, then reads the value.

function

ReadBool

#
bool ReadBool(bool& value) noexcept;
function

ReadBytes

#
bool ReadBytes(void* data, ETL_UINT32 bytes) noexcept;
function

IgnoreBits

#
void IgnoreBits(ETL_UINT32 bitCount) noexcept

Advances the read position by bitCount bits without reading them.

function

AlignReadToByte

#
void AlignReadToByte() noexcept;
function

AlignWriteToByte

#
void AlignWriteToByte() noexcept;
function

SetReadOffset

#
void SetReadOffset(ETL_UINT32 bitOffset) noexcept

Moves the read position to an absolute offset, in bits.

Alias of SetReadBitPos, kept because the header already declared it. It forwards the call instead of duplicating the code.
function

SetWriteOffset

#
void SetWriteOffset(ETL_UINT32 bitOffset) noexcept

Moves the write position to an absolute offset, in bits.

function

GetNumberOfBitsUsed

#
ETL_UINT32 GetNumberOfBitsUsed() const noexcept

Number of bits already written to the stream.

The three functions below are aliases of GetBitsWritten, GetBytesWritten and GetBitsRemaining. The header declared them with no implementation. They forward the call.
function

GetNumberOfBytesUsed

#
ETL_UINT32 GetNumberOfBytesUsed() const noexcept
function

GetNumberOfUnreadBits

#
ETL_UINT32 GetNumberOfUnreadBits() const noexcept
function

TryReadBits

#
bool TryReadBits(void* pDst, ETL_UINT32 bitCount) noexcept;
function

TryRead

#
template<typename T> bool TryRead(T& value) noexcept

Reads a value only when enough bits remain. Otherwise nothing is consumed.

function

PeekBits

#
bool PeekBits(void* pDst, ETL_UINT32 bitCount) const noexcept;
function

IsWriteByteAligned

#
bool IsWriteByteAligned() const noexcept;
function

IsReadByteAligned

#
bool IsReadByteAligned() const noexcept;
function

CanWriteBits

#
bool CanWriteBits(ETL_UINT32 bitCount) const noexcept;
function

CanReadBits

#
bool CanReadBits(ETL_UINT32 bitCount) const noexcept;
function

ReserveBits

#
bool ReserveBits(ETL_UINT32 bitCount) noexcept

Ensures capacity for bitCount more bits of writing.

Alias of Grow, which was the implemented function.
function

Reset

#
void Reset() noexcept;
function

Clear

#
void Clear() noexcept;
function

RewindRead

#
void RewindRead() noexcept;
function

RewindWrite

#
void RewindWrite() noexcept;
function

PatchBits

#
bool PatchBits(const void* pSrc, ETL_UINT32 bitCount, ETL_UINT32 bitOffset) noexcept;
function

GetReadBitPos

#
ETL_UINT32 GetReadBitPos() const noexcept;
function

GetWriteBitPos

#
ETL_UINT32 GetWriteBitPos() const noexcept;
function

SetReadBitPos

#
void SetReadBitPos(ETL_UINT32 pos) noexcept;
function

SetWriteBitPos

#
void SetWriteBitPos(ETL_UINT32 pos) noexcept;
function

GetBitsWritten

#
ETL_UINT32 GetBitsWritten() const noexcept;
function

GetBytesWritten

#
ETL_UINT32 GetBytesWritten() const noexcept;
function

GetBitsRemaining

#
ETL_UINT32 GetBitsRemaining() const noexcept;
function

GetData

#
ETL_UINT8 * GetData() noexcept;
function

GetData

#
const ETL_UINT8 * GetData() const noexcept;
function

GetCapacityBits

#
ETL_UINT32 GetCapacityBits() const noexcept;
function

GetCapacityBytes

#
ETL_UINT32 GetCapacityBytes() const noexcept;
const

InvalidPos

#
static constexpr ETL_UINT32 InvalidPos = 0xFFFFFFFF;