]> git.ipfire.org Git - thirdparty/pdns.git/blame - ext/lmdb-safe/lmdb-typed.cc
auth lmdb random-ids: stop generating negative numbers
[thirdparty/pdns.git] / ext / lmdb-safe / lmdb-typed.cc
CommitLineData
6a40fc00 1#include "lmdb-typed.hh"
fba1ae46 2#include "pdns/dns_random.hh"
6a40fc00 3
4unsigned int MDBGetMaxID(MDBRWTransaction& txn, MDBDbi& dbi)
5{
9c1e5491 6 auto cursor = txn->getRWCursor(dbi);
6a40fc00 7 MDBOutVal maxidval, maxcontent;
8 unsigned int maxid{0};
9 if(!cursor.get(maxidval, maxcontent, MDB_LAST)) {
10 maxid = maxidval.get<unsigned int>();
11 }
12 return maxid;
13}
14
fba1ae46
PD
15unsigned int MDBGetRandomID(MDBRWTransaction& txn, MDBDbi& dbi)
16{
17 auto cursor = txn->getRWCursor(dbi);
18 unsigned int id;
19 for(int attempts=0; attempts<20; attempts++) {
20 MDBOutVal key, content;
21
c1e15cd2 22 // dns_random generates a random number in [0..signed_int_max-1]. We add 1 to avoid 0 and allow type_max.
fba1ae46 23 // 0 is avoided because the put() interface uses it to mean "please allocate a number for me"
c1e15cd2 24 id = dns_random(std::numeric_limits<signed int>::max()) + 1;
fba1ae46
PD
25 if(cursor.find(MDBInVal(id), key, content)) {
26 return id;
27 }
28 }
29 throw std::runtime_error("MDBGetRandomID() could not assign an unused random ID");
30}
31
6a40fc00 32