1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
|
/* iksemel (XML parser for Jabber)
** Copyright (C) 2000-2003 Gurer Ozen
** This code is free software; you can redistribute it and/or
** modify it under the terms of GNU Lesser General Public License.
*/
#include "common.h"
#include "iksemel.h"
static unsigned int
hash_str (const char *str)
{
const char *p;
unsigned int h = 0;
for (p = str; *p != '\0'; p++) {
h = ( h << 5 ) - h + *p;
}
return h;
}
struct item {
char *name;
unsigned int count;
struct item *next;
};
struct hash_s {
struct item **table;
unsigned int size;
unsigned int count;
ikstack *s;
};
typedef struct hash_s hash;
hash *
hash_new (unsigned int table_size)
{
hash *h;
h = malloc (sizeof (struct hash_s));
if (!h) return NULL;
h->table = calloc (sizeof (struct item *), table_size);
if (!h->table) {
free (h);
return NULL;
}
h->s = iks_stack_new (sizeof (hash) * 128, 8192);
if (!h->s) {
free (h->table);
free (h);
return NULL;
}
h->size = table_size;
h->count = 0;
return h;
}
char *
hash_insert (hash *h, const char *name)
{
struct item *t, *p;
unsigned int val;
val = hash_str (name) % h->size;
h->count++;
for (t = h->table[val]; t; t = t->next) {
if (strcmp (t->name, name) == 0)
break;
}
if (NULL == t) {
t = iks_stack_alloc (h->s, sizeof (struct item));
if (!t) return NULL;
t->name = iks_stack_strdup (h->s, name, 0);
t->count = 0;
t->next = NULL;
p = h->table[val];
if (!p) {
h->table[val] = t;
} else {
while (1) {
if (p->next == NULL) {
p->next = t;
break;
}
p = p->next;
}
}
}
t->count++;
return t->name;
}
static int
my_cmp (const void *a, const void *b)
{
unsigned int c1, c2;
c1 = (*(struct item **)a)->count;
c2 = (*(struct item **)b)->count;
if (c1 > c2)
return -1;
else if (c1 == c2)
return 0;
else
return 1;
}
void
hash_print (hash *h, char *title_fmt, char *line_fmt)
{
struct item **tags, *t;
unsigned int i = 0, pos = 0;
tags = calloc (sizeof (struct tag *), h->count);
for (; i < h->size; i ++) {
for (t = h->table[i]; t; t = t->next) {
tags[pos++] = t;
}
}
qsort (tags, pos, sizeof (struct item *), my_cmp);
printf (title_fmt, pos);
for (i = 0; i < pos; i++) {
printf (line_fmt, tags[i]->name, tags[i]->count);
}
free (tags);
}
void
hash_delete (hash *h)
{
iks_stack_delete (h->s);
free (h->table);
free (h);
}
|