1#include <libexif/exif-mem.h>
2
3#include <stdlib.h>
4
5struct _ExifMem {
6	unsigned int ref_count;
7	ExifMemAllocFunc alloc_func;
8	ExifMemReallocFunc realloc_func;
9	ExifMemFreeFunc free_func;
10};
11
12/*! Default memory allocation function. */
13static void *
14exif_mem_alloc_func (ExifLong ds)
15{
16	return calloc ((size_t) ds, 1);
17}
18
19/*! Default memory reallocation function. */
20static void *
21exif_mem_realloc_func (void *d, ExifLong ds)
22{
23	return realloc (d, (size_t) ds);
24}
25
26/*! Default memory free function. */
27static void
28exif_mem_free_func (void *d)
29{
30	free (d);
31}
32
33ExifMem *
34exif_mem_new (ExifMemAllocFunc alloc_func, ExifMemReallocFunc realloc_func,
35	      ExifMemFreeFunc free_func)
36{
37	ExifMem *mem;
38
39	if (!alloc_func && !realloc_func)
40		return NULL;
41	mem = alloc_func ? alloc_func (sizeof (ExifMem)) :
42		           realloc_func (NULL, sizeof (ExifMem));
43	if (!mem) return NULL;
44	mem->ref_count = 1;
45
46	mem->alloc_func   = alloc_func;
47	mem->realloc_func = realloc_func;
48	mem->free_func    = free_func;
49
50	return mem;
51}
52
53void
54exif_mem_ref (ExifMem *mem)
55{
56	if (!mem) return;
57	mem->ref_count++;
58}
59
60void
61exif_mem_unref (ExifMem *mem)
62{
63	if (!mem) return;
64	if (!--mem->ref_count)
65		exif_mem_free (mem, mem);
66}
67
68void
69exif_mem_free (ExifMem *mem, void *d)
70{
71	if (!mem) return;
72	if (mem->free_func) {
73		mem->free_func (d);
74		return;
75	}
76}
77
78void *
79exif_mem_alloc (ExifMem *mem, ExifLong ds)
80{
81	if (!mem) return NULL;
82	if (mem->alloc_func || mem->realloc_func)
83		return mem->alloc_func ? mem->alloc_func (ds) :
84					 mem->realloc_func (NULL, ds);
85	return NULL;
86}
87
88void *
89exif_mem_realloc (ExifMem *mem, void *d, ExifLong ds)
90{
91	return (mem && mem->realloc_func) ? mem->realloc_func (d, ds) : NULL;
92}
93
94ExifMem *
95exif_mem_new_default (void)
96{
97	return exif_mem_new (exif_mem_alloc_func, exif_mem_realloc_func,
98			     exif_mem_free_func);
99}
100