04fabe65dbb7070e98796d6371e1b43294234bd0
[idzebra-moved-to-github.git] / dict / dopen.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1994-2010 Index Data
3
4 Zebra 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 Zebra 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
21
22 #include <sys/types.h>
23 #include <fcntl.h>
24 #if HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <stdio.h>
28 #include <stdlib.h>
29
30 #include "dict-p.h"
31
32 static void common_init(Dict_BFile bf, int block_size, int cache)
33 {
34     int i;
35
36     bf->block_size = block_size;
37     bf->compact_flag = 0;
38     bf->cache = cache;
39     bf->hash_size = 31;
40
41     bf->hits = bf->misses = 0;
42
43     /* Allocate all blocks in one chunk. */
44     bf->all_data = xmalloc(block_size * cache);
45
46     /* Allocate and initialize hash array (as empty) */
47     bf->hash_array = (struct Dict_file_block **)
48         xmalloc(sizeof(*bf->hash_array) * bf->hash_size);
49     for (i=bf->hash_size; --i >= 0; )
50         bf->hash_array[i] = NULL;
51
52     /* Allocate all block descriptors in one chunk */
53     bf->all_blocks = (struct Dict_file_block *)
54         xmalloc(sizeof(*bf->all_blocks) * cache);
55
56     /* Initialize the free list */
57     bf->free_list = bf->all_blocks;
58     for (i=0; i<cache-1; i++)
59         bf->all_blocks[i].h_next = bf->all_blocks+(i+1);
60     bf->all_blocks[i].h_next = NULL;
61
62     /* Initialize the data for each block. Will never be moved again */
63     for (i=0; i<cache; i++)
64         bf->all_blocks[i].data = (char*) bf->all_data + i*block_size;
65
66     /* Initialize lru queue */
67     bf->lru_back = NULL;
68     bf->lru_front = NULL;
69 }
70
71
72 Dict_BFile dict_bf_open(BFiles bfs, const char *name, int block_size,
73                         int cache, int rw)
74 {
75     Dict_BFile dbf;
76     
77     dbf = (Dict_BFile) xmalloc(sizeof(*dbf));
78     dbf->bf = bf_open(bfs, name, block_size, rw);
79     if (!dbf->bf)
80     {
81         xfree(dbf);
82         return 0;
83     }
84     common_init(dbf, block_size, cache);
85     return dbf;
86 }
87
88 void dict_bf_compact(Dict_BFile dbf)
89 {
90     dbf->compact_flag = 1;
91 }
92 /*
93  * Local variables:
94  * c-basic-offset: 4
95  * c-file-style: "Stroustrup"
96  * indent-tabs-mode: nil
97  * End:
98  * vim: shiftwidth=4 tabstop=8 expandtab
99  */
100