aboutsummaryrefslogtreecommitdiffstats
path: root/src/mem_pool.h
blob: cd1af2e77797fa1d6d0d02be2295c02d04ed040c (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
#ifndef RSPAMD_MEM_POOL_H
#define RSPAMD_MEM_POOL_H

#include <sys/types.h>
#include <glib.h>

typedef void (*pool_destruct_func)(void *ptr);

struct _pool_chain {
	u_char *begin;
	u_char *pos;
	size_t len;
	struct _pool_chain *next;
};

struct _pool_chain_shared {
	u_char *begin;
	u_char *pos;
	size_t len;
	gint lock;
	struct _pool_chain_shared *next;
};

struct _pool_destructors {
	pool_destruct_func func;
	void *data;
	struct _pool_destructors *prev;
};

typedef struct memory_pool_s {
	struct _pool_chain *cur_pool;
	struct _pool_chain *first_pool;
	struct _pool_chain_shared *shared_pool;
	struct _pool_destructors *destructors;
} memory_pool_t;

typedef struct memory_pool_stat_s {
	size_t bytes_allocated;
	size_t chunks_allocated;
	size_t shared_chunks_allocated;
	size_t chunks_freed;
} memory_pool_stat_t;

typedef struct memory_pool_rwlock_s {
	gint *__r_lock;
	gint *__w_lock;
} memory_pool_rwlock_t;

/* Allocate new memory poll */
memory_pool_t* memory_pool_new (size_t size);

/* Get memory from pool */
void* memory_pool_alloc (memory_pool_t* pool, size_t size);
/* Get memory and set it to zero */
void* memory_pool_alloc0 (memory_pool_t* pool, size_t size);
/* Make a copy of string in pool */
char* memory_pool_strdup (memory_pool_t* pool, const char *src);

/* Allocate piece of shared memory */
void* memory_pool_alloc_shared (memory_pool_t *pool, size_t size);
/* Lock and unlock chunk of shared memory in which pointer is placed */
void memory_pool_lock_shared (memory_pool_t *pool, void *pointer);
void memory_pool_unlock_shared (memory_pool_t *pool, void *pointer);

/* Add destructor callback to pool */
void memory_pool_add_destructor (memory_pool_t *pool, pool_destruct_func func, void *data);
/* Delete pool, free all its chunks and call destructors chain */
void memory_pool_delete (memory_pool_t *pool);

/* Mutexes operations */
gint* memory_pool_get_mutex (memory_pool_t *pool);
void memory_pool_lock_mutex (gint *mutex);
void memory_pool_unlock_mutex (gint *mutex);

/* Simple rwlock implementation */
memory_pool_rwlock_t* memory_pool_get_rwlock (memory_pool_t *pool);
void memory_pool_rlock_rwlock (memory_pool_rwlock_t *lock);
void memory_pool_wlock_rwlock (memory_pool_rwlock_t *lock);
void memory_pool_runlock_rwlock (memory_pool_rwlock_t *lock);
void memory_pool_wunlock_rwlock (memory_pool_rwlock_t *lock);

void memory_pool_stat (memory_pool_stat_t *st);

/* Get optimal pool size based on page size for this system */
size_t memory_pool_get_size ();

#define memory_pool_free(x) ((x)->len - ((x)->pos - (x)->begin))

#endif