traits.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #pragma once
  2. #include <util/generic/bitops.h>
  3. #include <util/generic/typetraits.h>
  4. #include <util/system/yassert.h>
  5. template <typename TWord>
  6. struct TBitSeqTraits {
  7. static constexpr ui8 NumBits = CHAR_BIT * sizeof(TWord);
  8. static constexpr TWord ModMask = static_cast<TWord>(NumBits - 1);
  9. static constexpr TWord DivShift = MostSignificantBitCT(NumBits);
  10. static inline TWord ElemMask(ui8 count) {
  11. // NOTE: Shifting by the type's length is UB, so we need this workaround.
  12. if (Y_LIKELY(count))
  13. return TWord(-1) >> (NumBits - count);
  14. return 0;
  15. }
  16. static inline TWord BitMask(ui8 pos) {
  17. return TWord(1) << pos;
  18. }
  19. static size_t NumOfWords(size_t bits) {
  20. return (bits + NumBits - 1) >> DivShift;
  21. }
  22. static bool Test(const TWord* data, ui64 pos, ui64 size) {
  23. Y_ASSERT(pos < size);
  24. return data[pos >> DivShift] & BitMask(pos & ModMask);
  25. }
  26. static TWord Get(const TWord* data, ui64 pos, ui8 width, TWord mask, ui64 size) {
  27. if (!width)
  28. return 0;
  29. Y_ASSERT((pos + width) <= size);
  30. size_t word = pos >> DivShift;
  31. TWord shift1 = pos & ModMask;
  32. TWord shift2 = NumBits - shift1;
  33. TWord res = data[word] >> shift1 & mask;
  34. if (shift2 < width) {
  35. res |= data[word + 1] << shift2 & mask;
  36. }
  37. return res;
  38. }
  39. static_assert(std::is_unsigned<TWord>::value, "Expected std::is_unsigned<T>::value.");
  40. static_assert((NumBits & (NumBits - 1)) == 0, "NumBits should be a power of 2.");
  41. };