]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/traverse.c
tdb2: feature support.
[ccan] / ccan / tdb2 / traverse.c
1  /*
2    Trivial Database 2: traverse function.
3    Copyright (C) Rusty Russell 2010
4
5    This library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 3 of the License, or (at your option) any later version.
9
10    This library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 */
18 #include "private.h"
19 #include <ccan/likely/likely.h>
20
21 int64_t tdb_traverse_(struct tdb_context *tdb,
22                       int (*fn)(struct tdb_context *,
23                                 TDB_DATA, TDB_DATA, void *),
24                       void *p)
25 {
26         enum TDB_ERROR ecode;
27         struct traverse_info tinfo;
28         struct tdb_data k, d;
29         int64_t count = 0;
30
31         k.dptr = NULL;
32         for (ecode = first_in_hash(tdb, &tinfo, &k, &d.dsize);
33              ecode == TDB_SUCCESS;
34              ecode = next_in_hash(tdb, &tinfo, &k, &d.dsize)) {
35                 d.dptr = k.dptr + k.dsize;
36                 
37                 count++;
38                 if (fn && fn(tdb, k, d, p)) {
39                         free(k.dptr);
40                         return count;
41                 }
42                 free(k.dptr);
43         }
44
45         if (ecode != TDB_ERR_NOEXIST) {
46                 return ecode;
47         }
48         return count;
49 }
50         
51 enum TDB_ERROR tdb_firstkey(struct tdb_context *tdb, struct tdb_data *key)
52 {
53         struct traverse_info tinfo;
54
55         return first_in_hash(tdb, &tinfo, key, NULL);
56 }
57
58 /* We lock twice, not very efficient.  We could keep last key & tinfo cached. */
59 enum TDB_ERROR tdb_nextkey(struct tdb_context *tdb, struct tdb_data *key)
60 {
61         struct traverse_info tinfo;
62         struct hash_info h;
63         struct tdb_used_record rec;
64
65         tinfo.prev = find_and_lock(tdb, *key, F_RDLCK, &h, &rec, &tinfo);
66         free(key->dptr);
67         if (TDB_OFF_IS_ERR(tinfo.prev)) {
68                 return tinfo.prev;
69         }
70         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
71
72         return next_in_hash(tdb, &tinfo, key, NULL);
73 }