string.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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& append(const char* str, size_type n = npos)
  30. {
  31. this->pop_back();
  32. while (n-- && *str != 0x00) {
  33. this->push_back(*str);
  34. ++str;
  35. }
  36. this->push_back(0x00);
  37. return *this;
  38. }
  39. string& append(const string& str)
  40. {
  41. return this->append(str.data());
  42. }
  43. string& operator+=(const char c)
  44. {
  45. *this->back() = c;
  46. this->push_back(0x00);
  47. return *this;
  48. }
  49. string& operator+=(const char* str)
  50. {
  51. return this->append(str);
  52. }
  53. string& operator+=(const string& str)
  54. {
  55. return this->append(str);
  56. }
  57. string substr(size_type pos, size_type n = npos)
  58. {
  59. return string(this->m_arr + pos, n);
  60. }
  61. const char* c_str(void) const noexcept
  62. {
  63. return this->data();
  64. }
  65. void clear(void)
  66. {
  67. inner_vector_type::clear();
  68. this->push_back(0x00);
  69. }
  70. char pop(void)
  71. {
  72. this->pop_back();
  73. auto iter = inner_vector_type::back();
  74. char c = *iter;
  75. *iter = 0x00;
  76. return c;
  77. }
  78. typename inner_vector_type::iterator_type back(void)
  79. {
  80. return --inner_vector_type::back();
  81. }
  82. typename inner_vector_type::const_iterator_type back(void) const
  83. {
  84. return --inner_vector_type::back();
  85. }
  86. typename inner_vector_type::const_iterator_type cback(void) const
  87. {
  88. return --inner_vector_type::cback();
  89. }
  90. };
  91. } // namespace types
  92. #endif