ref
This commit is contained in:
1
runtime/.gitignore
vendored
Normal file
1
runtime/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.build
|
||||
6
runtime/build.sh
Executable file
6
runtime/build.sh
Executable file
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
mkdir -p .build
|
||||
clang -c runtime.c -o .build/runtime.o
|
||||
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");
|
||||
}
|
||||
}
|
||||
13
runtime/ref.h
Normal file
13
runtime/ref.h
Normal file
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct
|
||||
{
|
||||
int ref_count;
|
||||
void (*destructor)(void *self);
|
||||
} ref_header;
|
||||
|
||||
void *rc_alloc(size_t size, void (*destructor)(void *self));
|
||||
void rc_retain(void *obj);
|
||||
void rc_release(void *obj);
|
||||
1
runtime/runtime.c
Normal file
1
runtime/runtime.c
Normal file
@@ -0,0 +1 @@
|
||||
#include "ref.c"
|
||||
Reference in New Issue
Block a user