SkBitSet.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2011 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #ifndef SkBitSet_DEFINED
  8. #define SkBitSet_DEFINED
  9. #include "include/private/SkTemplates.h"
  10. class SkBitSet {
  11. public:
  12. explicit SkBitSet(int numberOfBits) {
  13. SkASSERT(numberOfBits >= 0);
  14. fDwordCount = (numberOfBits + 31) / 32; // Round up size to 32-bit boundary.
  15. if (fDwordCount > 0) {
  16. fBitData.reset((uint32_t*)sk_calloc_throw(fDwordCount * sizeof(uint32_t)));
  17. }
  18. }
  19. /** Set the value of the index-th bit to true. */
  20. void set(int index) {
  21. uint32_t mask = 1 << (index & 31);
  22. uint32_t* chunk = this->internalGet(index);
  23. SkASSERT(chunk);
  24. *chunk |= mask;
  25. }
  26. bool has(int index) const {
  27. const uint32_t* chunk = this->internalGet(index);
  28. uint32_t mask = 1 << (index & 31);
  29. return chunk && SkToBool(*chunk & mask);
  30. }
  31. // Calls f(unsigned) for each set value.
  32. template<typename FN>
  33. void getSetValues(FN f) const {
  34. const uint32_t* data = fBitData.get();
  35. for (unsigned i = 0; i < fDwordCount; ++i) {
  36. if (uint32_t value = data[i]) { // There are set bits
  37. unsigned index = i * 32;
  38. for (unsigned j = 0; j < 32; ++j) {
  39. if (0x1 & (value >> j)) {
  40. f(index | j);
  41. }
  42. }
  43. }
  44. }
  45. }
  46. private:
  47. std::unique_ptr<uint32_t, SkFunctionWrapper<void, void, sk_free>> fBitData;
  48. size_t fDwordCount; // Dword (32-bit) count of the bitset.
  49. uint32_t* internalGet(int index) const {
  50. size_t internalIndex = index / 32;
  51. if (internalIndex >= fDwordCount) {
  52. return nullptr;
  53. }
  54. return fBitData.get() + internalIndex;
  55. }
  56. };
  57. #endif