From 535aaf7e3c4145df815916e1449818d52f357987 Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Sun, 12 Jul 2020 21:36:48 +0200 Subject: Add tomsg client lib for C --- ssh/string_view.c | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 ssh/string_view.c (limited to 'ssh/string_view.c') 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 +#include +#include +#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--; + } +} -- cgit v1.2.3-70-g09d2