summaryrefslogtreecommitdiffstats
path: root/src/resources/resource.c
diff options
context:
space:
mode:
authorP. J. McDermott <pjm@nac.net>2013-02-15 15:28:42 (EST)
committer P. J. McDermott <pjm@nac.net>2013-02-15 15:28:42 (EST)
commitc978f746058497ddd9ddc9cf3e156c4453e487f1 (patch)
treeb7855dd65c735c54ad535f31d4fbd645ca29fc1b /src/resources/resource.c
parent80191b41352ad20493fb62e8f3683d69133d0d24 (diff)
downloadoverworld-rpg-c978f746058497ddd9ddc9cf3e156c4453e487f1.zip
overworld-rpg-c978f746058497ddd9ddc9cf3e156c4453e487f1.tar.gz
overworld-rpg-c978f746058497ddd9ddc9cf3e156c4453e487f1.tar.bz2
Add resource manager and move src/image.*.
Diffstat (limited to 'src/resources/resource.c')
-rw-r--r--src/resources/resource.c87
1 files changed, 87 insertions, 0 deletions
diff --git a/src/resources/resource.c b/src/resources/resource.c
new file mode 100644
index 0000000..ebfcf27
--- /dev/null
+++ b/src/resources/resource.c
@@ -0,0 +1,87 @@
+#include <stdlib.h>
+#include <string.h>
+#include "resource.h"
+
+#include "../logging.h"
+
+inline void *
+resource_alloc(const char *path, size_t size)
+{
+ void *new_res;
+
+ debug("Allocating resource \"%s\"...", path);
+ new_res = malloc(size);
+ if (new_res == NULL) {
+ err(1, "Failed to allocate resource \"%s\"", path);
+ return NULL;
+ }
+ memset(new_res, 0, size);
+
+ return new_res;
+}
+
+struct resource *
+resource_get(struct resource_table *resources, const char *path)
+{
+ struct resource *res;
+
+ for (res = resources->head; res != NULL; res = res->next) {
+ if (strcmp(res->path, path) == 0) {
+ debug("Found resource \"%s\"", path);
+ return res;
+ }
+ }
+
+ return NULL;
+}
+
+void
+resource_add(struct resource_table *resources, const char *path,
+ struct resource *new_res)
+{
+ new_res->path = strdup(path);
+ new_res->prev = resources->tail;
+ new_res->next = NULL;
+
+ if (resources->head == NULL) {
+ resources->head = new_res;
+ } else {
+ resources->tail->next = new_res;
+ }
+ resources->tail = new_res;
+}
+
+/* XXX: Not thread-safe. */
+void
+resource_use(struct resource *resource)
+{
+ ++resource->refs;
+}
+
+int
+resource_free(struct resource_table *resources, struct resource *resource)
+{
+ if (resource == NULL) {
+ return -1;
+ }
+
+ debug("Releasing resource with path \"%s\" and %d refs...",
+ resource->path, resource->refs);
+
+ if (--resource->refs == 0) {
+ debug("Freeing resource with path \"%s\"...", resource->path);
+ if (resource->prev == NULL) {
+ resources->head = resource->next;
+ } else {
+ resource->prev->next = resource->next;
+ }
+ if (resource->next == NULL) {
+ resources->tail = resource->prev;
+ } else {
+ resource->next->prev = resource->prev;
+ }
+ free(resource);
+ return 1;
+ }
+ return 0;
+}