summaryrefslogtreecommitdiff
path: root/euler/include/std/string.hpp
blob: c5a3d99139a2bb7be57cd86eebee25aff423b70d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma once

#include <std/fwd/string.hpp>

#include <cstddef>
#include <vector>

namespace std {

  class string {

    std::vector<char> characters;

  public:
    static const size_t npos = (size_t)-1;

    constexpr string() : characters({'\0'}) {}

    constexpr string(const string &other)
    : characters(other.characters) {}

    constexpr string(string &&other) noexcept
    : characters(std::move(other.characters)) {}

    constexpr string(const char *s) {
      size_t count = 0;
      while (s[count] != '\0')
        ++count;
      characters.resize(count + 1);
      for (size_t i = 0; i <= count; ++i)
        characters[i] = s[i];
    }

    constexpr ~string() {}

    constexpr string &operator =(const string &str) {
      characters = str.characters;
      return *this;
    }

    constexpr string &operator =(string &&str) noexcept {
      characters = std::move(str.characters);
      return *this;
    }

    constexpr size_t size() const noexcept {
      return characters.size() - 1;
    }

    constexpr void resize(size_t count) {
      if (count < characters.size() - 1) {
        characters.resize(count + 1);
        characters[count] = '\0';
      }
      else if (count > characters.size() - 1)
        characters.resize(count + 1);
    }

    constexpr void clear() noexcept {
      resize(0);
    }

    constexpr const char *data() const noexcept {
      return characters.data();
    }

    constexpr char *data() noexcept {
      return characters.data();
    }

    constexpr char &operator[](size_t pos) {
      return characters[pos];
    }

    constexpr const char &operator[](size_t pos) const {
      return characters[pos];
    }

    constexpr string &erase(size_t index = 0, size_t count = npos) {
      count = std::min(count, size() - index);
      for (size_t i = index; i + count < size(); ++i)
        characters[i] = characters[i + count];
      resize(size() - count);
      return *this;
    }

  };

}