RtlpFindBitsInline - NtDoc

Native API online documentation, based on the System Informer (formerly Process Hacker) phnt headers
#ifndef _NTRTL_H
#ifndef PHNT_NO_INLINE_RTL_BITMAP

// Private implementation shared by the clear-bit and set-bit searches.
// Scan ULONGs so a ULONG-aligned buffer needs no extra 64-bit padding.
_Success_(return != MAXULONG)
_Check_return_
FORCEINLINE
ULONG
NTAPI_INLINE
RtlpFindBitsInline(
    _In_ PRTL_BITMAP BitMapHeader,
    _In_ ULONG NumberToFind,
    _In_ ULONG HintIndex,
    _In_ BOOLEAN FindSetBits
    )
{
    ULONG size = BitMapHeader->SizeOfBitMap;
    ULONG index;
    ULONG limit;
    ULONG runStart;
    ULONG runLength;
    ULONG bits;
    ULONG count;
    ULONG skip;
    ULONG length;
    ULONG invert = FindSetBits ? 0 : MAXULONG;

    if (HintIndex >= size)
        HintIndex = 0;

    // Native empty searches return the effective hint on a byte boundary.
    if (NumberToFind == 0)
        return HintIndex & ~7u;
    if (NumberToFind > size)
        return MAXULONG;

    index = HintIndex;
    limit = size;

    for (;;)
    {
        runStart = index;
        runLength = 0;

        while (index < limit)
        {
            if (NumberToFind - runLength > limit - index)
                break;

            count = 32 - (index & 31);
            if (count > limit - index)
                count = limit - index;

            bits = (BitMapHeader->Buffer[index >> 5] ^ invert) >> (index & 31);
            if (count < 32)
                bits &= (1u << count) - 1;

            if (!_BitScanForward(&skip, bits))
            {
                runLength = 0;
                index += count;
                continue;
            }

            if (skip != 0)
            {
                runLength = 0;
                index += skip;
                count -= skip;
                bits >>= skip;
            }

            if (runLength == 0)
                runStart = index;

            if (!_BitScanForward(&length, ~bits))
                length = 32;
            if (length > count)
                length = count;

            if (length >= NumberToFind - runLength)
                return runStart;

            runLength += length;
            index += length;
        }

        if (HintIndex == 0)
            return MAXULONG;

        // Wrap once; a run starting before the hint may extend beyond it.
        // Preserve the native ULONG addition used for this search bound.
        limit = HintIndex + NumberToFind;
        if (limit > size)
            limit = size;
        HintIndex = 0;
        index = 0;
    }
}

#endif
#endif

View code on GitHub

NtDoc

No description available.