String.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include "AKString.h"
  2. #include "StdLibExtras.h"
  3. #include "StringBuilder.h"
  4. #include <LibC/stdarg.h>
  5. namespace AK {
  6. bool String::operator==(const String& other) const
  7. {
  8. if (!m_impl)
  9. return !other.m_impl;
  10. if (!other.m_impl)
  11. return false;
  12. if (length() != other.length())
  13. return false;
  14. return !memcmp(characters(), other.characters(), length());
  15. }
  16. String String::empty()
  17. {
  18. return StringImpl::the_empty_stringimpl();
  19. }
  20. String String::isolated_copy() const
  21. {
  22. if (!m_impl)
  23. return { };
  24. if (!m_impl->length())
  25. return empty();
  26. char* buffer;
  27. auto impl = StringImpl::create_uninitialized(length(), buffer);
  28. memcpy(buffer, m_impl->characters(), m_impl->length());
  29. return String(move(*impl));
  30. }
  31. String String::substring(size_t start, size_t length) const
  32. {
  33. ASSERT(m_impl);
  34. ASSERT(start + length <= m_impl->length());
  35. // FIXME: This needs some input bounds checking.
  36. char* buffer;
  37. auto new_impl = StringImpl::create_uninitialized(length, buffer);
  38. memcpy(buffer, characters() + start, length);
  39. buffer[length] = '\0';
  40. return new_impl;
  41. }
  42. Vector<String> String::split(const char separator) const
  43. {
  44. if (is_empty())
  45. return { };
  46. Vector<String> v;
  47. size_t substart = 0;
  48. for (size_t i = 0; i < length(); ++i) {
  49. char ch = characters()[i];
  50. if (ch == separator) {
  51. size_t sublen = i - substart;
  52. if (sublen != 0)
  53. v.append(substring(substart, sublen));
  54. substart = i + 1;
  55. }
  56. }
  57. size_t taillen = length() - substart;
  58. if (taillen != 0)
  59. v.append(substring(substart, taillen));
  60. if (characters()[length() - 1] == separator)
  61. v.append(empty());
  62. return v;
  63. }
  64. ByteBuffer String::to_byte_buffer() const
  65. {
  66. if (!m_impl)
  67. return nullptr;
  68. return ByteBuffer::copy(reinterpret_cast<const byte*>(characters()), length());
  69. }
  70. unsigned String::to_uint(bool& ok) const
  71. {
  72. unsigned value = 0;
  73. for (size_t i = 0; i < length(); ++i) {
  74. if (characters()[i] < '0' || characters()[i] > '9') {
  75. ok = false;
  76. return 0;
  77. }
  78. value = value * 10;
  79. value += characters()[i] - '0';
  80. }
  81. ok = true;
  82. return value;
  83. }
  84. String String::format(const char* fmt, ...)
  85. {
  86. StringBuilder builder;
  87. va_list ap;
  88. va_start(ap, fmt);
  89. builder.appendvf(fmt, ap);
  90. va_end(ap);
  91. return builder.to_string();
  92. }
  93. }