Happy new year
[pazpar2-moved-to-github.git] / src / normalize_cache.c
1 /* This file is part of Pazpar2.
2    Copyright (C) Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #include <string.h>
21
22 #include <yaz/yaz-util.h>
23 #include <yaz/mutex.h>
24 #include <yaz/nmem.h>
25
26 #if HAVE_CONFIG_H
27 #include <config.h>
28 #endif
29
30 #include "ppmutex.h"
31 #include "normalize_cache.h"
32
33 #include "pazpar2_config.h"
34
35 struct cached_item {
36     char *spec;
37     struct cached_item *next;
38     normalize_record_t nt;
39 };
40
41 struct normalize_cache_s {
42     struct cached_item *items;
43     NMEM nmem;
44     YAZ_MUTEX mutex;
45 };
46
47 normalize_cache_t normalize_cache_create(void)
48 {
49     NMEM nmem = nmem_create();
50     normalize_cache_t nc = nmem_malloc(nmem, sizeof(*nc));
51     nc->nmem = nmem;
52     nc->items = 0;
53     nc->mutex = 0;
54     pazpar2_mutex_create(&nc->mutex, "normalize_cache");
55     return nc;
56 }
57
58 normalize_record_t normalize_cache_get(normalize_cache_t nc,
59                                        struct conf_service *service,
60                                        const char *spec)
61 {
62     normalize_record_t nt;
63     struct cached_item *ci;
64
65     yaz_mutex_enter(nc->mutex);
66     for (ci = nc->items; ci; ci = ci->next)
67         if (!strcmp(spec, ci->spec))
68             break;
69     if (ci)
70         nt = ci->nt;
71     else
72     {
73         nt = normalize_record_create(service, spec);
74         if (nt)
75         {
76             ci = nmem_malloc(nc->nmem, sizeof(*ci));
77             ci->next = nc->items;
78             nc->items = ci;
79             ci->nt = nt;
80             ci->spec = nmem_strdup(nc->nmem, spec);
81         }
82     }
83     yaz_mutex_leave(nc->mutex);
84     return nt;
85 }
86
87 void normalize_cache_destroy(normalize_cache_t nc)
88 {
89     if (nc)
90     {
91         struct cached_item *ci = nc->items;
92         for (; ci; ci = ci->next)
93             normalize_record_destroy(ci->nt);
94         yaz_mutex_destroy(&nc->mutex);
95         nmem_destroy(nc->nmem);
96     }
97 }
98
99 /*
100  * Local variables:
101  * c-basic-offset: 4
102  * c-file-style: "Stroustrup"
103  * indent-tabs-mode: nil
104  * End:
105  * vim: shiftwidth=4 tabstop=8 expandtab
106  */
107