From eaca435a5bd65e40bc0415a7b227bef4fda56fa7 Mon Sep 17 00:00:00 2001 From: orignal Date: Sat, 18 Feb 2023 19:45:31 -0500 Subject: [PATCH] find multiple closest hashes --- libi2pd/KadDHT.cpp | 33 +++++++++++++++++++++++++++++++++ libi2pd/KadDHT.h | 3 +++ 2 files changed, 36 insertions(+) diff --git a/libi2pd/KadDHT.cpp b/libi2pd/KadDHT.cpp index 29664f79..c3905b7a 100644 --- a/libi2pd/KadDHT.cpp +++ b/libi2pd/KadDHT.cpp @@ -205,6 +205,39 @@ namespace data } return nullptr; } + + std::vector DHTTable::FindClosest (const IdentHash& h, size_t num) + { + std::vector vec; + if (num > 0) + FindClosest (h, num, m_Root, 0, vec); + return vec; + } + + void DHTTable::FindClosest (const IdentHash& h, size_t num, DHTNode * root, int level, std::vector& hashes) + { + if (hashes.size () >= num) return; + if (root->hash) + { + hashes.push_back (root->hash); + return; + } + int bit = h.GetBit (level); + if (bit) + { + if (root->one) + FindClosest (h, num, root->one, level + 1, hashes); + if (hashes.size () < num && root->zero) + FindClosest (h, num, root->zero, level + 1, hashes); + } + else + { + if (root->zero) + FindClosest (h, num, root->zero, level + 1, hashes); + if (hashes.size () < num && root->one) + FindClosest (h, num, root->one, level + 1, hashes); + } + } void DHTTable::Print (std::stringstream& s) { diff --git a/libi2pd/KadDHT.h b/libi2pd/KadDHT.h index 4a1b61b6..eb12aae7 100644 --- a/libi2pd/KadDHT.h +++ b/libi2pd/KadDHT.h @@ -11,6 +11,7 @@ #define KADDHT_H__ #include +#include #include #include "Identity.h" @@ -42,6 +43,7 @@ namespace data DHTNode * Insert (const IdentHash& h); bool Remove (const IdentHash& h); IdentHash * FindClosest (const IdentHash& h); + std::vector FindClosest (const IdentHash& h, size_t num); void Print (std::stringstream& s); size_t GetSize () const { return m_Size; }; @@ -51,6 +53,7 @@ namespace data DHTNode * Insert (IdentHash * h, DHTNode * root, int level); // recursive bool Remove (const IdentHash& h, DHTNode * root, int level); IdentHash * FindClosest (const IdentHash& h, DHTNode * root, int level); + void FindClosest (const IdentHash& h, size_t num, DHTNode * root, int level, std::vector& hashes); void Print (std::stringstream& s, DHTNode * root, int level); private: