aboutsummaryrefslogtreecommitdiff
path: root/util.c
blob: e210e34a44aa57316c788018984b7d8000836c53 (plain) (blame)
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
#include <util.h>
#include <arpa/inet.h>
#include <stdlib.h>

#include <stdio.h>
#include <errno.h>
#include <regex.h>

uint16_t inet_atop(const char *port) {
	return htons(atoi(port));
}

void herrc(int output, const char* funcName) {
	if (output < 0 && errno != EINTR) {
		perror(funcName);
	}
}

void herr(int output, const char* funcName) {
	if (output < 0) {
		perror(funcName);
		exit(errno);
	}
}

sds gsub(const sds str, const char* regex, const char* repl) {
	regex_t preg;
	regcomp(&preg, regex, 0);

	int strInd = 0;
	regmatch_t pmatch[1] = {
		{ .rm_so = 0, .rm_eo = 0, },
	};

	sds ret = sdsempty();
	// sdslen is in O(1) time
	while (strInd < sdslen(str)) {
		if (regexec(&preg, str + strInd, 1, pmatch, 0) > 0) {
			ret = sdscat(ret, str + strInd);
			break;
		}
		ret = sdscatlen(ret, str + strInd, pmatch[0].rm_so);
		ret = sdscat(ret, repl);
		strInd += pmatch[0].rm_eo;
	}

	return ret;
}