summaryrefslogtreecommitdiffstats
path: root/src/resources/resource.c
blob: ebfcf27bdf99a89e2cb55771759b8d3f1d44513c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
}