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 _PUBLIC_
int64_t ntdb_traverse_(struct ntdb_context
*ntdb
,
22 int (*fn
)(struct ntdb_context
*,
23 NTDB_DATA
, NTDB_DATA
, void *),
26 enum NTDB_ERROR ecode
;
32 for (ecode
= first_in_hash(ntdb
, &h
, &k
, &d
.dsize
);
33 ecode
== NTDB_SUCCESS
;
34 ecode
= next_in_hash(ntdb
, &h
, &k
, &d
.dsize
)) {
35 d
.dptr
= k
.dptr
+ k
.dsize
;
38 if (fn
&& fn(ntdb
, k
, d
, p
)) {
39 ntdb
->free_fn(k
.dptr
, ntdb
->alloc_data
);
42 ntdb
->free_fn(k
.dptr
, ntdb
->alloc_data
);
45 if (ecode
!= NTDB_ERR_NOEXIST
) {
46 return NTDB_ERR_TO_OFF(ecode
);
51 _PUBLIC_
enum NTDB_ERROR
ntdb_firstkey(struct ntdb_context
*ntdb
, NTDB_DATA
*key
)
55 return first_in_hash(ntdb
, &h
, key
, NULL
);
58 /* We lock twice, not very efficient. We could keep last key & h cached. */
59 _PUBLIC_
enum NTDB_ERROR
ntdb_nextkey(struct ntdb_context
*ntdb
, NTDB_DATA
*key
)
62 struct ntdb_used_record rec
;
65 off
= find_and_lock(ntdb
, *key
, F_RDLCK
, &h
, &rec
, NULL
);
66 ntdb
->free_fn(key
->dptr
, ntdb
->alloc_data
);
67 if (NTDB_OFF_IS_ERR(off
)) {
68 return NTDB_OFF_TO_ERR(off
);
70 ntdb_unlock_hash(ntdb
, h
.h
, F_RDLCK
);
72 /* If we found something, skip to next. */
75 return next_in_hash(ntdb
, &h
, key
, NULL
);
78 static int wipe_one(struct ntdb_context
*ntdb
,
79 NTDB_DATA key
, NTDB_DATA data
, enum NTDB_ERROR
*ecode
)
81 *ecode
= ntdb_delete(ntdb
, key
);
82 return (*ecode
!= NTDB_SUCCESS
);
85 _PUBLIC_
enum NTDB_ERROR
ntdb_wipe_all(struct ntdb_context
*ntdb
)
87 enum NTDB_ERROR ecode
;
90 ecode
= ntdb_allrecord_lock(ntdb
, F_WRLCK
, NTDB_LOCK_WAIT
, false);
91 if (ecode
!= NTDB_SUCCESS
)
94 /* FIXME: Be smarter. */
95 count
= ntdb_traverse(ntdb
, wipe_one
, &ecode
);
97 ecode
= NTDB_OFF_TO_ERR(count
);
98 ntdb_allrecord_unlock(ntdb
, F_WRLCK
);