asb / lua-tinycdb

A lua binding to the tinycdb library by Michael Tokarev

lua-tinycdb / cdb_find.c
b058edee » asb 2008-07-19 Check in v0.1 sources 1 /* $Id: cdb_find.c,v 1.8 2003/11/03 16:42:41 mjt Exp $
2 * cdb_find routine
3 *
4 * This file is a part of tinycdb package by Michael Tokarev, mjt@corpit.ru.
5 * Public domain.
6 */
7
8 #include "cdb_int.h"
9
10 int
11 cdb_find(struct cdb *cdbp, const void *key, unsigned klen)
12 {
13 const unsigned char *htp; /* hash table pointer */
14 const unsigned char *htab; /* hash table */
15 const unsigned char *htend; /* end of hash table */
16 unsigned httodo; /* ht bytes left to look */
17 unsigned pos, n;
18
19 unsigned hval;
20
21 if (klen >= cdbp->cdb_dend) /* if key size is too large */
22 return 0;
23
24 hval = cdb_hash(key, klen);
25
26 /* find (pos,n) hash table to use */
27 /* first 2048 bytes (toc) are always available */
28 /* (hval % 256) * 8 */
29 htp = cdbp->cdb_mem + ((hval << 3) & 2047); /* index in toc (256x8) */
30 n = cdb_unpack(htp + 4); /* table size */
31 if (!n) /* empty table */
32 return 0; /* not found */
33 httodo = n << 3; /* bytes of htab to lookup */
34 pos = cdb_unpack(htp); /* htab position */
35 if (n > (cdbp->cdb_fsize >> 3) /* overflow of httodo ? */
36 || pos < cdbp->cdb_dend /* is htab inside data section ? */
37 || pos > cdbp->cdb_fsize /* htab start within file ? */
38 || httodo > cdbp->cdb_fsize - pos) /* entrie htab within file ? */
39 return errno = EPROTO, -1;
40
41 htab = cdbp->cdb_mem + pos; /* htab pointer */
42 htend = htab + httodo; /* after end of htab */
43 /* htab starting position: rest of hval modulo htsize, 8bytes per elt */
44 htp = htab + (((hval >> 8) % n) << 3);
45
46 for(;;) {
47 pos = cdb_unpack(htp + 4); /* record position */
48 if (!pos)
49 return 0;
50 if (cdb_unpack(htp) == hval) {
51 if (pos > cdbp->cdb_dend - 8) /* key+val lengths */
52 return errno = EPROTO, -1;
53 if (cdb_unpack(cdbp->cdb_mem + pos) == klen) {
54 if (cdbp->cdb_dend - klen < pos + 8)
55 return errno = EPROTO, -1;
56 if (memcmp(key, cdbp->cdb_mem + pos + 8, klen) == 0) {
57 n = cdb_unpack(cdbp->cdb_mem + pos + 4);
58 pos += 8;
59 if (cdbp->cdb_dend < n || cdbp->cdb_dend - n < pos + klen)
60 return errno = EPROTO, -1;
61 cdbp->cdb_kpos = pos;
62 cdbp->cdb_klen = klen;
63 cdbp->cdb_vpos = pos + klen;
64 cdbp->cdb_vlen = n;
65 return 1;
66 }
67 }
68 }
69 httodo -= 8;
70 if (!httodo)
71 return 0;
72 if ((htp += 8) >= htend)
73 htp = htab;
74 }
75
76 }