Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / examples / cpp / dht-kademlia / answer.cpp
1 /* Copyright (c) 2012-2022. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "answer.hpp"
8
9 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(kademlia_node);
10
11 namespace kademlia {
12
13 /** @brief Prints an Answer, for debugging purposes */
14 void Answer::print() const
15 {
16   XBT_INFO("Searching %08x, size %zu", destination_id_, nodes_.size());
17   unsigned int i = 0;
18   for (auto const& contact : nodes_)
19     XBT_INFO("Node %08x: %08x is at distance %u", i++, contact.first, contact.second);
20 }
21
22 /** @brief Merge two answers together, only keeping the best nodes
23   * @param source the source of the nodes to add
24   */
25 unsigned int Answer::merge(const Answer* source)
26 {
27   if (this == source)
28     return 0;
29
30   unsigned int nb_added = 0;
31   for (auto const& contact : source->nodes_) {
32     if (std::find(nodes_.begin(), nodes_.end(), contact) == nodes_.end()) {
33       nodes_.push_back(contact);
34       nb_added++;
35     }
36   }
37   trim();
38   return nb_added;
39 }
40
41 /** @brief Trims an Answer, in order for it to have a size of less or equal to "bucket_size" */
42 void Answer::trim()
43 {
44   // sort by distance
45   std::sort(nodes_.begin(), nodes_.end(),
46             [](const std::pair<unsigned int, unsigned int>& a, const std::pair<unsigned int, unsigned int>& b) {
47               return (a.second < b.second);
48             });
49   if (nodes_.size() > BUCKET_SIZE)
50     nodes_.resize(BUCKET_SIZE);
51 }
52
53 /** @brief Returns if the destination we are trying to find is found
54   * @return if the destination is found.
55   */
56 bool Answer::destinationFound() const
57 {
58   return not nodes_.empty() && nodes_.begin()->second == 0;
59 }
60
61 /** @brief Adds the content of a bucket unsigned into an answer object.
62  * @param bucket the bucket we have to had unsigned into
63  */
64 void Answer::addBucket(const Bucket* bucket)
65 {
66   xbt_assert((bucket != nullptr), "Provided a NULL bucket");
67
68   for (auto const& id : bucket->nodes_) {
69     unsigned int distance = id ^ destination_id_;
70     nodes_.emplace_back(id, distance);
71   }
72 }
73 } // namespace kademlia