2 Trivial Database 2: traverse function.
3 Copyright (C) Rusty Russell 2010
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.
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.
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/>.
19 #include <ccan/likely/likely.h>
21 static int64_t traverse(struct tdb_context *tdb, int ltype,
22 tdb_traverse_func fn, void *p)
25 struct traverse_info tinfo;
29 for (ret = first_in_hash(tdb, ltype, &tinfo, &k, &d.dsize);
31 ret = next_in_hash(tdb, ltype, &tinfo, &k, &d.dsize)) {
32 d.dptr = k.dptr + k.dsize;
35 if (fn && fn(tdb, k, d, p))
44 int64_t tdb_traverse(struct tdb_context *tdb, tdb_traverse_func fn, void *p)
46 return traverse(tdb, F_WRLCK, fn, p);
49 int64_t tdb_traverse_read(struct tdb_context *tdb,
50 tdb_traverse_func fn, void *p)
53 bool was_ro = tdb->read_only;
54 tdb->read_only = true;
55 ret = traverse(tdb, F_RDLCK, fn, p);
56 tdb->read_only = was_ro;
60 TDB_DATA tdb_firstkey(struct tdb_context *tdb)
62 struct traverse_info tinfo;
64 switch (first_in_hash(tdb, F_RDLCK, &tinfo, &k, NULL)) {
68 tdb->ecode = TDB_SUCCESS;
75 /* We lock twice, not very efficient. We could keep last key & tinfo cached. */
76 TDB_DATA tdb_nextkey(struct tdb_context *tdb, TDB_DATA key)
78 struct traverse_info tinfo;
80 struct tdb_used_record rec;
82 tinfo.prev = find_and_lock(tdb, key, F_RDLCK, &h, &rec, &tinfo);
83 if (unlikely(tinfo.prev == TDB_OFF_ERR))
85 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
87 switch (next_in_hash(tdb, F_RDLCK, &tinfo, &key, NULL)) {
91 tdb->ecode = TDB_SUCCESS;