string.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #pragma once
  2. #include <vector>
  3. #include <string.h>
  4. #include <types/allocator.hpp>
  5. #include <types/types.h>
  6. namespace types {
  7. template <typename Allocator =
  8. types::allocator_adapter<char, types::kernel_allocator>>
  9. class string : public std::vector<char, Allocator> {
  10. public:
  11. using inner_vector_type = std::vector<char, Allocator>;
  12. using size_type = typename inner_vector_type::size_type;
  13. using iterator = typename inner_vector_type::iterator;
  14. using const_iterator = typename inner_vector_type::const_iterator;
  15. static inline constexpr size_type npos = (-1U);
  16. public:
  17. constexpr string()
  18. : inner_vector_type()
  19. {
  20. this->reserve(8);
  21. this->push_back(0x00);
  22. }
  23. constexpr string(const char* str, size_type n = npos)
  24. : string()
  25. {
  26. this->append(str, n);
  27. }
  28. constexpr string& append(const char* str, size_type n = npos)
  29. {
  30. this->pop_back();
  31. while (n-- && *str != 0x00) {
  32. this->push_back(*str);
  33. ++str;
  34. }
  35. this->push_back(0x00);
  36. return *this;
  37. }
  38. constexpr string& append(const string& str)
  39. {
  40. return this->append(str.data());
  41. }
  42. constexpr string& operator+=(const char c)
  43. {
  44. this->insert(this->end(), c);
  45. return *this;
  46. }
  47. constexpr string& operator+=(const char* str)
  48. {
  49. return this->append(str);
  50. }
  51. constexpr string& operator+=(const string& str)
  52. {
  53. return this->append(str);
  54. }
  55. constexpr bool operator==(const string& rhs) const
  56. {
  57. return strcmp(c_str(), rhs.c_str()) == 0;
  58. }
  59. constexpr string& assign(const char* str, size_type n = npos)
  60. {
  61. this->clear();
  62. return this->append(str, n);
  63. }
  64. constexpr string substr(size_type pos, size_type n = npos)
  65. {
  66. return string(this->m_arr + pos, n);
  67. }
  68. constexpr const char* c_str(void) const noexcept
  69. {
  70. return this->data();
  71. }
  72. constexpr void clear()
  73. {
  74. inner_vector_type::clear();
  75. this->push_back(0x00);
  76. }
  77. constexpr char pop(void)
  78. {
  79. this->pop_back();
  80. auto& ref = inner_vector_type::back();
  81. char c = ref;
  82. ref = 0x00;
  83. return c;
  84. }
  85. constexpr iterator end() noexcept
  86. { return --inner_vector_type::end(); }
  87. constexpr const_iterator end() const noexcept
  88. { return --inner_vector_type::cend(); }
  89. constexpr const_iterator cend() const noexcept
  90. { return --inner_vector_type::cend(); }
  91. };
  92. } // namespace types