summaryrefslogtreecommitdiffstats
path: root/src/lib/memarea.c
blob: 747ea8b843bb2e295795b63bd0503686e862d727 (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
/* Copyright (c) 2017-2018 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "memarea.h"

struct memarea {
	const void *data;
	size_t size;

	memarea_free_callback_t *callback;
	void *context;

	int refcount;
};

static struct memarea memarea_empty = {
	.refcount = 1,
};

#undef memarea_init
struct memarea *
memarea_init(const void *data, size_t size,
	     memarea_free_callback_t *callback, void *context)
{
	struct memarea *area;

	i_assert(callback != NULL);

	area = i_new(struct memarea, 1);
	area->data = data;
	area->size = size;
	area->callback = callback;
	area->context = context;
	area->refcount = 1;
	return area;
}

struct memarea *memarea_init_empty(void)
{
	i_assert(memarea_empty.refcount > 0);
	memarea_empty.refcount++;
	return &memarea_empty;
}

void memarea_ref(struct memarea *area)
{
	i_assert(area->refcount > 0);
	area->refcount++;
}

void memarea_unref(struct memarea **_area)
{
	struct memarea *area = *_area;

	*_area = NULL;
	i_assert(area->refcount > 0);

	if (--area->refcount > 0)
		return;
	i_assert(area != &memarea_empty);
	area->callback(area->context);
	i_free(area);
}

void memarea_free_without_callback(struct memarea **_area)
{
	struct memarea *area = *_area;

	*_area = NULL;
	i_assert(memarea_get_refcount(area) == 1);
	i_free(area);
}

unsigned int memarea_get_refcount(struct memarea *area)
{
	i_assert(area->refcount > 0);
	return area->refcount;
}

const void *memarea_get(struct memarea *area, size_t *size_r)
{
	*size_r = area->size;
	return area->data;
}

size_t memarea_get_size(struct memarea *area)
{
	return area->size;
}

void memarea_free_callback_noop(void *context ATTR_UNUSED)
{
}