view slab.c @ 794:d018af7c979c

slab: make struct mem_cache private Signed-off-by: Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
author Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
date Sun, 15 Mar 2020 15:52:09 +0200
parents 6077388dbf4c
children
line wrap: on
line source

/*
 * Copyright (c) 2015-2020 Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <errno.h>
#include <string.h>

#include <jeffpc/error.h>
#include <jeffpc/mem.h>

/*
 * A slab allocator - well, not really... just use malloc and free directly.
 */

struct mem_cache {
	size_t size;
	size_t align;
};

#pragma weak mem_cache_create
struct mem_cache *mem_cache_create(char *name, size_t size, size_t align)
{
	struct mem_cache *cache;

	if (!size)
		return ERR_PTR(-EINVAL);

	/* FIXME: check that the value is 0, or a power of 2 */

	cache = malloc(sizeof(struct mem_cache));
	if (!cache)
		return ERR_PTR(-ENOMEM);

	cache->size = size;
	cache->align = (align < sizeof(void *)) ? sizeof(void *) : align;

	return cache;
}

#pragma weak mem_cache_destroy
void mem_cache_destroy(struct mem_cache *cache)
{
	if (!cache)
		return;

	free(cache);
}

#pragma weak mem_cache_alloc
void *mem_cache_alloc(struct mem_cache *cache)
{
	void *obj;
	int ret;

	ret = posix_memalign(&obj, cache->align, cache->size);

	return ret ? NULL : obj;
}

#pragma weak mem_cache_free
void mem_cache_free(struct mem_cache *cache, void *buf)
{
	free(buf);
}