Skip to content

Commit 33439d7

Browse files
committed
refactor: Make add_to_list non-recursive.
1 parent f84e8cd commit 33439d7

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

toxcore/DHT.c

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -606,27 +606,42 @@ bool add_to_list(
606606
Node_format *nodes_list, uint32_t length, const uint8_t pk[CRYPTO_PUBLIC_KEY_SIZE],
607607
const IP_Port *ip_port, const uint8_t cmp_pk[CRYPTO_PUBLIC_KEY_SIZE])
608608
{
609-
for (uint32_t i = 0; i < length; ++i) {
610-
Node_format *node = &nodes_list[i];
609+
uint8_t pk_cur[CRYPTO_PUBLIC_KEY_SIZE];
610+
memcpy(pk_cur, pk, CRYPTO_PUBLIC_KEY_SIZE);
611+
IP_Port ip_port_cur = *ip_port;
611612

612-
if (id_closest(cmp_pk, node->public_key, pk) == 2) {
613-
uint8_t pk_bak[CRYPTO_PUBLIC_KEY_SIZE];
614-
memcpy(pk_bak, node->public_key, CRYPTO_PUBLIC_KEY_SIZE);
613+
bool inserted = false;
614+
bool done = false;
615615

616-
const IP_Port ip_port_bak = node->ip_port;
617-
memcpy(node->public_key, pk, CRYPTO_PUBLIC_KEY_SIZE);
616+
while (!done) {
617+
done = true;
618618

619-
node->ip_port = *ip_port;
619+
for (uint32_t i = 0; i < length; ++i) {
620+
Node_format *node = &nodes_list[i];
620621

621-
if (i != length - 1) {
622-
add_to_list(nodes_list, length, pk_bak, &ip_port_bak, cmp_pk);
623-
}
622+
if (id_closest(cmp_pk, node->public_key, pk_cur) == 2) {
623+
uint8_t pk_bak[CRYPTO_PUBLIC_KEY_SIZE];
624+
memcpy(pk_bak, node->public_key, CRYPTO_PUBLIC_KEY_SIZE);
624625

625-
return true;
626+
const IP_Port ip_port_bak = node->ip_port;
627+
memcpy(node->public_key, pk_cur, CRYPTO_PUBLIC_KEY_SIZE);
628+
629+
node->ip_port = ip_port_cur;
630+
631+
if (i == length - 1) {
632+
return true;
633+
}
634+
635+
memcpy(pk_cur, pk_bak, CRYPTO_PUBLIC_KEY_SIZE);
636+
ip_port_cur = ip_port_bak;
637+
done = false;
638+
inserted = true;
639+
break;
640+
}
626641
}
627642
}
628643

629-
return false;
644+
return inserted;
630645
}
631646

632647
/**

0 commit comments

Comments
 (0)