/*
 * Copyright (c) 2026, Chloe M., et al.
 * Provided under the BSD-3 clause.
 *
 * Description: Bit operations
 * Author:      Chloe M.
 */

#ifndef _SDK_BITOPS_H_
#define _SDK_BITOPS_H_ 1

#include <ptdef.h>

#define BOPS_M1  0x5555555555555555ULL /* 01010101... */
#define BOPS_M2  0x3333333333333333ULL /* 00110011... */
#define BOPS_M4  0x0F0F0F0F0F0F0F0FULL /* 00001111... */
#define BOPS_M8  0x00FF00FF00FF00FFULL /* x4(0), x4(1) */
#define BOPS_M16 0x0000FFFF0000FFFFULL /* x16(0), x16(1) */
#define BOPS_M32 0x00000000FFFFFFFFULL /* x32(0), x32(1) */
#define BOPS_H0  0x0101010101010101ULL /* sum of 256^{0,1,2,3...} */

ALWAYS_INLINE static inline LONG
PopCnt(UQUAD Value)
{
    Value -= (Value >> 1) & BOPS_M1;
    Value =  (Value & BOPS_M2) + ((Value >> 2) & BOPS_M2);
    Value =  (Value + (Value >> 4)) & BOPS_M4;
    return (Value * BOPS_H0) >> 56;
}

#endif  /* !_SDK_BITOPS_H_ */
