]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/traverse.c
tdb2: rework io functions to return enum TDB_ERROR.
[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, tdb_traverse_func fn, void *p)
22 {
23         int ret;
24         struct traverse_info tinfo;
25         struct tdb_data k, d;
26         int64_t count = 0;
27
28         k.dptr = NULL;
29         for (ret = first_in_hash(tdb, &tinfo, &k, &d.dsize);
30              ret == 1;
31              ret = next_in_hash(tdb, &tinfo, &k, &d.dsize)) {
32                 d.dptr = k.dptr + k.dsize;
33                 
34                 count++;
35                 if (fn && fn(tdb, k, d, p)) {
36                         free(k.dptr);
37                         break;
38                 }
39                 free(k.dptr);
40         }
41
42         if (ret < 0)
43                 return -1;
44         return count;
45 }
46         
47 TDB_DATA tdb_firstkey(struct tdb_context *tdb)
48 {
49         struct traverse_info tinfo;
50         struct tdb_data k;
51         switch (first_in_hash(tdb, &tinfo, &k, NULL)) {
52         case 1:
53                 return k;
54         case 0:
55                 tdb->ecode = TDB_SUCCESS;
56                 /* Fall thru... */
57         default:
58                 return tdb_null;
59         }
60 }
61
62 /* We lock twice, not very efficient.  We could keep last key & tinfo cached. */
63 TDB_DATA tdb_nextkey(struct tdb_context *tdb, TDB_DATA key)
64 {
65         struct traverse_info tinfo;
66         struct hash_info h;
67         struct tdb_used_record rec;
68
69         tinfo.prev = find_and_lock(tdb, key, F_RDLCK, &h, &rec, &tinfo);
70         if (unlikely(tinfo.prev == TDB_OFF_ERR))
71                 return tdb_null;
72         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
73
74         switch (next_in_hash(tdb, &tinfo, &key, NULL)) {
75         case 1:
76                 return key;
77         case 0:
78                 tdb->ecode = TDB_SUCCESS;
79                 /* Fall thru... */
80         default:
81                 return tdb_null;
82         }
83 }