summaryrefslogtreecommitdiff
path: root/include/sized_string.h
diff options
context:
space:
mode:
authorrobojumper <robojumper@gmail.com>2024-05-29 20:02:57 +0200
committerrobojumper <robojumper@gmail.com>2024-06-02 00:06:17 +0200
commite6429777e5090a5cc07c0fa1fe1fe91d42a772af (patch)
treea3f872fc8748f8d32a61fe7c477684cfe7fb91b6 /include/sized_string.h
parentbe163e6de709e5d44ed3faf38b69202d16bfe6b0 (diff)
sized_string (can we fix libc headers yet?)
Diffstat (limited to 'include/sized_string.h')
-rw-r--r--include/sized_string.h69
1 files changed, 69 insertions, 0 deletions
diff --git a/include/sized_string.h b/include/sized_string.h
new file mode 100644
index 00000000..1d619dda
--- /dev/null
+++ b/include/sized_string.h
@@ -0,0 +1,69 @@
+#ifndef SIZED_STRING_H
+#define SIZED_STRING_H
+
+#include <MSL_C/string.h>
+
+/**
+ * A statically sized string buffer used for resource
+ * identification where strings are guaranteed to be short.
+ *
+ * Note: We aren't aware of any other projects that use a similar
+ * class and given that SS has no debugging info anywhere it's hard
+ * to be certain about anything.
+ */
+template <size_t Size>
+struct SizedString {
+ SizedString() {
+ mChars[0] = '\0';
+ }
+
+ char mChars[Size];
+
+ char *operator&() {
+ return mChars;
+ }
+
+ const char *operator&() const {
+ return mChars;
+ }
+
+ void operator=(const char *src) {
+ if (src != mChars) {
+ mChars[0] = '\0';
+ operator+=(src);
+ }
+ }
+
+ void operator+=(const char *src) {
+ if (src != nullptr) {
+ size_t destLen = strlen(mChars);
+ size_t copyLen = strlen(src);
+
+ // Make sure copy length isnt more than destination length
+ if (destLen + copyLen + 1 >= Size) {
+ size_t tmpLen = Size - destLen;
+ copyLen = tmpLen - 1;
+ }
+
+ strncpy(mChars + destLen, src, copyLen);
+
+ // make sure string is null terminated
+ size_t offset = destLen + copyLen;
+ mChars[offset] = '\0';
+ }
+ }
+
+ int sprintf(const char *fmt, ...) {
+ va_list args;
+ va_start(args, fmt);
+
+ int printed = vsnprintf(this->mChars, Size, fmt, args);
+ if (printed != strlen(this->mChars)) {
+ this->mChars[0] = '\0';
+ }
+ va_end(list);
+ return printed;
+ }
+};
+
+#endif