Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0afc935e8437860e881a2f622429ebf8acc8a880
[simgrid.git] / examples / s4u / dht-kademlia / answer.cpp
1 /* Copyright (c) 2012-2019. 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 bool sortbydistance(const std::pair<unsigned int, unsigned int>& a, const std::pair<unsigned int, unsigned int>& b)
14 {
15   return (a.second < b.second);
16 }
17
18 /** @brief Prints a answer_t, for debugging purposes */
19 void Answer::print()
20 {
21   XBT_INFO("Searching %08x, size %u", destination_id_, size_);
22   unsigned int i = 0;
23   for (auto contact : nodes)
24     XBT_INFO("Node %08x: %08x is at distance %u", i++, contact.first, contact.second);
25 }
26
27 /** @brief Merge two answers together, only keeping the best nodes
28   * @param source the source of the nodes to add
29   */
30 unsigned int Answer::merge(Answer* source)
31 {
32   if (this == source)
33     return 0;
34
35   unsigned int nb_added = 0;
36   for (auto contact : source->nodes) {
37     if (std::find(nodes.begin(), nodes.end(), contact) == nodes.end()) {
38       nodes.push_back(contact);
39       size_++;
40       nb_added++;
41     }
42   }
43   std::sort(nodes.begin(), nodes.end(), sortbydistance);
44   trim();
45   return nb_added;
46 }
47
48 /** @brief Trims an Answer, in order for it to have a size of less or equal to "bucket_size" */
49 void Answer::trim()
50 {
51   while (size_ > BUCKET_SIZE) {
52     nodes.pop_back();
53     size_--;
54   }
55   xbt_assert(nodes.size() == size_, "Wrong size for the answer");
56 }
57
58 /** @brief Returns if the destination we are trying to find is found
59   * @return if the destination is found.
60   */
61 bool Answer::destinationFound()
62 {
63   if (nodes.empty())
64     return 0;
65
66   return (*nodes.begin()).second == 0;
67 }
68
69 /** @brief Adds the content of a bucket unsigned into a answer object.
70   * @param bucket the bucket we have to had unsigned into
71   */
72 void Answer::addBucket(const Bucket* bucket)
73 {
74   xbt_assert((bucket != nullptr), "Provided a NULL bucket");
75
76   for (auto id : bucket->nodes) {
77     unsigned int distance = id ^ destination_id_;
78     nodes.push_back(std::pair<unsigned int, unsigned int>(id, distance));
79     size_++;
80   }
81 }
82 }