String.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <cstdio>
  2. #include <cstring>
  3. #include "utils/String.h"
  4. String::String() : String("") {
  5. }
  6. String::String(const char* str) : usedCapacity(1) {
  7. *this += str;
  8. }
  9. String& String::operator+=(const char* str) {
  10. usedCapacity--;
  11. size_t start = usedCapacity;
  12. while(usedCapacity + 1 < capacity && str[usedCapacity - start] != '\0') {
  13. data[usedCapacity] = str[usedCapacity - start];
  14. usedCapacity++;
  15. }
  16. data[usedCapacity++] = '\0';
  17. return *this;
  18. }
  19. String& String::operator+=(char c) {
  20. if(usedCapacity + 1 < capacity) {
  21. data[usedCapacity - 1] = c;
  22. data[usedCapacity] = '\0';
  23. usedCapacity++;
  24. }
  25. return *this;
  26. }
  27. String& String::operator+=(char32_t c) {
  28. if(c <= 0x7F) {
  29. *this += (char) c;
  30. } else if(c <= 0x7FF) {
  31. *this += (char) (0xC0 | ((c >> 6) & 0x1F));
  32. *this += (char) (0x80 | ((c >> 0) & 0x3F));
  33. } else if(c <= 0xFFFF) {
  34. *this += (char) (0xE0 | ((c >> 12) & 0xF));
  35. *this += (char) (0x80 | ((c >> 6) & 0x3F));
  36. *this += (char) (0x80 | ((c >> 0) & 0x3F));
  37. } else {
  38. *this += (char) (0xF0 | ((c >> 18) & 0x7));
  39. *this += (char) (0x80 | ((c >> 12) & 0x3F));
  40. *this += (char) (0x80 | ((c >> 6) & 0x3F));
  41. *this += (char) (0x80 | ((c >> 0) & 0x3F));
  42. }
  43. return *this;
  44. }
  45. String& String::operator+=(unsigned int i) {
  46. usedCapacity += snprintf(data + usedCapacity - 1, capacity - usedCapacity, "%u", i);
  47. return *this;
  48. }
  49. String& String::operator+=(double d) {
  50. usedCapacity += snprintf(data + usedCapacity - 1, capacity - usedCapacity, (d == (long) d) ? "%lg.0" : "%lg", d);
  51. return *this;
  52. }
  53. String String::operator+(const char* str) const {
  54. String s(this->data);
  55. s += str;
  56. return s;
  57. }
  58. String::operator const char*() const {
  59. return data;
  60. }
  61. size_t String::getLength() const {
  62. return usedCapacity - 1;
  63. }
  64. bool String::isFull() const {
  65. return usedCapacity >= capacity;
  66. }
  67. bool String::operator==(const String& other) const {
  68. return usedCapacity == other.usedCapacity && *this == other.data;
  69. }
  70. bool String::operator!=(const String& other) const {
  71. return !(*this == other);
  72. }
  73. bool String::operator==(const char* other) const {
  74. return strcmp(data, other) == 0;
  75. }
  76. bool String::operator!=(const char* other) const {
  77. return !(*this == other);
  78. }