/*
* 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
* .
*/
#include
#include
#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;
}