diff --git a/c_os/user/lib/StringView.h b/c_os/user/lib/StringView.h new file mode 100644 index 0000000..ad556fa --- /dev/null +++ b/c_os/user/lib/StringView.h @@ -0,0 +1,61 @@ +#ifndef C_OS_STRINGVIEW_H +#define C_OS_STRINGVIEW_H + +#include "user/lib/String.h" +#include "user/lib/Iterator.h" +#include + +namespace bse { + + class string_view { + private: + std::size_t len = 0; + char* buf = nullptr; + + public: + using iterator = ContinuousIterator; + + string_view() = default; + + string_view(char* str) : len(strlen(str)), buf(str) {} + + string_view(const string& str) : len(str.size()), buf(static_cast(str)) {} + + iterator begin() { return iterator(buf); } + iterator begin() const { return iterator(buf); } + iterator end() { return iterator(&buf[len]); } + iterator end() const { return iterator(&buf[len]); } + + explicit operator char*() { return buf; } + explicit operator char*() const { return buf; } + + char operator[](std::size_t pos) { return buf[pos]; } + char operator[](std::size_t pos) const { return buf[pos]; } + + bool operator==(const string_view& other) const { + return buf == other.buf; + } + + bool operator!=(const string_view& other) const { + return buf != other.buf; + } + + string_view substring(std::size_t first, std::size_t last) const { + if (first < 0 || first > len || last <= first || last > len) { + return nullptr; + } + + string_view new_view; + new_view.len = last - first; + new_view.buf = &buf[first]; + return new_view; + } + + std::size_t size() const { + return len; + } + }; + +} // namespace bse + +#endif //C_OS_STRINGVIEW_H