Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright headers.
[simgrid.git] / examples / s4u / dht-kademlia / routing_table.cpp
1 /* Copyright (c) 2012-2018. 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 = new Bucket*[identifier_size + 1];
18   for (unsigned int i = 0; i < identifier_size + 1; i++)
19     buckets[i]        = new Bucket(i);
20 }
21
22 RoutingTable::~RoutingTable()
23 {
24   // Free the buckets.
25   for (unsigned int i = 0; i <= identifier_size; i++) {
26     delete buckets[i];
27   }
28   delete[] buckets;
29 }
30
31 void RoutingTable::print()
32 {
33   XBT_INFO("Routing table of %08x:", id_);
34
35   for (unsigned int i = 0; i <= identifier_size; i++) {
36     if (not buckets[i]->nodes.empty()) {
37       XBT_INFO("Bucket number %u: ", i);
38       int j = 0;
39       for (auto value : buckets[i]->nodes) {
40         XBT_INFO("Element %d: %08x", j, value);
41         j++;
42       }
43     }
44   }
45 }
46
47 /** @brief Finds the corresponding bucket in a routing table for a given identifier
48   * @param id the identifier
49   * @return the bucket in which the the identifier would be.
50   */
51 Bucket* RoutingTable::findBucket(unsigned int id)
52 {
53   unsigned int xor_number = id_ ^ id;
54   unsigned int prefix     = get_node_prefix(xor_number, identifier_size);
55   xbt_assert(prefix <= identifier_size, "Tried to return a  bucket that doesn't exist.");
56   return buckets[prefix];
57 }
58
59 /** Returns if the routing table contains the id. */
60 bool RoutingTable::contains(unsigned int node_id)
61 {
62   Bucket* bucket = findBucket(node_id);
63   return std::find(bucket->nodes.begin(), bucket->nodes.end(), node_id) != bucket->nodes.end();
64 }
65 }