-
Notifications
You must be signed in to change notification settings - Fork 0
/
rc_ptr.c
38 lines (35 loc) · 814 Bytes
/
rc_ptr.c
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
#include "rc_ptr.h"
#include <stdlib.h>
static size_t usedMem = 0;
typedef struct RCPtrHdr{
unsigned int retainCount;
size_t size;
char buf[];
}RCPtrHdr;
#define getHdr(x) ((RCPtrHdr *)( (char*)x - sizeof(RCPtrHdr)))
void *rcMalloc(size_t size){
RCPtrHdr *hdr = (RCPtrHdr *)malloc(sizeof(RCPtrHdr) + size);
hdr->retainCount = 1;
hdr->size = size;
usedMem += size;
return (void*)hdr->buf;
}
void rcRetain(void *ptr){
RCPtrHdr *hdr = getHdr(ptr);
hdr->retainCount++;
}
void rcFree(void *ptr){
RCPtrHdr *hdr = getHdr(ptr);
hdr->retainCount--;
if(!hdr->retainCount) {
free(hdr);
usedMem -= hdr->size;
}
}
extern size_t rcSize(void *ptr){
RCPtrHdr *hdr = getHdr(ptr);
return hdr->size;
}
extern size_t rcUsedMem(){
return usedMem;
}