Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework gvm_hosts_shuffle() implementation. #199

Merged
merged 1 commit into from
Mar 21, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 28 additions & 17 deletions base/hosts.c
Original file line number Diff line number Diff line change
Expand Up @@ -1224,34 +1224,45 @@ gvm_hosts_free (gvm_hosts_t *hosts)
void
gvm_hosts_shuffle (gvm_hosts_t *hosts)
{
int count;
GList *new_list;
size_t i = 0;
GRand *rand;
GList *element;
void **shuffle_array;

if (hosts == NULL)
return;

count = gvm_hosts_count (hosts);
new_list = NULL;

/* Store all host pointers in an array. */
shuffle_array = g_malloc0 (hosts->count * sizeof (gvm_host_t *));
element = hosts->hosts;
while (element)
{
shuffle_array[i] = element->data;
element = element->next;
i++;
}
/* Shuffle the array. */
rand = g_rand_new ();
for (i = 0; i < hosts->count; i++)
{
void *tmp;
int j = g_rand_int_range (rand, 0, hosts->count);

while (count)
tmp = shuffle_array[i];
shuffle_array[i] = shuffle_array[j];
shuffle_array[j] = tmp;
}
/* Insert shuffled hosts in the list. */
element = hosts->hosts;
for (i = 0; i < hosts->count; i++)
{
GList *element;

/* Get element from random position [0, count[. */
element = g_list_nth (hosts->hosts, g_rand_int_range (rand, 0, count));
/* Remove it. */
hosts->hosts = g_list_remove_link (hosts->hosts, element);
/* Insert it in new list */
new_list = g_list_concat (element, new_list);
count--;
element->data = shuffle_array[i];
element = element->next;
}
hosts->hosts = new_list;
hosts->current = hosts->hosts;

hosts->current = hosts->hosts;
g_rand_free (rand);
g_free (shuffle_array);
}

/**
Expand Down