| 1 |
sysadm |
1.1 |
/* routines to search in in-progress cdb file
|
| 2 |
|
|
*
|
| 3 |
|
|
* This file is a part of tinycdb package by Michael Tokarev, mjt@corpit.ru.
|
| 4 |
|
|
* Public domain.
|
| 5 |
|
|
*/
|
| 6 |
|
|
|
| 7 |
|
|
#include "common/setup_before.h"
|
| 8 |
|
|
#include <stdio.h>
|
| 9 |
|
|
#include "cdb_int.h"
|
| 10 |
|
|
#include "common/setup_after.h"
|
| 11 |
|
|
|
| 12 |
|
|
static int
|
| 13 |
|
|
match(FILE *fd, unsigned pos, const char *key, unsigned klen)
|
| 14 |
|
|
{
|
| 15 |
|
|
unsigned char buf[64]; /*XXX cdb_buf may be used here instead */
|
| 16 |
|
|
if (fseek(fd, pos, SEEK_SET) || fread(buf, 1, 8, fd) != 8)
|
| 17 |
|
|
return -1;
|
| 18 |
|
|
if (cdb_unpack(buf) != klen)
|
| 19 |
|
|
return 0;
|
| 20 |
|
|
|
| 21 |
|
|
while(klen > sizeof(buf)) {
|
| 22 |
|
|
if (fread(buf, 1, sizeof(buf), fd) != sizeof(buf))
|
| 23 |
|
|
return -1;
|
| 24 |
|
|
if (memcmp(buf, key, sizeof(buf)) != 0)
|
| 25 |
|
|
return 0;
|
| 26 |
|
|
key += sizeof(buf);
|
| 27 |
|
|
klen -= sizeof(buf);
|
| 28 |
|
|
}
|
| 29 |
|
|
if (klen) {
|
| 30 |
|
|
if (fread(buf, 1, klen, fd) != klen)
|
| 31 |
|
|
return -1;
|
| 32 |
|
|
if (memcmp(buf, key, klen) != 0)
|
| 33 |
|
|
return 0;
|
| 34 |
|
|
}
|
| 35 |
|
|
return 1;
|
| 36 |
|
|
}
|
| 37 |
|
|
|
| 38 |
|
|
int
|
| 39 |
|
|
_cdb_make_find(struct cdb_make *cdbmp,
|
| 40 |
|
|
const void *key, unsigned klen, unsigned hval,
|
| 41 |
|
|
struct cdb_rl **rlp)
|
| 42 |
|
|
{
|
| 43 |
|
|
struct cdb_rl *rl = cdbmp->cdb_rec[hval&255];
|
| 44 |
|
|
int r, i;
|
| 45 |
|
|
int seeked = 0;
|
| 46 |
|
|
while(rl) {
|
| 47 |
|
|
for(i = rl->cnt - 1; i >= 0; --i) { /* search backward */
|
| 48 |
|
|
if (rl->rec[i].hval != hval)
|
| 49 |
|
|
continue;
|
| 50 |
|
|
/*XXX this explicit flush may be unnecessary having
|
| 51 |
|
|
* smarter match() that looks to cdb_buf too, but
|
| 52 |
|
|
* most of a time here spent in finding hash values
|
| 53 |
|
|
* (above), not keys */
|
| 54 |
|
|
if (cdbmp->cdb_bpos != cdbmp->cdb_buf) {
|
| 55 |
|
|
if (fwrite(cdbmp->cdb_buf, 1,
|
| 56 |
|
|
cdbmp->cdb_bpos - cdbmp->cdb_buf, cdbmp->cdb_fd) < 0)
|
| 57 |
|
|
return -1;
|
| 58 |
|
|
cdbmp->cdb_bpos = cdbmp->cdb_buf;
|
| 59 |
|
|
}
|
| 60 |
|
|
seeked = 1;
|
| 61 |
|
|
r = match(cdbmp->cdb_fd, rl->rec[i].rpos, key, klen);
|
| 62 |
|
|
if (!r)
|
| 63 |
|
|
continue;
|
| 64 |
|
|
if (r < 0)
|
| 65 |
|
|
return -1;
|
| 66 |
|
|
if (fseek(cdbmp->cdb_fd, cdbmp->cdb_dpos, SEEK_SET))
|
| 67 |
|
|
return -1;
|
| 68 |
|
|
if (rlp)
|
| 69 |
|
|
*rlp = rl;
|
| 70 |
|
|
return i + 1;
|
| 71 |
|
|
}
|
| 72 |
|
|
rl = rl->next;
|
| 73 |
|
|
}
|
| 74 |
|
|
if (seeked && fseek(cdbmp->cdb_fd, cdbmp->cdb_dpos, SEEK_SET))
|
| 75 |
|
|
return -1;
|
| 76 |
|
|
return 0;
|
| 77 |
|
|
}
|
| 78 |
|
|
|
| 79 |
|
|
int
|
| 80 |
|
|
cdb_make_exists(struct cdb_make *cdbmp,
|
| 81 |
|
|
const void *key, unsigned klen)
|
| 82 |
|
|
{
|
| 83 |
|
|
return _cdb_make_find(cdbmp, key, klen, cdb_hash(key, klen), NULL);
|
| 84 |
|
|
}
|