1 /*
2 * Copyright (C) 2016 Jakub Kruszona-Zawadzki, Core Technology Sp. z o.o.
3 *
4 * This file is part of MooseFS.
5 *
6 * MooseFS is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, version 2 (only).
9 *
10 * MooseFS is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with MooseFS; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA
18 * or visit http://www.gnu.org/licenses/gpl-2.0.html
19 */
20
21 #include <stdlib.h>
22 #include <inttypes.h>
23
24 typedef struct _shp {
25 void *pointer;
26 void (*freefn)(void*);
27 uint32_t refcnt;
28 } shp;
29
shp_new(void * pointer,void (* freefn)(void *))30 void* shp_new(void *pointer,void (*freefn)(void*)) {
31 shp *s;
32 s = malloc(sizeof(shp));
33 s->pointer = pointer;
34 s->freefn = freefn;
35 s->refcnt = 1;
36 return s;
37 }
38
shp_get(void * vs)39 void* shp_get(void *vs) {
40 shp *s = (shp*)vs;
41 return s->pointer;
42 }
43
shp_inc(void * vs)44 void shp_inc(void *vs) {
45 shp *s = (shp*)vs;
46 s->refcnt++;
47 }
48
shp_dec(void * vs)49 void shp_dec(void *vs) {
50 shp *s = (shp*)vs;
51 if (s->refcnt>0) {
52 s->refcnt--;
53 }
54 if (s->refcnt==0) {
55 s->freefn(s->pointer);
56 free(s);
57 }
58 }
59