cff3ee0b52001222102959579381806d0d069263
[yaz-moved-to-github.git] / test / test_shared_ptr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2010 Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file test_shared_ptr.c
8  * \brief test shared pointer
9  */
10
11 #if HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18
19 #include <yaz/mutex.h>
20 #include <yaz/wrbuf.h>
21 #include <yaz/test.h>
22
23 #define YAZ_SHPTR_TYPE(type) \
24     struct type##_shptr \
25     {                          \
26     type ptr;                  \
27     int ref;                   \
28     YAZ_MUTEX mutex;           \
29     };  \
30     typedef struct type##_shptr *type##_shptr_t;
31
32 #define YAZ_SHPTR_INIT(p,n) {                   \
33         p = xmalloc(sizeof(*p));                \
34         p->ptr = n;                             \
35         p->ref = 1;                             \
36         p->mutex = 0;  \
37         yaz_mutex_create(&p->mutex);            \
38     }
39
40 #define YAZ_SHPTR_INC(p) {                      \
41         yaz_mutex_enter(p->mutex);              \
42         p->ref++;                               \
43         yaz_mutex_leave(p->mutex);              \
44     }
45
46 #define YAZ_SHPTR_DEC(p, destroy)  {             \
47     yaz_mutex_enter(p->mutex);                   \
48     if (--p->ref == 0) {                         \
49         yaz_mutex_leave(p->mutex);               \
50         destroy(p->ptr);                         \
51         yaz_mutex_destroy(&p->mutex);            \
52         xfree(p);                                \
53         p = 0;                                   \
54     } else { \
55     yaz_mutex_leave(p->mutex); \
56     } \
57     }
58
59 YAZ_SHPTR_TYPE(WRBUF)
60
61 static void test(void)
62 {
63     WRBUF w = wrbuf_alloc();
64
65     WRBUF_shptr_t t = 0;
66     
67     YAZ_SHPTR_INIT(t, w);
68     YAZ_CHECK(t);
69
70     YAZ_SHPTR_INC(t);
71     YAZ_CHECK(t);
72
73     YAZ_SHPTR_DEC(t, wrbuf_destroy);
74     YAZ_CHECK(t);
75
76     YAZ_SHPTR_DEC(t, wrbuf_destroy);
77     YAZ_CHECK(!t);
78 }
79
80 int main (int argc, char **argv)
81 {
82     YAZ_CHECK_INIT(argc, argv);
83     test();
84     YAZ_CHECK_TERM;
85 }
86
87
88 /*
89  * Local variables:
90  * c-basic-offset: 4
91  * c-file-style: "Stroustrup"
92  * indent-tabs-mode: nil
93  * End:
94  * vim: shiftwidth=4 tabstop=8 expandtab
95  */
96