String.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <cstring>
  2. #include <cstdio>
  3. #include "common/utils/String.h"
  4. String::String() : length(0) {
  5. data[0] = '\0';
  6. }
  7. String::String(const char* str) : length(0) {
  8. for(; length < MAX_LENGTH - 1 && str[length] != '\0'; length++) {
  9. data[length] = str[length];
  10. }
  11. data[length] = '\0';
  12. }
  13. String::String(const String& other) : length(other.length) {
  14. memcpy(data, other.data, length + 1);
  15. }
  16. String& String::operator=(const String& other) {
  17. if(this != &other) {
  18. length = other.length;
  19. memcpy(data, other.data, length + 1);
  20. }
  21. return *this;
  22. }
  23. bool String::operator==(const String& other) const {
  24. return length == other.length && strcmp(data, other.data) == 0;
  25. }
  26. bool String::operator!=(const String& other) const {
  27. return !(*this == other);
  28. }
  29. String::operator const char*() const {
  30. return data;
  31. }
  32. char String::operator[](uint index) const {
  33. return data[index];
  34. }
  35. uint String::getLength() const {
  36. return length;
  37. }
  38. String& String::append(const char* str) {
  39. for(uint i = 0; length < MAX_LENGTH - 1 && str[i] != '\0'; length++, i++) {
  40. data[length] = str[i];
  41. }
  42. data[length] = '\0';
  43. return *this;
  44. }
  45. String& String::append(u8 u) {
  46. return append(static_cast<s8>(u));
  47. }
  48. String& String::append(u16 u) {
  49. return append("%hu", u);
  50. }
  51. String& String::append(u32 u) {
  52. return append("%u", u);
  53. }
  54. String& String::append(u64 u) {
  55. return append("%lu", u);
  56. }
  57. String& String::append(s8 c) {
  58. if(length < MAX_LENGTH - 1) {
  59. data[length++] = c;
  60. data[length] = '\0';
  61. }
  62. return *this;
  63. }
  64. String& String::append(s16 s) {
  65. return append("%hi", s);
  66. }
  67. String& String::append(s32 s) {
  68. return append("%i", s);
  69. }
  70. String& String::append(s64 s) {
  71. return append("%li", s);
  72. }
  73. String& String::append(float f) {
  74. return append("%.2f", f);
  75. }
  76. String& String::append(bool b) {
  77. return append(b ? "true" : "false");
  78. }
  79. String& String::clear() {
  80. data[0] = '\0';
  81. length = 0;
  82. return *this;
  83. }