string.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #pragma once
  2. #include <kernel/stdio.h>
  3. #include <types/allocator.hpp>
  4. #include <types/types.h>
  5. #include <types/vector.hpp>
  6. #ifdef __cplusplus
  7. namespace types {
  8. template <template <typename _value_type> class Allocator = kernel_allocator>
  9. class string : public types::vector<char, Allocator> {
  10. public:
  11. using inner_vector_type = types::vector<char, Allocator>;
  12. using size_type = typename inner_vector_type::size_type;
  13. static inline constexpr size_type npos = (-1U);
  14. public:
  15. explicit string(size_type capacity = 8)
  16. : inner_vector_type(capacity)
  17. {
  18. this->push_back(0x00);
  19. }
  20. string(const char* str, size_type n = npos)
  21. : string()
  22. {
  23. this->append(str, n);
  24. }
  25. string(const string& str)
  26. : inner_vector_type((const inner_vector_type&)str)
  27. {
  28. }
  29. string(string&& str)
  30. : inner_vector_type((inner_vector_type &&) move(str))
  31. {
  32. }
  33. string& append(const char* str, size_type n = npos)
  34. {
  35. this->pop_back();
  36. while (n-- && *str != 0x00) {
  37. this->push_back(*str);
  38. ++str;
  39. }
  40. this->push_back(0x00);
  41. return *this;
  42. }
  43. string& append(const string& str)
  44. {
  45. return this->append(str.data());
  46. }
  47. string& append(string&& str)
  48. {
  49. return this->append(str.data());
  50. }
  51. string& operator+=(const char c)
  52. {
  53. *this->back() = c;
  54. this->push_back(0x00);
  55. return *this;
  56. }
  57. string& operator+=(const char* str)
  58. {
  59. return this->append(str);
  60. }
  61. string& operator+=(const string& str)
  62. {
  63. return this->append(str);
  64. }
  65. string& operator+=(string&& str)
  66. {
  67. return this->append(move(str));
  68. }
  69. string substr(size_type pos, size_type n = npos)
  70. {
  71. return string(this->m_arr + pos, n);
  72. }
  73. const char* c_str(void) const noexcept
  74. {
  75. return this->data();
  76. }
  77. void clear(void)
  78. {
  79. inner_vector_type::clear();
  80. this->push_back(0x00);
  81. }
  82. char pop(void)
  83. {
  84. this->pop_back();
  85. auto iter = inner_vector_type::back();
  86. char c = *iter;
  87. *iter = 0x00;
  88. return c;
  89. }
  90. typename inner_vector_type::iterator_type back(void)
  91. {
  92. return --inner_vector_type::back();
  93. }
  94. typename inner_vector_type::const_iterator_type back(void) const
  95. {
  96. return --inner_vector_type::back();
  97. }
  98. typename inner_vector_type::const_iterator_type cback(void) const
  99. {
  100. return --inner_vector_type::cback();
  101. }
  102. };
  103. } // namespace types
  104. #endif