aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
blob: 9ad9190331d3fd940becc0fc7d9b01439de9a416 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "config.h"
#include "system.h"
#include "utils.h"

void __strbuild(char *buf, int size,
		const char *file, int line,
		const char *fmt, ...)
{
	va_list ap;
	int len;

	va_start(ap, fmt);
	len = vsnprintf(NULL, 0, fmt, ap);
	va_end(ap);

	if (len < 0) {
		fprintf(stderr, "%s:%d: ", file, line);
		perror("");
		exit(EXIT_FAILURE);
	}
	if (len >= size) {
		fprintf(stderr, "%s:%d: error: not enough space, "
			"have %d, need at least %d\n",
			file, line,
			size, len + 1);
		exit(EXIT_FAILURE);
	}

	va_start(ap, fmt);
	len = vsnprintf(buf, size, fmt, ap);
	va_end(ap);

	assert(len >= 0);
}

int str_has_suffix(const char *str, const char *suffix)
{
	int str_len = strlen(str);
	int suffix_len = strlen(suffix);
	return ((str_len > suffix_len)
		&& (strcmp(str + str_len - suffix_len, suffix) == 0));
}

void assert_db_exists(void)
{
	const char *db_path = ftag_config_get(FC_DATABASE_PATH);
	if (file_exists(db_path))
		return;

	if (errno == ENOENT) {
		fprintf(stderr,
			"ftag: database not found at \"%s\", "
			"have you run \"ftag init\"?\n",
			db_path);
	}
	else {
		perror(db_path);
	}
	exit(EXIT_FAILURE);
}

uint32_t sum(const char *file)
{
	FILE *stream = fopen(file, "r");
	uint8_t buf[4096];
	size_t buf_len;
	uint32_t sum = 5381;
	if (!file) {
		fprintf(stderr, "fopen: \"%s\": ", file);
		perror("");
		exit(EXIT_FAILURE);
	}
	while ((buf_len = fread(&buf, 1, sizeof(buf), stream)) != 0) {
		for (int i = 0; i < buf_len; i++) {
			uint8_t next = buf[i];
			sum = sum*33 + next;
		}
	}
	if (ferror(stream)) {
		fprintf(stderr, "fread: \"%s\": ", file);
		perror("");
		exit(EXIT_FAILURE);
	}
	fclose(stream);
	return sum;
}

time_t time_from_str(const char *str)
{
	int rc;
	struct tm tm;
	memset(&tm, 0, sizeof(tm));
	rc = sscanf(str, "%d-%d-%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
	if (rc <= 0) {
		perror("sscanf");
		exit(EXIT_FAILURE);
	}
	tm.tm_year -= 1900;
	tm.tm_mon -= 1;
	return mktime(&tm);
}