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_none(void) { return (Object)NULL; }

Object object_create(VmState state, struct object_class *class, int priv_size) {
	(void)state;
	abort_if(state, 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(state, obj == NULL,
		"object_create: not enough memory for an objects");
	obj->class_data = class;
	obj->ref_count = 1;
	return (Object)obj;
}

char *object_priv(VmState state, Object object, struct object_class *class) {
	(void)state;
	abort_if(
		state, object == object_none(), "object_priv: no priv on none");
	struct object *obj = (struct object *)object;
	abort_if(state, obj->class_data != class,
		"object_priv: incompatible class");
	return obj->priv_data;
}

void object_hold(VmState state, Object object) {
	(void)state;
	if (object == object_none())
		return;
	struct object *obj = (struct object *)object;
	atomic_fetch_add_explicit(&obj->ref_count, 1, memory_order_relaxed);
}

void object_drop(VmState state, Object *objptr) {
	if (*objptr == object_none())
		return;
	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(state, obj);
		free(obj);
	}
	*objptr = object_none();
}

void dispatch_call(VmState state, Object object, const char *name) {
	if (object == object_none()) {
		abort_msg(state, "dispatch_call: cannot dispatch on none");
	}
	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, call->priv);
			return;
		}
		++call;
	}
	abort_msg(state, "dispatch_calll: no call found to dispatch");
}