ref
This commit is contained in:
42
runtime/ref.c
Normal file
42
runtime/ref.c
Normal file
@@ -0,0 +1,42 @@
|
||||
#include "ref.h"
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
void *rc_alloc(size_t size, void (*destructor)(void *self))
|
||||
{
|
||||
printf("rc_alloc %zu bytes\n", size);
|
||||
ref_header *header = malloc(sizeof(ref_header) + size);
|
||||
if (!header)
|
||||
{
|
||||
exit(69);
|
||||
}
|
||||
|
||||
header->ref_count = 1;
|
||||
header->destructor = destructor;
|
||||
|
||||
return (void *)(header + 1);
|
||||
}
|
||||
|
||||
void rc_retain(void *obj)
|
||||
{
|
||||
printf("rc_retain\n");
|
||||
ref_header *header = ((ref_header *)obj) - 1;
|
||||
header->ref_count++;
|
||||
}
|
||||
|
||||
void rc_release(void *obj)
|
||||
{
|
||||
ref_header *header = ((ref_header *)obj) - 1;
|
||||
printf("rc_release\n");
|
||||
if (--header->ref_count == 0)
|
||||
{
|
||||
if (header->destructor)
|
||||
{
|
||||
header->destructor(obj);
|
||||
}
|
||||
|
||||
free(header);
|
||||
printf("rc_free\n");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user