aboutsummaryrefslogtreecommitdiff
path: root/ssh/string_view.c
diff options
context:
space:
mode:
Diffstat (limited to 'ssh/string_view.c')
-rw-r--r--ssh/string_view.c72
1 files changed, 72 insertions, 0 deletions
diff --git a/ssh/string_view.c b/ssh/string_view.c
new file mode 100644
index 0000000..2f4f22a
--- /dev/null
+++ b/ssh/string_view.c
@@ -0,0 +1,72 @@
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "string_view.h"
+
+
+struct string_view string_view(const char *s, size_t len) {
+ return (struct string_view){.s = s, .len = len};
+}
+
+bool sv_equals(const struct string_view s, const char *cmp) {
+ return s.s && s.len == strlen(cmp) && memcmp(s.s, cmp, s.len) == 0;
+}
+
+bool sv_is_empty(const struct string_view s) {
+ return !s.s || s.len == 0;
+}
+
+bool sv_copy(const struct string_view s, char **output) {
+ if (s.s != NULL) {
+ char *buffer = malloc(s.len + 1);
+ if (!buffer) return false; // really should return TOMSG_ERR_MEMORY, but this will do
+ memcpy(buffer, s.s, s.len);
+ buffer[s.len] = '\0';
+ *output = buffer;
+ return true;
+ } else {
+ *output = NULL;
+ return false;
+ }
+}
+
+bool sv_parse_i64(const struct string_view s, int64_t *output) {
+ if (!s.s || s.len > 20) return false; // strlen(itoa(INT64_MIN)) == 20
+ char buf[21];
+ memcpy(buf, s.s, s.len);
+ buf[s.len] = '\0';
+ char *endp;
+ *output = strtoll(buf, &endp, 10);
+ return endp == buf + s.len;
+}
+
+struct string_view sv_tokenise_word(struct string_view *line) {
+ if (!line->s) return string_view(NULL, 0);
+
+ for (size_t i = 0; i < line->len; i++) {
+ if (line->s[i] == ' ') {
+ const struct string_view word = string_view(line->s, i);
+ line->s += i + 1;
+ line->len -= i + 1;
+ return word;
+ }
+ }
+
+ // No space found; if line is not empty, this is the final word
+ if (line->len > 0) {
+ const struct string_view word = *line;
+ *line = string_view(NULL, 0);
+ return word;
+ }
+
+ // Line is empty, so return NULL.
+ return string_view(NULL, 0);
+}
+
+void sv_skip_whitespace(struct string_view *line) {
+ if (!line->s) return;
+ while (line->len > 0 && isspace(line->s[0])) {
+ line->s++;
+ line->len--;
+ }
+}