readonly_bitvector.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #pragma once
  2. #include "bitvector.h"
  3. #include "traits.h"
  4. #include <util/memory/blob.h>
  5. #include <cstring>
  6. template <typename T>
  7. class TReadonlyBitVector {
  8. public:
  9. using TWord = T;
  10. using TTraits = TBitSeqTraits<TWord>;
  11. TReadonlyBitVector()
  12. : Size_()
  13. , Data_()
  14. {
  15. }
  16. explicit TReadonlyBitVector(const TBitVector<T>& vector)
  17. : Size_(vector.Size_)
  18. , Data_(vector.Data_.data())
  19. {
  20. }
  21. bool Test(ui64 pos) const {
  22. return TTraits::Test(Data_, pos, Size_);
  23. }
  24. TWord Get(ui64 pos, ui8 width, TWord mask) const {
  25. return TTraits::Get(Data_, pos, width, mask, Size_);
  26. }
  27. TWord Get(ui64 pos, ui8 width) const {
  28. return Get(pos, width, TTraits::ElemMask(width));
  29. }
  30. ui64 Size() const {
  31. return Size_;
  32. }
  33. const T* Data() const {
  34. return Data_;
  35. }
  36. static void SaveForReadonlyAccess(IOutputStream* out, const TBitVector<T>& bv) {
  37. ::Save(out, bv.Size_);
  38. ::Save(out, static_cast<ui64>(bv.Data_.size()));
  39. ::SavePodArray(out, bv.Data_.data(), bv.Data_.size());
  40. }
  41. virtual TBlob LoadFromBlob(const TBlob& blob) {
  42. size_t read = 0;
  43. auto cursor = [&]() { return blob.AsUnsignedCharPtr() + read; };
  44. auto readToPtr = [&](auto* ptr) {
  45. memcpy(ptr, cursor(), sizeof(*ptr));
  46. read += sizeof(*ptr);
  47. };
  48. readToPtr(&Size_);
  49. ui64 wordCount{};
  50. readToPtr(&wordCount);
  51. Data_ = reinterpret_cast<const T*>(cursor());
  52. read += wordCount * sizeof(T);
  53. return blob.SubBlob(read, blob.Size());
  54. }
  55. private:
  56. ui64 Size_;
  57. const T* Data_;
  58. };