string.hpp 2.5 KB

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