|
0
|
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 |
|
|
2
|
17 |
#include <sys/types.h>
|
|
|
18 |
#include <sys/stat.h>
|
|
|
19 |
#include <sys/mman.h>
|
|
|
20 |
#include <unistd.h>
|
|
0
|
21 |
#include "cdb++.h"
|
|
|
22 |
#include "internal.h"
|
|
|
23 |
|
|
|
24 |
#define FAIL do{ abort(); return 0; }while(0)
|
|
|
25 |
|
|
|
26 |
inline uint32 max(uint32 a, uint32 b)
|
|
|
27 |
{
|
|
|
28 |
return a > b ? a : b;
|
|
|
29 |
}
|
|
|
30 |
|
|
|
31 |
cdb_reader::cdb_reader(const mystring& filename)
|
|
2
|
32 |
: map(0),
|
|
|
33 |
failed(1),
|
|
0
|
34 |
eof(false)
|
|
|
35 |
{
|
|
2
|
36 |
int fd = open(filename.c_str(), O_RDONLY);
|
|
|
37 |
if(fd == -1) return;
|
|
|
38 |
struct stat buf;
|
|
|
39 |
if(fstat(fd, &buf) != -1)
|
|
|
40 |
map = (unsigned char*)mmap(0, buf.st_size, PROT_READ, MAP_SHARED, fd, 0);
|
|
|
41 |
close(fd);
|
|
|
42 |
failed = !map;
|
|
0
|
43 |
firstrec();
|
|
|
44 |
}
|
|
|
45 |
|
|
|
46 |
cdb_reader::~cdb_reader()
|
|
|
47 |
{
|
|
|
48 |
}
|
|
|
49 |
|
|
|
50 |
void cdb_reader::abort()
|
|
|
51 |
{
|
|
|
52 |
failed = true;
|
|
2
|
53 |
if(map)
|
|
|
54 |
munmap(map, size);
|
|
0
|
55 |
}
|
|
|
56 |
|
|
|
57 |
bool cdb_reader::firstrec()
|
|
|
58 |
{
|
|
|
59 |
if(failed) return false;
|
|
2
|
60 |
ptr = map + 2048;
|
|
|
61 |
eod = map + unpack(map);
|
|
0
|
62 |
return true;
|
|
|
63 |
}
|
|
|
64 |
|
|
|
65 |
datum* cdb_reader::nextrec()
|
|
|
66 |
{
|
|
|
67 |
if(eof) return 0;
|
|
2
|
68 |
if(ptr >= eod) {
|
|
0
|
69 |
eof = true;
|
|
|
70 |
return 0;
|
|
|
71 |
}
|
|
2
|
72 |
if(failed || eod-ptr < 8) FAIL;
|
|
|
73 |
uint32 klen = unpack(ptr); ptr += 4;
|
|
|
74 |
uint32 dlen = unpack(ptr); ptr += 4;
|
|
|
75 |
if ((uint32)(eod - ptr) < klen + dlen) FAIL;
|
|
|
76 |
datum* result = new datum(mystring((char*)ptr, klen),
|
|
|
77 |
mystring((char*)ptr+klen, dlen));
|
|
|
78 |
ptr += klen + dlen;
|
|
|
79 |
return result;
|
|
0
|
80 |
}
|