summaryrefslogtreecommitdiffstats
path: root/src/resources/resource.c
blob: 8b1cca31e2efb9c8af0e4a3aa73a1372acb5d1d0 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 * Copyright (C) 2013  Patrick "P. J." McDermott
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <string.h>
#include "resource.h"

#include "../logging.h"

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;
}