Newer
Older
Tardis / lang / object.c
// SPDX-License-Identifier: MIT
// Copyright (c) 2023 John Watts and the LuminaSensum contributors

#include "object.h"
#include "error.h"
#include <stdatomic.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

struct object {
	struct object_class *class_data;
	atomic_int ref_count;
	char priv_data[];
};

Object object_create(struct object_class *class, int priv_size) {
	abort_if(priv_size < 1, "object_create: priv_size too small");
	size_t size = sizeof(struct object) + priv_size;
	struct object *obj = calloc(size, 1);
	abort_if(
		obj == NULL, "object_create: not enough memory for an objects");
	obj->class_data = class;
	obj->ref_count = 1;
	return (Object)obj;
}

char *object_priv(Object object, struct object_class *class) {
	abort_if(object == NULL, "object_priv: no object");
	struct object *obj = (struct object *)object;
	abort_if(obj->class_data != class, "object_priv: incompatible class");
	return obj->priv_data;
}

void object_hold(Object object) {
	abort_if(object == NULL, "object_hold holding NULL");
	struct object *obj = (struct object *)object;
	atomic_fetch_add_explicit(&obj->ref_count, 1, memory_order_relaxed);
}

void object_drop(Object *objptr) {
	abort_if(*objptr == NULL, "object_drop dropping NULL");
	struct object *obj = (struct object *)*objptr;
	atomic_int count = atomic_fetch_sub_explicit(
		&obj->ref_count, 1, memory_order_relaxed);
	if (count == 1) {
		// We were the last user of the object, clean it up
		obj->class_data->cleanup(obj);
		free(obj);
	}
	*objptr = NULL;
}

void dispatch_call(VmState state, Object object, const char *name) {
	struct object *obj = (struct object *)object;
	struct object_call *call = obj->class_data->calls;
	while (call->name != NULL) {
		if (strcmp(call->name, name) == 0) {
			call->handler(state, obj);
			return;
		}
		++call;
	}
	abort_msg("no call found to dispatch");
}