ntdb: allocator attribute.
[Samba.git] / lib / ntdb / traverse.c
blobee1e1006db910ff2795090755088e01cebe36368
1 /*
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/>.
18 #include "private.h"
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 *),
24 void *p)
26 enum NTDB_ERROR ecode;
27 struct traverse_info tinfo;
28 NTDB_DATA k, d;
29 int64_t count = 0;
31 k.dptr = NULL;
32 for (ecode = first_in_hash(ntdb, &tinfo, &k, &d.dsize);
33 ecode == NTDB_SUCCESS;
34 ecode = next_in_hash(ntdb, &tinfo, &k, &d.dsize)) {
35 d.dptr = k.dptr + k.dsize;
37 count++;
38 if (fn && fn(ntdb, k, d, p)) {
39 ntdb->free_fn(k.dptr, ntdb->alloc_data);
40 return count;
42 ntdb->free_fn(k.dptr, ntdb->alloc_data);
45 if (ecode != NTDB_ERR_NOEXIST) {
46 return NTDB_ERR_TO_OFF(ecode);
48 return count;
51 _PUBLIC_ enum NTDB_ERROR ntdb_firstkey(struct ntdb_context *ntdb, NTDB_DATA *key)
53 struct traverse_info tinfo;
55 return first_in_hash(ntdb, &tinfo, key, NULL);
58 /* We lock twice, not very efficient. We could keep last key & tinfo cached. */
59 _PUBLIC_ enum NTDB_ERROR ntdb_nextkey(struct ntdb_context *ntdb, NTDB_DATA *key)
61 struct traverse_info tinfo;
62 struct hash_info h;
63 struct ntdb_used_record rec;
65 tinfo.prev = find_and_lock(ntdb, *key, F_RDLCK, &h, &rec, &tinfo);
66 ntdb->free_fn(key->dptr, ntdb->alloc_data);
67 if (NTDB_OFF_IS_ERR(tinfo.prev)) {
68 return NTDB_OFF_TO_ERR(tinfo.prev);
70 ntdb_unlock_hashes(ntdb, h.hlock_start, h.hlock_range, F_RDLCK);
72 return next_in_hash(ntdb, &tinfo, key, NULL);
75 static int wipe_one(struct ntdb_context *ntdb,
76 NTDB_DATA key, NTDB_DATA data, enum NTDB_ERROR *ecode)
78 *ecode = ntdb_delete(ntdb, key);
79 return (*ecode != NTDB_SUCCESS);
82 _PUBLIC_ enum NTDB_ERROR ntdb_wipe_all(struct ntdb_context *ntdb)
84 enum NTDB_ERROR ecode;
85 int64_t count;
87 ecode = ntdb_allrecord_lock(ntdb, F_WRLCK, NTDB_LOCK_WAIT, false);
88 if (ecode != NTDB_SUCCESS)
89 return ecode;
91 /* FIXME: Be smarter. */
92 count = ntdb_traverse(ntdb, wipe_one, &ecode);
93 if (count < 0)
94 ecode = NTDB_OFF_TO_ERR(count);
95 ntdb_allrecord_unlock(ntdb, F_WRLCK);
96 return ecode;