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 <stddef.h>
#include <string.h>

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

void object_drop(struct object **objptr) {
	abort_if(*objptr == NULL, "object_drop dropping NULL");
	struct object *obj = *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);
	}
	*objptr = NULL;
}

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