aboutsummaryrefslogtreecommitdiff
path: root/libk/string.h
diff options
context:
space:
mode:
authorAqua-sama <aqua@iserlohn-fortress.net>2021-01-31 23:24:42 +0200
committerAqua-sama <aqua@iserlohn-fortress.net>2021-01-31 23:24:42 +0200
commit950f164a2eb851dbab0aacb44334f0b687d123e8 (patch)
treea31c6e3140de2b208eca99e82535d740e9ca4039 /libk/string.h
parentInitial commit (diff)
downloadkernel.cpp-950f164a2eb851dbab0aacb44334f0b687d123e8.tar.xz
libk: add its own makefile
Diffstat (limited to 'libk/string.h')
-rw-r--r--libk/string.h69
1 files changed, 69 insertions, 0 deletions
diff --git a/libk/string.h b/libk/string.h
new file mode 100644
index 0000000..deb6fde
--- /dev/null
+++ b/libk/string.h
@@ -0,0 +1,69 @@
+#pragma once
+#include "types.h"
+
+constexpr size_t strlen(const char *str) {
+ int len = 0;
+ while (str[len])
+ ++len;
+ return len;
+}
+
+/* reverse: reverse string s in place */
+constexpr void reverse(char s[]) {
+ int i, j;
+ char c;
+
+ for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
+ c = s[i];
+ s[i] = s[j];
+ s[j] = c;
+ }
+}
+
+/* itoa: convert n to characters in s */
+template <int base = 10> constexpr void itoa(int n, char s[]) {
+ int i, sign;
+
+ if ((sign = n) < 0) /* record sign */
+ n = -n; /* make n positive */
+
+ i = 0;
+ do { /* generate digits in reverse order */
+ s[i++] = "0123456789abcdef"[n % base]; /* get next digit */
+ } while ((n /= base) > 0); /* delete it */
+
+ if (sign < 0)
+ s[i++] = '-';
+
+ s[i] = '\0';
+
+ reverse(s);
+}
+
+class String {
+public:
+ class Iterator {
+ friend class String;
+
+ public:
+ char next() { return p->buffer[pos++]; }
+ operator bool() const { return (pos < p->m_length); }
+
+ private:
+ Iterator(const String *s) : p(s) {}
+
+ size_t pos = 0;
+ const String *p;
+ };
+
+ friend class Iterator;
+
+ String(const char *d) : buffer{d}, m_length{strlen(d)} {}
+ String(const char *d, size_t l) : buffer{d}, m_length{l} {}
+
+ Iterator begin() const { return Iterator(this); }
+
+private:
+ const char *const buffer;
+ const size_t m_length;
+};