common.h 1.46 KB
Newer Older
Vicent Marti committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Vicent Marti committed
3 4 5 6
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */
7 8 9
#ifndef INCLUDE_common_h__
#define INCLUDE_common_h__

10
#include "git2_util.h"
11
#include "errors.h"
12

13
/*
14 15 16
* Include the declarations for deprecated functions; this ensures
* that they're decorated with the proper extern/visibility attributes.
*/
17 18
#include "git2/deprecated.h"

19
#include "posix.h"
20

21
/**
22
 * Initialize a structure with a version.
23
 */
24 25 26 27 28 29
GIT_INLINE(void) git__init_structure(void *structure, size_t len, unsigned int version)
{
	memset(structure, 0, len);
	*((int*)structure) = version;
}
#define GIT_INIT_STRUCTURE(S,V) git__init_structure(S, sizeof(*S), V)
30

31 32 33 34
#define GIT_INIT_STRUCTURE_FROM_TEMPLATE(PTR,VERSION,TYPE,TPL) do { \
	TYPE _tmpl = TPL; \
	GIT_ERROR_CHECK_VERSION(&(VERSION), _tmpl.version, #TYPE);      \
	memcpy((PTR), &_tmpl, sizeof(_tmpl)); } while (0)
35 36

/**
Ben Straub committed
37 38
 * Check a versioned structure for validity
 */
39
GIT_INLINE(int) git_error__check_version(const void *structure, unsigned int expected_max, const char *name)
Ben Straub committed
40
{
Vicent Marti committed
41
	unsigned int actual;
Vicent Marti committed
42

Ben Straub committed
43
	if (!structure)
44
		return 0;
Ben Straub committed
45

Vicent Marti committed
46
	actual = *(const unsigned int*)structure;
Ben Straub committed
47
	if (actual > 0 && actual <= expected_max)
48
		return 0;
Ben Straub committed
49

50
	git_error_set(GIT_ERROR_INVALID, "invalid version %d on %s", actual, name);
51
	return -1;
Ben Straub committed
52
}
53
#define GIT_ERROR_CHECK_VERSION(S,V,N) if (git_error__check_version(S,V,N) < 0) return -1
Ben Straub committed
54

55
#endif