string.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. };
  71. } // namespace types
  72. #endif