#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "libiberty.h"
#include "partition.h"
static int elem_compare PARAMS ((const void *, const void *));
partition
partition_new (num_elements)
int num_elements;
{
int e;
partition part = (partition)
xmalloc (sizeof (struct partition_def) +
(num_elements - 1) * sizeof (struct partition_elem));
part->num_elements = num_elements;
for (e = 0; e < num_elements; ++e)
{
part->elements[e].class_element = e;
part->elements[e].next = &(part->elements[e]);
part->elements[e].class_count = 1;
}
return part;
}
void
partition_delete (part)
partition part;
{
free (part);
}
int
partition_union (part, elem1, elem2)
partition part;
int elem1;
int elem2;
{
struct partition_elem *elements = part->elements;
struct partition_elem *e1;
struct partition_elem *e2;
struct partition_elem *p;
struct partition_elem *old_next;
int class_element = elements[elem1].class_element;
if (class_element == elements[elem2].class_element)
return class_element;
if (elements[elem1].class_count < elements[elem2].class_count)
{
int temp = elem1;
elem1 = elem2;
elem2 = temp;
class_element = elements[elem1].class_element;
}
e1 = &(elements[elem1]);
e2 = &(elements[elem2]);
elements[class_element].class_count
+= elements[e2->class_element].class_count;
e2->class_element = class_element;
for (p = e2->next; p != e2; p = p->next)
p->class_element = class_element;
old_next = e1->next;
e1->next = e2->next;
e2->next = old_next;
return class_element;
}
static int
elem_compare (elem1, elem2)
const void *elem1;
const void *elem2;
{
int e1 = * (const int *) elem1;
int e2 = * (const int *) elem2;
if (e1 < e2)
return -1;
else if (e1 > e2)
return 1;
else
return 0;
}
void
partition_print (part, fp)
partition part;
FILE *fp;
{
char *done;
int num_elements = part->num_elements;
struct partition_elem *elements = part->elements;
int *class_elements;
int e;
done = (char *) xmalloc (num_elements);
memset (done, 0, num_elements);
class_elements = (int *) xmalloc (num_elements * sizeof (int));
fputc ('[', fp);
for (e = 0; e < num_elements; ++e)
if (! done[e])
{
int c = e;
int count = elements[elements[e].class_element].class_count;
int i;
for (i = 0; i < count; ++i) {
class_elements[i] = c;
done[c] = 1;
c = elements[c].next - elements;
}
qsort ((void *) class_elements, count, sizeof (int), elem_compare);
fputc ('(', fp);
for (i = 0; i < count; ++i)
fprintf (fp, i == 0 ? "%d" : " %d", class_elements[i]);
fputc (')', fp);
}
fputc (']', fp);
free (done);
}