compressed_enum_table.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #ifndef compressed_enum_table_h
  14. #define compressed_enum_table_h
  15. #include <cstdint>
  16. #include <cassert>
  17. #include <type_traits>
  18. template<typename Tenum, size_t Nbits, size_t Nitems>
  19. class CompressedEnumTable
  20. {
  21. public:
  22. uint32_t* data()
  23. {
  24. return mData;
  25. }
  26. const uint32_t* data() const
  27. {
  28. return mData;
  29. }
  30. Tenum get(size_t index) const
  31. {
  32. assert(index >= 0 && index < Nitems);
  33. size_t wordIndex = index / ITEMS_PER_WORD;
  34. size_t offset = (index % ITEMS_PER_WORD) * Nbits;
  35. return static_cast<Tenum>((mData[wordIndex] >> offset) & VALUE_MASK);
  36. }
  37. void set(size_t index, Tenum val)
  38. {
  39. assert(index >= 0 && index < Nitems);
  40. size_t wordIndex = index / ITEMS_PER_WORD;
  41. size_t offset = (index % ITEMS_PER_WORD) * Nbits;
  42. uint32_t v = static_cast<uint32_t>(val) << offset;
  43. mData[wordIndex] = (mData[wordIndex] & ~(VALUE_MASK << offset)) | v;
  44. }
  45. static constexpr size_t getWordIndex(size_t index)
  46. {
  47. return index / ITEMS_PER_WORD;
  48. }
  49. static constexpr size_t byteSize()
  50. {
  51. return WORD_COUNT * 4;
  52. }
  53. static constexpr size_t count()
  54. {
  55. return Nitems;
  56. }
  57. protected:
  58. static_assert(32 % Nbits == 0, "Nbits must divide 32");
  59. static const size_t ITEMS_PER_WORD = 32 / Nbits;
  60. static const size_t WORD_COUNT = ( Nbits * Nitems + 31 ) / 32;
  61. static const uint32_t VALUE_MASK = (1 << Nbits) - 1;
  62. uint32_t mData[WORD_COUNT];
  63. };
  64. #endif /* compressed_enum_table_h */