aboutsummaryrefslogtreecommitdiff
path: root/ssh/string_view.c
blob: ba052360093c8c7f6c30b09061f35c00617b7b60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#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--;
	}
}

void sv_skip(struct string_view *line, size_t num) {
	if (!line->s) return;
	if (num > line->len) num = line->len;
	line->s += num;
	line->len -= num;
}