set_of_chars.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Optimized implementation of a set of chars
  2. // Complexity of the contains() operation: constant
  3. // Required space: 32 bytes
  4. //
  5. // Platform: ISO C++ 98/11/14
  6. // $Id$
  7. //
  8. // (c) __vic 2011
  9. #ifndef __VIC_SET_OF_CHARS_H
  10. #define __VIC_SET_OF_CHARS_H
  11. #include<__vic/defs.h>
  12. #include<cstring>
  13. #if __cpp_initializer_lists
  14. #include<initializer_list>
  15. #endif
  16. namespace __vic {
  17. //////////////////////////////////////////////////////////////////////////////
  18. class set_of_chars
  19. {
  20. unsigned char set[32] // set of 256 bits
  21. #if __cpp_initializer_lists
  22. = {}
  23. #endif
  24. ;
  25. public:
  26. #if __cpp_initializer_lists
  27. __VIC_CONSTEXPR_FUNC set_of_chars() __VIC_DEFAULT_CTR
  28. template<class Iter>
  29. __VIC_CONSTEXPR14 set_of_chars(Iter begin, Iter end) { add(begin, end); }
  30. __VIC_CONSTEXPR14 set_of_chars(const char *c_str) { add(c_str); }
  31. __VIC_CONSTEXPR14 set_of_chars(std::initializer_list<char> set) { add(set); }
  32. #else
  33. set_of_chars() { clear(); }
  34. template<class Iter>
  35. set_of_chars(Iter begin, Iter end) { assign(begin, end); }
  36. set_of_chars(const char *c_str) { assign(c_str); }
  37. #endif
  38. __VIC_CONSTEXPR_FUNC bool contains(char ch) const
  39. {
  40. return set[static_cast<unsigned char>(ch) >> 3] & (1 << (ch & 7));
  41. }
  42. __VIC_CONSTEXPR14 void add(char ch)
  43. {
  44. // Set the corresponding bit
  45. set[static_cast<unsigned char>(ch) >> 3] |= 1 << (ch & 7);
  46. }
  47. __VIC_CONSTEXPR14 void remove(char ch)
  48. {
  49. // Reset the corresponding bit
  50. set[static_cast<unsigned char>(ch) >> 3] &= ~(1 << (ch & 7));
  51. }
  52. template<class Iter>
  53. __VIC_CONSTEXPR14 void add(Iter begin, Iter end)
  54. {
  55. while(begin != end) add(*begin++);
  56. }
  57. __VIC_CONSTEXPR14 void add(const char *c_str)
  58. {
  59. while(*c_str) add(*c_str++);
  60. }
  61. template<class Iter>
  62. void assign(Iter begin, Iter end)
  63. {
  64. clear();
  65. add(begin, end);
  66. }
  67. void assign(const char *c_str)
  68. {
  69. clear();
  70. add(c_str);
  71. }
  72. #if __cpp_initializer_lists
  73. __VIC_CONSTEXPR14 void add(std::initializer_list<char> set)
  74. {
  75. add(set.begin(), set.end());
  76. }
  77. void assign(std::initializer_list<char> set)
  78. {
  79. clear();
  80. add(set);
  81. }
  82. #endif
  83. void clear() { std::memset(set, 0, sizeof set); }
  84. };
  85. //////////////////////////////////////////////////////////////////////////////
  86. } // namespace
  87. #endif // header guard