From b1296f2c97c6fdc1c6a9922dc09c951b5cafdc12 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Mon, 29 Oct 2018 21:49:54 +0100 Subject: Initial commit --- include/dchat/StringView.hpp | 95 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 include/dchat/StringView.hpp (limited to 'include/dchat/StringView.hpp') diff --git a/include/dchat/StringView.hpp b/include/dchat/StringView.hpp new file mode 100644 index 0000000..659610a --- /dev/null +++ b/include/dchat/StringView.hpp @@ -0,0 +1,95 @@ +#pragma once + +#include "types.hpp" +#include +#include + +namespace dchat +{ + template + class BasicStringView + { + public: + BasicStringView() : data(nullptr), size(0) + { + + } + + BasicStringView(const BasicStringView &other) : data(other.data), size(other.size) + { + + } + + BasicStringView(const CharType *_data) : data(_data), size(strlen(_data)) + { + + } + + BasicStringView(const CharType *_data, usize _size) : data(_data), size(_size) + { + + } + + BasicStringView& operator = (const BasicStringView &other) + { + data = other.data; + size = other.size; + return *this; + } + + BasicStringView(BasicStringView &&other) + { + data = other.data; + size = other.size; + + other.data = nullptr; + other.size = 0; + } + + bool equals(const BasicStringView &other) const + { + if(size != other.size) return false; + return memcmp(data, other.data, size * sizeof(CharType)) == 0; + } + + bool operator == (const BasicStringView &other) const + { + return equals(other); + } + + bool operator != (const BasicStringView &other) const + { + return !equals(other); + } + + CharType operator [] (usize index) const + { + assert(index < size); + return data[index]; + } + + // Returns -1 if substr not found. + // TODO: Make this more efficient + usize find(const BasicStringView &substr, usize offset = 0) const + { + if(substr.size == 0) + return -1; + + if(offset + substr.size > size) + return -1; + + for(usize i = offset; i < size - (substr.size - 1); ++i) + { + if(memcmp(data + i, substr.data, substr.size * sizeof(CharType)) == 0) + return i; + } + return -1; + } + + const CharType *data; + usize size; + }; + + using StringView = BasicStringView; + using StringViewUtf32 = BasicStringView; +} -- cgit v1.2.3