From 4e0892dc86a95323ae5fa9faf0a67341f0c5f946 Mon Sep 17 00:00:00 2001 From: Peter Evans Date: Tue, 6 Feb 2018 23:24:48 -0600 Subject: [PATCH] Add dependency injection container for vm --- include/vm_di.h | 21 +++++++++++++++++++++ sources.cmake | 1 + src/vm_di.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 include/vm_di.h create mode 100644 src/vm_di.c diff --git a/include/vm_di.h b/include/vm_di.h new file mode 100644 index 0000000..1bdc863 --- /dev/null +++ b/include/vm_di.h @@ -0,0 +1,21 @@ +#ifndef _VM_DI_H_ +#define _VM_DI_H_ + +enum vm_di_entry { + VM_CPU, + VM_MACHINE, + VM_REFLECT, + + // This value is the size of the DI container we will construct. As + // you can see, it's quite a bit higher than what would be implied + // by the number of enum values currently defined--and it is so we + // don't have to update this value every time we add a new value. + // But be wary that you don't add so many entries as to go beyond + // VM_DI_SIZE's defined value! + VM_DI_SIZE = 100, +}; + +extern void *vm_di_get(int); +extern int vm_di_set(int, void *); + +#endif diff --git a/sources.cmake b/sources.cmake index a31e120..da87f99 100644 --- a/sources.cmake +++ b/sources.cmake @@ -25,6 +25,7 @@ set(erc_sources option.c vm_area.c vm_bitfont.c + vm_di.c vm_event.c vm_reflect.c vm_screen.c diff --git a/src/vm_di.c b/src/vm_di.c new file mode 100644 index 0000000..3201935 --- /dev/null +++ b/src/vm_di.c @@ -0,0 +1,49 @@ +/* + * vm_di.c + * + * This code defines a very (very!) simplistic form of dependency + * injection container. It's up to you to set the entries of the + * container appropriately. + * + * This container is obviously _not type-safe_. It's just a bunch of + * void pointers. This container, however, _is_ immutable; once you set + * a value for a DI entry, it cannot be changed. + */ + +#include + +#include "log.h" +#include "vm_di.h" + +/* + * I learned something new today: this array will be constructed with + * zero-values for each entry because it is statically declared. See: + * http://en.cppreference.com/w/c/language/initialization + */ +static void *di_table[VM_DI_SIZE]; + +/* + * Set the di table entry `ent` to `val`. If there is a _previous_ + * value assigned to ent, then this returns ERR_INVALID, and no + * further assignment is allowed. + */ +int +vm_di_set(int ent, void *val) +{ + if (di_table[ent] != NULL) { + return ERR_INVALID; + } + + di_table[ent] = val; + return OK; +} + +/* + * Return the value assigned to the given ent, or NULL if no entry has + * been defined before. + */ +void * +vm_di_get(int ent) +{ + return di_table[ent]; +}