diff --git a/src/ox/std/CMakeLists.txt b/src/ox/std/CMakeLists.txt index 0050e5a4e..5bd0ac2b1 100644 --- a/src/ox/std/CMakeLists.txt +++ b/src/ox/std/CMakeLists.txt @@ -20,6 +20,7 @@ install( byteswap.hpp memops.hpp random.hpp + string.hpp strops.hpp std.hpp types.hpp diff --git a/src/ox/std/std.hpp b/src/ox/std/std.hpp index 93c9ad20c..f0858ad61 100644 --- a/src/ox/std/std.hpp +++ b/src/ox/std/std.hpp @@ -12,4 +12,5 @@ #include "memops.hpp" #include "random.hpp" #include "strops.hpp" +#include "string.hpp" #include "types.hpp" diff --git a/src/ox/std/string.hpp b/src/ox/std/string.hpp new file mode 100644 index 000000000..4086a3734 --- /dev/null +++ b/src/ox/std/string.hpp @@ -0,0 +1,84 @@ +/* + * Copyright 2015 - 2017 gtalent2@gmail.com + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include "types.hpp" + +namespace ox { + +// Bounded String +template +class bstring { + private: + uint8_t m_buff[buffLen]; + + public: + bstring(const char *str); + + const bstring &operator=(const char *str); + + const bstring &operator=(char *str); + + /** + * Returns the number of characters in this string. + */ + size_t len(); + + /** + * Returns the number of bytes used for this string. + */ + size_t size(); +}; + +template +bstring::bstring(const char *str) { + *this = str; +} + +template +const bstring &bstring::operator=(const char *str) { + return *this = (const char*) str; +} + +template +const bstring &bstring::operator=(char *str) { + auto strLen = ox_strlen(str) + 1; + if (size() < strLen) { + strLen = size(); + } + ox_memcpy(m_buff, str, strLen); + // make sure last element is a null terminator + m_buff[size() - 1] = 0; + return *this; +} + +template +size_t bstring::len() { + size_t length = 0; + for (size_t i = 0; i < buffLen; i++) { + auto b = m_buff[i]; + if (b) { + if ((b & (1 << 8)) == 0) { // normal ASCII character + length++; + } else if ((b & (256 << 6)) == (256 << 6)) { // start of UTF-8 character + length++; + } + } else { + break; + } + } + return length; +} + +template +size_t bstring::size() { + return buffLen; +} + +} diff --git a/src/ox/std/types.hpp b/src/ox/std/types.hpp index bc200352e..c57108f9c 100644 --- a/src/ox/std/types.hpp +++ b/src/ox/std/types.hpp @@ -5,6 +5,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + #pragma once typedef signed char int8_t;