1 #include <libexif/exif-mem.h>
2
3 #include <stdlib.h>
4
5 struct _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. */
13 static void *
exif_mem_alloc_func(ExifLong ds)14 exif_mem_alloc_func (ExifLong ds)
15 {
16 return calloc ((size_t) ds, 1);
17 }
18
19 /*! Default memory reallocation function. */
20 static void *
exif_mem_realloc_func(void * d,ExifLong ds)21 exif_mem_realloc_func (void *d, ExifLong ds)
22 {
23 return realloc (d, (size_t) ds);
24 }
25
26 /*! Default memory free function. */
27 static void
exif_mem_free_func(void * d)28 exif_mem_free_func (void *d)
29 {
30 free (d);
31 }
32
33 ExifMem *
exif_mem_new(ExifMemAllocFunc alloc_func,ExifMemReallocFunc realloc_func,ExifMemFreeFunc free_func)34 exif_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
53 void
exif_mem_ref(ExifMem * mem)54 exif_mem_ref (ExifMem *mem)
55 {
56 if (!mem) return;
57 mem->ref_count++;
58 }
59
60 void
exif_mem_unref(ExifMem * mem)61 exif_mem_unref (ExifMem *mem)
62 {
63 if (!mem) return;
64 if (!--mem->ref_count)
65 exif_mem_free (mem, mem);
66 }
67
68 void
exif_mem_free(ExifMem * mem,void * d)69 exif_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
78 void *
exif_mem_alloc(ExifMem * mem,ExifLong ds)79 exif_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
88 void *
exif_mem_realloc(ExifMem * mem,void * d,ExifLong ds)89 exif_mem_realloc (ExifMem *mem, void *d, ExifLong ds)
90 {
91 return (mem && mem->realloc_func) ? mem->realloc_func (d, ds) : NULL;
92 }
93
94 ExifMem *
exif_mem_new_default(void)95 exif_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