aboutsummaryrefslogtreecommitdiff
path: root/src/utils.h
blob: e382ace73477c320a14d0480aa3cd0fd8cb12b64 (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
#ifndef UTILS_H
#define UTILS_H

/* Utility functions for manipulating strings, time, and error codes. */

#include <stdio.h>
#include <stdint.h>
#include <time.h>

/* Internals of strbuild. */
void __strbuild(char *buf, int size,
		const char *file, int line,
		const char *fmt, ...);

/* Safely create a formatted string and write it to BUF. BUF shall be a buffer
 * of size at least SIZE. BUF can be stack-allocated. If the formatting cannot
 * be performed, exit(3) is called. This function is not meant to be called
 * directly: the macro strbuild should be used. The code is adapted from the
 * make_message function of the vsnprintf(3) manual page, section "examples". */
#define strbuild(buf, fmt, ...) \
	__strbuild(buf, sizeof(buf), __FILE__, __LINE__, fmt, __VA_ARGS__)

#define strbuild_with_size(buf, size, fmt, ...)				\
	__strbuild(buf, size, __FILE__, __LINE__, fmt, __VA_ARGS__)

int str_has_suffix(const char *str, const char *suffix);

/* Abort if the database does not exist. */
void assert_db_exists(void);

/* Compute something that identifies the content of FILE. Algorithm by Dan
 * Bernstein from http://www.cse.yorku.ca/~oz/hash.html via
 * https://stackoverflow.com/a/7666577/20138083. */
uint32_t sum(const char *file);

/* Return an integer timestamp from a date string of the format YYYY-MM-DD. */
time_t time_from_str(const char *str);

#endif