BitMask.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2009-2016, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <anki/util/StdTypes.h>
  7. namespace anki
  8. {
  9. /// @addtogroup util_containers
  10. /// @{
  11. /// Easy bit mask manipulation.
  12. template<typename T>
  13. class BitMask
  14. {
  15. public:
  16. using Value = T;
  17. /// Default contructor. Will zero the mask.
  18. BitMask()
  19. : m_bitmask(static_cast<Value>(0))
  20. {
  21. }
  22. /// Construcor.
  23. /// @param mask The bits to enable.
  24. template<typename TInt>
  25. BitMask(TInt mask)
  26. : m_bitmask(static_cast<Value>(mask))
  27. {
  28. }
  29. /// Copy.
  30. BitMask(const BitMask& b) = default;
  31. /// Copy.
  32. BitMask& operator=(const BitMask& b) = default;
  33. /// Set or unset a bit at the given position.
  34. template<typename TInt>
  35. void set(TInt mask, Bool setBits = true)
  36. {
  37. Value maski = static_cast<Value>(mask);
  38. m_bitmask = (setBits) ? (m_bitmask | maski) : (m_bitmask & ~maski);
  39. }
  40. /// Unset a bit (set to zero) at the given position.
  41. template<typename TInt>
  42. void unset(TInt mask)
  43. {
  44. Value maski = static_cast<Value>(mask);
  45. m_bitmask &= ~maski;
  46. }
  47. /// Flip the bits at the given position. It will go from 1 to 0 or from 0 to
  48. /// 1.
  49. template<typename TInt>
  50. void flip(TInt mask)
  51. {
  52. Value maski = static_cast<Value>(mask);
  53. m_bitmask ^= maski;
  54. }
  55. /// Return true if the bit is set or false if it's not.
  56. template<typename TInt>
  57. Bool get(TInt mask) const
  58. {
  59. Value maski = static_cast<Value>(mask);
  60. return (m_bitmask & maski) == maski;
  61. }
  62. /// Given a mask check if any are enabled.
  63. template<typename TInt>
  64. Bool getAny(TInt mask) const
  65. {
  66. Value maski = static_cast<Value>(mask);
  67. return (m_bitmask & maski) != static_cast<Value>(0);
  68. }
  69. protected:
  70. Value m_bitmask;
  71. };
  72. /// @}
  73. } // end namespace anki