|
1 // Copyright (C) 1999,2000 Bruce Guenter <bruceg@em.ca> |
|
2 // |
|
3 // This program is free software; you can redistribute it and/or modify |
|
4 // it under the terms of the GNU General Public License as published by |
|
5 // the Free Software Foundation; either version 2 of the License, or |
|
6 // (at your option) any later version. |
|
7 // |
|
8 // This program is distributed in the hope that it will be useful, |
|
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 // GNU General Public License for more details. |
|
12 // |
|
13 // You should have received a copy of the GNU General Public License |
|
14 // along with this program; if not, write to the Free Software |
|
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
|
16 |
|
17 #include "cdb++.h" |
|
18 #include "internal.h" |
|
19 |
|
20 static int match(fdibuf& in, const mystring& key) |
|
21 { |
|
22 unsigned len = key.length(); |
|
23 const char* keyptr = key.c_str(); |
|
24 |
|
25 while (len > 0) { |
|
26 char buf[32]; |
|
27 unsigned n = sizeof buf; |
|
28 if(n > len) n = len; |
|
29 if(!in.read(buf, n)) return -1; |
|
30 for(unsigned i = 0;i < n;++i) |
|
31 if(buf[i] != keyptr[i]) return 0; |
|
32 keyptr += n; |
|
33 len -= n; |
|
34 } |
|
35 return 1; |
|
36 } |
|
37 |
|
38 int cdb_reader::seek(const mystring& key, uint32& dlen) |
|
39 { |
|
40 if(failed) |
|
41 return -1; |
|
42 uint32 h = hash(key); |
|
43 uint32 pos = 8 * (h & 255); |
|
44 |
|
45 uint32 poshash = unpack(header+pos); |
|
46 uint32 lenhash = unpack(header+pos+4); |
|
47 |
|
48 if(!lenhash) return 0; |
|
49 uint32 h2 = (h >> 8) % lenhash; |
|
50 |
|
51 for (uint32 loop = 0; loop < lenhash; ++loop) { |
|
52 if(!in.seek(poshash+8*h2)) return -1; |
|
53 unsigned char packbuf[8]; |
|
54 if(!in.read(packbuf, 8)) return -1; |
|
55 uint32 poskd = unpack(packbuf + 4); |
|
56 if(!poskd) return 0; |
|
57 if(unpack(packbuf) == h) { |
|
58 if(!in.seek(poskd)) return -1; |
|
59 if(!in.read(packbuf, 8)) return -1; |
|
60 if(unpack(packbuf) == key.length()) |
|
61 switch(match(in, key)) { |
|
62 case -1: |
|
63 return -1; |
|
64 case 1: |
|
65 dlen = unpack(packbuf + 4); |
|
66 return 1; |
|
67 } |
|
68 } |
|
69 if(++h2 == lenhash) h2 = 0; |
|
70 } |
|
71 return 0; |
|
72 } |
|
73 |
|
74 datum* cdb_reader::get(const mystring& key) |
|
75 { |
|
76 if(failed) |
|
77 return 0; |
|
78 uint32 len; |
|
79 switch(seek(key, len)) { |
|
80 case -1: return 0; |
|
81 case 0: return 0; |
|
82 } |
|
83 // Big assume: data is relatively small (will fit on stack) |
|
84 char buf[len]; |
|
85 datum* d = !in.read(buf, len) ? 0 : new datum(key, mystring(buf, len)); |
|
86 return d; |
|
87 } |