StringBuffer.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #ifndef STRINGBUFFER_H
  2. #define STRINGBUFFER_H
  3. #include <cstring>
  4. template<int N>
  5. class StringBuffer final {
  6. int length;
  7. int hash;
  8. char data[N];
  9. void addToHash(char c) {
  10. hash = 31 * hash + c;
  11. }
  12. void addToHash(int from, int to) {
  13. for(int i = from; i < to; i++) {
  14. addToHash(data[i]);
  15. }
  16. }
  17. public:
  18. StringBuffer() : length(0), hash(0) {
  19. data[0] = '\0';
  20. }
  21. StringBuffer(const char* str) : StringBuffer() {
  22. append(str);
  23. }
  24. bool operator==(const char* str) const {
  25. return strcmp(data, str) == 0;
  26. }
  27. bool operator==(const StringBuffer& other) const {
  28. return length == other.length && other == data;
  29. }
  30. bool operator!=(const char* str) const {
  31. return !((*this) == str);
  32. }
  33. bool operator!=(const StringBuffer& other) const {
  34. return !((*this) == other);
  35. }
  36. operator const char*() const {
  37. return data;
  38. }
  39. char operator[](int index) const {
  40. return data[index];
  41. }
  42. int getLength() const {
  43. return length;
  44. }
  45. StringBuffer& append(char c) {
  46. if(length < N - 1) {
  47. data[length++] = c;
  48. addToHash(c);
  49. data[length] = '\0';
  50. }
  51. return *this;
  52. }
  53. StringBuffer& append(const char* str) {
  54. for(int i = 0; length < N - 1 && str[i] != '\0'; length++, i++) {
  55. data[length] = str[i];
  56. addToHash(str[i]);
  57. }
  58. data[length] = '\0';
  59. return *this;
  60. }
  61. template<typename T>
  62. StringBuffer& append(const char* format, const T& t) {
  63. int left = N - length;
  64. int written = snprintf(data + length, left, format, t);
  65. int oldLength = length;
  66. if(written < left) {
  67. length += written;
  68. } else {
  69. length = N - 1;
  70. }
  71. addToHash(oldLength, length);
  72. return *this;
  73. }
  74. StringBuffer& append(int i) {
  75. return append("%d", i);
  76. }
  77. StringBuffer& append(float i) {
  78. return append("%.2f", i);
  79. }
  80. StringBuffer& append(bool b) {
  81. return b ? append("true") : append("false");
  82. }
  83. StringBuffer& clear() {
  84. length = 0;
  85. hash = 0;
  86. data[0] = '\0';
  87. return *this;
  88. }
  89. int hashCode() const {
  90. return hash;
  91. }
  92. };
  93. template<int N>
  94. bool operator==(const char* str, const StringBuffer<N> buffer) {
  95. return buffer == str;
  96. }
  97. template<int N>
  98. bool operator!=(const char* str, const StringBuffer<N> buffer) {
  99. return buffer != str;
  100. }
  101. #endif