Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines with new year.
[simgrid.git] / examples / s4u / dht-kademlia / routing_table.cpp
1 /* Copyright (c) 2012-2020. 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 "routing_table.hpp"
8 #include "node.hpp"
9
10 XBT_LOG_NEW_DEFAULT_CATEGORY(kademlia_routing_table, "Messages specific for this example");
11
12 namespace kademlia {
13
14 /** @brief Initialization of a node routing table.  */
15 RoutingTable::RoutingTable(unsigned int node_id) : id_(node_id)
16 {
17   buckets.reserve(IDENTIFIER_SIZE + 1);
18   for (unsigned int i = 0; i < IDENTIFIER_SIZE + 1; i++)
19     buckets.emplace_back(i);
20 }
21
22 void RoutingTable::print() const
23 {
24   XBT_INFO("Routing table of %08x:", id_);
25
26   for (unsigned int i = 0; i <= IDENTIFIER_SIZE; i++) {
27     if (not buckets[i].nodes.empty()) {
28       XBT_INFO("Bucket number %u: ", i);
29       int j = 0;
30       for (auto value : buckets[i].nodes) {
31         XBT_INFO("Element %d: %08x", j, value);
32         j++;
33       }
34     }
35   }
36 }
37
38 /** @brief Finds the corresponding bucket in a routing table for a given identifier
39   * @param id the identifier
40   * @return the bucket in which the the identifier would be.
41   */
42 Bucket* RoutingTable::findBucket(unsigned int id)
43 {
44   unsigned int xor_number = id_ ^ id;
45   unsigned int prefix     = get_node_prefix(xor_number, IDENTIFIER_SIZE);
46   xbt_assert(prefix <= IDENTIFIER_SIZE, "Tried to return a  bucket that doesn't exist.");
47   return &buckets[prefix];
48 }
49
50 /** Returns if the routing table contains the id. */
51 bool RoutingTable::contains(unsigned int node_id)
52 {
53   const Bucket* bucket = findBucket(node_id);
54   return std::find(bucket->nodes.begin(), bucket->nodes.end(), node_id) != bucket->nodes.end();
55 }
56 }