1 /* Copyright (c) 2012-2021. The SimGrid Team.
2 * All rights reserved. */
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. */
7 #include "routing_table.h"
10 XBT_LOG_NEW_DEFAULT_CATEGORY(dht_kademlia_routing_table, "Messages specific for this example");
12 /** @brief Initialization of a node routing table. */
13 routing_table_t routing_table_init(unsigned int node_id)
15 routing_table_t table = xbt_new(s_routing_table_t, 1);
16 table->buckets = xbt_new(s_bucket_t, IDENTIFIER_SIZE + 1);
17 for (unsigned int i = 0; i < IDENTIFIER_SIZE + 1; i++) {
18 table->buckets[i].nodes = xbt_dynar_new(sizeof(unsigned int), NULL);
19 table->buckets[i].id = i;
25 /** @brief Frees the routing table */
26 void routing_table_free(routing_table_t table)
29 for (unsigned int i = 0; i <= IDENTIFIER_SIZE; i++) {
30 xbt_dynar_free(&table->buckets[i].nodes);
32 xbt_free(table->buckets);
36 /**@brief prints the routing table, to debug stuff. */
37 void routing_table_print(const_routing_table_t table)
39 XBT_INFO("Routing table of %08x:", table->id);
41 for (unsigned int i = 0; i <= IDENTIFIER_SIZE; i++) {
42 if (!xbt_dynar_is_empty(table->buckets[i].nodes)) {
43 XBT_INFO("Bucket number %u: ", i);
46 xbt_dynar_foreach (table->buckets[i].nodes, j, value) {
47 XBT_INFO("Element %u: %08x", j, value);
53 /** @brief Finds an identifier in a bucket and returns its position or returns -1 if it doesn't exists
54 * @param bucket the bucket in which we try to find our identifier
57 unsigned int bucket_find_id(const_bucket_t bucket, unsigned int id)
60 unsigned int current_id;
61 xbt_dynar_foreach (bucket->nodes, i, current_id) {
62 if (id == current_id) {
69 /** @brief Finds the corresponding bucket in a routing table for a given identifier
70 * @param table the routing table
71 * @param id the identifier
72 * @return the bucket in which the the identifier would be.
74 bucket_t routing_table_find_bucket(const_routing_table_t table, unsigned int id)
76 unsigned int xor_number = table->id ^ id;
77 unsigned int prefix = get_node_prefix(xor_number, IDENTIFIER_SIZE);
78 xbt_assert(prefix <= IDENTIFIER_SIZE, "Tried to return a bucket that doesn't exist.");
79 bucket_t bucket = &table->buckets[prefix];