aboutsummaryrefslogtreecommitdiff
path: root/util.c
blob: d07899f7427e415483eb5eba03944743c1af4039 (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
80
81
82
#include <stdlib.h>
#include <string.h>
#include "util.h"

struct string_list *string_split(const char *string, char delim) {
	const char *loc = string;
	int size = 2; /* rest of string, NULL terminator */
	int index = 0;
	char delims[2] = {0};
	char *saveptr = NULL;
	struct string_list *list = calloc(1, sizeof(struct string_list));

	if (!list)
		goto finish;

	list->source = strdup(string);
	if (!list->source)
		goto finish;

	while((loc = strchr(loc, delim))) {
		size++;
		while (*loc && *loc == delim) loc++;
	}

	list->list = calloc(size, sizeof(char *));
	if (!list->list)
		goto finish;

	delims[0] = delim;

	while((loc = strtok_r(index == 0 ? list->source : NULL, delims, &saveptr))) {
		list->list[index++] = loc;
		if (index >= size)
			break;
	}

finish:
	return list;
}

void string_list_free(struct string_list *list) {
	if (list) {
		if (list->list) {
			free(list->list);
			list->list = NULL;
		}
		if (list->source) {
			free(list->source);
			list->source = NULL;
		}

		free(list);
	}
}

void string_truncate(char *string, size_t max_len) {
	size_t len = strlen(string) + 1;
	if (len <= max_len) return;

	strncpy(&string[max_len - 4], "...\0", 4);
}

void string_wrap(char *string, size_t max_len, size_t max_lines) {
	char *line = string;

	for (size_t i = 1; i < max_lines; i++) {
		char *p = line;
		char *prev;
		do {
			prev = p;
			p = strchr(prev+1, ' ');
		} while (p && p - line < (int)max_len);

		if (!p && strlen(line) < max_len) break;

		if (prev && prev != line) {
			line = prev + 1;
			*prev = '\n';
		}
	}
	string_truncate(line, max_len);
}