refcount.c revision c391633a8cc03f0fc3be0b7c424b28acf94bc878
1N/A/*
1N/A SSSD
1N/A
1N/A Simple reference counting wrappers for talloc.
1N/A
1N/A Authors:
1N/A Martin Nagy <mnagy@redhat.com>
1N/A
1N/A Copyright (C) Red Hat, Inc 2009
1N/A
1N/A This program is free software; you can redistribute it and/or modify
1N/A it under the terms of the GNU General Public License as published by
1N/A the Free Software Foundation; either version 3 of the License, or
1N/A (at your option) any later version.
1N/A
1N/A This program is distributed in the hope that it will be useful,
1N/A but WITHOUT ANY WARRANTY; without even the implied warranty of
1N/A MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1N/A GNU General Public License for more details.
1N/A
1N/A You should have received a copy of the GNU General Public License
1N/A along with this program. If not, see <http://www.gnu.org/licenses/>.
1N/A*/
1N/A
1N/A#include <talloc.h>
1N/A
1N/A#include "refcount.h"
1N/A#include "util/util.h"
1N/A
1N/Astruct wrapper {
1N/A int *refcount;
1N/A void *ptr;
1N/A};
1N/A
1N/Astatic int
1N/Arefcount_destructor(struct wrapper *wrapper)
1N/A{
1N/A (*wrapper->refcount)--;
1N/A if (*wrapper->refcount == 0) {
1N/A talloc_free(wrapper->ptr);
1N/A };
1N/A
1N/A return 0;
1N/A}
1N/A
1N/Avoid *
1N/A_rc_alloc(const void *context, size_t size, size_t refcount_offset,
1N/A const char *type_name)
1N/A{
1N/A struct wrapper *wrapper;
1N/A
1N/A wrapper = talloc(context, struct wrapper);
1N/A if (wrapper == NULL) {
1N/A return NULL;
1N/A }
1N/A
1N/A wrapper->ptr = talloc_named_const(NULL, size, type_name);
1N/A if (wrapper->ptr == NULL) {
1N/A talloc_free(wrapper);
1N/A return NULL;
1N/A };
1N/A
1N/A wrapper->refcount = (int *)((char *)wrapper->ptr + refcount_offset);
1N/A *wrapper->refcount = 1;
1N/A
1N/A talloc_set_destructor(wrapper, refcount_destructor);
1N/A
1N/A return wrapper->ptr;
1N/A}
1N/A
1N/Avoid *
1N/A_rc_reference(const void *context, size_t refcount_offset, void *source)
1N/A{
1N/A struct wrapper *wrapper;
1N/A
1N/A wrapper = talloc(context, struct wrapper);
1N/A if (wrapper == NULL) {
1N/A return NULL;
1N/A }
1N/A
1N/A wrapper->ptr = source;
1N/A wrapper->refcount = (int *)((char *)wrapper->ptr + refcount_offset);
1N/A (*wrapper->refcount)++;
1N/A
1N/A talloc_set_destructor(wrapper, refcount_destructor);
1N/A
1N/A return wrapper->ptr;
1N/A}
1N/A