enumset.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. *
  6. * Copyright (C) 2012,2014 International Business Machines
  7. * Corporation and others. All Rights Reserved.
  8. *
  9. ******************************************************************************
  10. */
  11. /**
  12. * \file
  13. * \brief C++: internal template EnumSet<>
  14. */
  15. #ifndef ENUMSET_H
  16. #define ENUMSET_H
  17. #include "unicode/utypes.h"
  18. #if U_SHOW_CPLUSPLUS_API
  19. U_NAMESPACE_BEGIN
  20. /* Can't use #ifndef U_HIDE_INTERNAL_API for the entire EnumSet class, needed in .h file declarations */
  21. /**
  22. * enum bitset for boolean fields. Similar to Java EnumSet<>.
  23. * Needs to range check. Used for private instance variables.
  24. * @internal
  25. * \cond
  26. */
  27. template<typename T, uint32_t minValue, uint32_t limitValue>
  28. class EnumSet {
  29. public:
  30. inline EnumSet() : fBools(0) {}
  31. inline EnumSet(const EnumSet<T,minValue,limitValue>& other) : fBools(other.fBools) {}
  32. inline ~EnumSet() {}
  33. #ifndef U_HIDE_INTERNAL_API
  34. inline void clear() { fBools=0; }
  35. inline void add(T toAdd) { set(toAdd, 1); }
  36. inline void remove(T toRemove) { set(toRemove, 0); }
  37. inline int32_t contains(T toCheck) const { return get(toCheck); }
  38. inline void set(T toSet, int32_t v) { fBools=(fBools&(~flag(toSet)))|(v?(flag(toSet)):0); }
  39. inline int32_t get(T toCheck) const { return (fBools & flag(toCheck))?1:0; }
  40. inline UBool isValidEnum(T toCheck) const { return (toCheck>=minValue&&toCheck<limitValue); }
  41. inline UBool isValidValue(int32_t v) const { return (v==0||v==1); }
  42. inline const EnumSet<T,minValue,limitValue>& operator=(const EnumSet<T,minValue,limitValue>& other) {
  43. fBools = other.fBools;
  44. return *this;
  45. }
  46. inline uint32_t getAll() const {
  47. return fBools;
  48. }
  49. #endif /* U_HIDE_INTERNAL_API */
  50. private:
  51. inline uint32_t flag(T toCheck) const { return (1<<(toCheck-minValue)); }
  52. private:
  53. uint32_t fBools;
  54. };
  55. /** \endcond */
  56. U_NAMESPACE_END
  57. #endif /* U_SHOW_CPLUSPLUS_API */
  58. #endif /* ENUMSET_H */