From fbfc078e9f44c1c1e95c9c484f1d5650bcf631b7 Mon Sep 17 00:00:00 2001 From: Benji Dial Date: Sat, 27 Jul 2024 16:57:39 -0400 Subject: lots and lots of userspace stuff --- euler/source/std/string.cpp | 86 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 euler/source/std/string.cpp (limited to 'euler/source/std/string.cpp') diff --git a/euler/source/std/string.cpp b/euler/source/std/string.cpp new file mode 100644 index 0000000..31c47a5 --- /dev/null +++ b/euler/source/std/string.cpp @@ -0,0 +1,86 @@ +#include +#include + +namespace std { + + int stoi(const std::string &str, size_t *pos, int base) { + //TODO: exceptions + + size_t i = 0; + while (isspace(str[i])) + ++i; + + bool is_negative = false; + if (str[i] == '-') { + is_negative = true; + ++i; + } + else if (str[i] == '+') + ++i; + + if ((base == 16 || base == 0) && str[i] == '0' && + (str[i + 1] == 'x' || str[i + 1] == 'X')) { + base = 16; + i += 2; + } + + else if ((base == 8 || base == 0) && str[i] == '0') { + base = 8; + ++i; + } + + else if (base == 0) + base = 10; + + int value = 0; + + while (true) { + char c = str[i]; + if (c >= '0' && c < '0' + base) + value = value * base + c - '0'; + else if (c >= 'a' && c < 'a' + base - 10) + value = value * base + c - 'a' + 10; + else if (c >= 'A' && c < 'A' + base - 10) + value = value * base + c - 'A' + 10; + else + break; + } + + if (pos != 0) + *pos = i; + + return is_negative ? -value : value; + + } + + std::string to_string(int value) { + + int max_place = 1; + int places = 1; + while (max_place <= value / 10) { + max_place *= 10; + ++places; + } + + std::string s; + s.resize(places); + + for (int i = 0; i < places; ++i) { + s[i] = (value / max_place) % 10 + '0'; + max_place /= 10; + } + + return s; + + } + + std::string operator +(std::string &&lhs, std::string &&rhs) { + std::string s = std::move(lhs); + s.resize(lhs.size() + rhs.size()); + for (size_t i = 0; i < rhs.size(); ++i) + s[lhs.size() + i] = rhs[i]; + rhs.clear(); + return s; + } + +} -- cgit v1.2.3