crap-libs/oop/oop.c

67 lines
1.4 KiB
C
Raw Normal View History

2017-03-07 22:52:11 +00:00
#include "oop.h"
#include <string.h>
2017-03-09 15:24:02 +00:00
#include <stdlib.h>
2017-03-07 22:52:11 +00:00
class_id_t class_ids = 0;
meta_class_t classes[MAX_CLASSES];
2017-03-09 15:24:02 +00:00
class_id_t oop_add_class(const char* name, class_t super, bool instanceable) {
2017-03-07 22:52:11 +00:00
classes[class_ids] = (meta_class_t) {
.name = name,
2017-03-09 15:24:02 +00:00
.super = super.id,
2017-03-07 22:52:11 +00:00
.instanceable = instanceable
};
return class_ids++;
}
2017-03-09 15:24:02 +00:00
bool oop_instance_of_id(void* object, class_id_t id) {
2017-03-07 22:52:11 +00:00
if (sizeof (object) < sizeof (object_t))
return false; // not an object
object_t* obj = (object_t*) object;
2017-03-09 15:24:02 +00:00
return obj->meta_obj.type.id == id;
2017-03-07 22:52:11 +00:00
}
2017-03-09 15:24:02 +00:00
bool oop_instance_of(void* object, class_t type) {
return oop_instance_of_id(object, type.id);
2017-03-07 22:52:11 +00:00
}
2017-03-09 15:24:02 +00:00
const char* oop_get_class_name_by_id(class_id_t id) {
2017-03-07 22:52:11 +00:00
return classes[id].name;
}
2017-03-09 15:24:02 +00:00
const char* oop_get_class_name(class_t type) {
return oop_get_class_name_by_id(type.id);
2017-03-07 22:52:11 +00:00
}
2017-03-09 15:24:02 +00:00
class_id_t oop_id_from_name(const char* class_name) {
2017-03-07 22:52:11 +00:00
for (int i = 0; i < class_ids; i++) {
if (strcmp(class_name, classes[i].name) == 0)
return i;
}
2017-03-09 15:24:02 +00:00
return NO_CLASS_ID;
2017-03-07 22:52:11 +00:00
}
2017-03-09 15:24:02 +00:00
bool oop_class_exists(const char* class_name) {
return oop_id_from_name(class_name) != NO_CLASS_ID;
}
class_t object_class;
void method(object, destruct)(object_t* obj) {
free(obj);
}
object_t* method(object, construct)() {
object_t* obj = malloc(sizeof(object_t));
populate(object)(obj, object_class);
return obj;
}
void method(object, populate)(object_t* obj, class_t type) {
obj->meta_obj.type = type;
add_method(obj, object, destruct);
2017-03-07 22:52:11 +00:00
}