]> code.delx.au - pulseaudio/blob - polyp/memblock.c
0571f5dae87859137c18f6bb20cdbf764447a8f2
[pulseaudio] / polyp / memblock.c
1 /* $Id$ */
2
3 /***
4 This file is part of polypaudio.
5
6 polypaudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 or (at your option) any later version.
10
11 polypaudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with polypaudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <assert.h>
29 #include <string.h>
30
31 #include "memblock.h"
32 #include "xmalloc.h"
33
34 static unsigned memblock_count = 0, memblock_total = 0;
35
36 struct pa_memblock *pa_memblock_new(size_t length) {
37 struct pa_memblock *b = pa_xmalloc(sizeof(struct pa_memblock)+length);
38 b->type = PA_MEMBLOCK_APPENDED;
39 b->ref = 1;
40 b->length = length;
41 b->data = b+1;
42 memblock_count++;
43 memblock_total += length;
44 return b;
45 }
46
47 struct pa_memblock *pa_memblock_new_fixed(void *d, size_t length) {
48 struct pa_memblock *b = pa_xmalloc(sizeof(struct pa_memblock));
49 b->type = PA_MEMBLOCK_FIXED;
50 b->ref = 1;
51 b->length = length;
52 b->data = d;
53 memblock_count++;
54 memblock_total += length;
55 return b;
56 }
57
58 struct pa_memblock *pa_memblock_new_dynamic(void *d, size_t length) {
59 struct pa_memblock *b = pa_xmalloc(sizeof(struct pa_memblock));
60 b->type = PA_MEMBLOCK_DYNAMIC;
61 b->ref = 1;
62 b->length = length;
63 b->data = d;
64 memblock_count++;
65 memblock_total += length;
66 return b;
67 }
68
69 struct pa_memblock* pa_memblock_ref(struct pa_memblock*b) {
70 assert(b && b->ref >= 1);
71 b->ref++;
72 return b;
73 }
74
75 void pa_memblock_unref(struct pa_memblock*b) {
76 assert(b && b->ref >= 1);
77 b->ref--;
78
79 if (b->ref == 0) {
80 if (b->type == PA_MEMBLOCK_DYNAMIC)
81 pa_xfree(b->data);
82
83 memblock_count--;
84 memblock_total -= b->length;
85
86 pa_xfree(b);
87 }
88 }
89
90 void pa_memblock_unref_fixed(struct pa_memblock *b) {
91 void *d;
92
93 assert(b && b->ref >= 1);
94
95 if (b->ref == 1) {
96 pa_memblock_unref(b);
97 return;
98 } else {
99 d = pa_xmalloc(b->length);
100 memcpy(d, b->data, b->length);
101 b->data = d;
102 b->type = PA_MEMBLOCK_DYNAMIC;
103 b->ref--;
104 }
105 }
106
107 unsigned pa_memblock_get_count(void) {
108 return memblock_count;
109 }
110
111 unsigned pa_memblock_get_total(void) {
112 return memblock_total;
113 }