summaryrefslogtreecommitdiff
path: root/src/util/staticstr.h
blob: b7d0790c4fd6e550c540aa4ebfd4f36cece56de9 (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
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */
#ifndef INCLUDE_stackstr_h__
#define INCLUDE_stackstr_h__

#include "git2_util.h"

typedef struct {
	/* Length of / number of bytes used by `data`. */
	size_t len;

	/* Size of the allocated `data` buffer. */
	size_t size;

	/* The actual string buffer data. */
	char data[GIT_FLEX_ARRAY];
} git_staticstr;

#define git_staticstr_with_size(__size) \
	struct { \
		size_t len; \
		size_t size; \
		char data[__size]; \
	}

#define git_staticstr_init(__str, __size) \
	do { \
		(__str)->len = 0; \
		(__str)->size = __size; \
		(__str)->data[0] = '\0'; \
	} while(0)

#define git_staticstr_offset(__str) \
	((__str)->data + (__str)->len)

#define git_staticstr_remain(__str) \
	((__str)->len > (__str)->size ? 0 : ((__str)->size - (__str)->len))

#define git_staticstr_increase(__str, __len) \
	do { ((__str)->len += __len); } while(0)

#define git_staticstr_consume_bytes(__str, __len) \
	do { git_staticstr_consume(__str, (__str)->data + __len); } while(0)

#define git_staticstr_consume(__str, __end) \
	do { \
		if (__end > (__str)->data && \
		    __end <= (__str)->data + (__str)->len) { \
			size_t __consumed = __end - (__str)->data; \
			memmove((__str)->data, __end, (__str)->len - __consumed); \
			(__str)->len -= __consumed; \
			(__str)->data[(__str)->len] = '\0'; \
		} \
	} while(0)

#define git_staticstr_clear(__str) \
	do { \
		(__str)->len = 0; \
		(__str)->data[0] = 0; \
	} while(0)

#endif