1////////////////////////////////////////////////////////////////////////////////
2//
3//	File: SFHash.cpp
4//
5//	Date: December 1999
6//
7//	Author: Daniel Switkin
8//
9//	Copyright 2003 (c) by Daniel Switkin. This file is made publically available
10//	under the BSD license, with the stipulations that this complete header must
11//	remain at the top of the file indefinitely, and credit must be given to the
12//	original author in any about box using this software.
13//
14////////////////////////////////////////////////////////////////////////////////
15
16// Additional authors:	Stephan A��mus, <superstippi@gmx.de>
17//						John Scipione, <jscipione@gmail.com>
18
19
20#include "SFHash.h"
21
22#include <stdio.h>
23#include <stdlib.h>
24
25
26SFHash::SFHash(int size) {
27	fatalerror = false;
28	this->size = size;
29	iterate_pos = iterate_depth = 0;
30	main_array = (HashItem**)malloc(this->size * sizeof(HashItem*));
31
32	if (main_array == NULL) {
33		fatalerror = true;
34		return;
35	}
36
37	for (int x = 0; x < this->size; x++)
38		main_array[x] = NULL;
39}
40
41
42SFHash::~SFHash() {
43	for (int x = 0; x < size; x++) {
44		HashItem* item = main_array[x];
45		while (item != NULL) {
46			HashItem* t = item->next;
47			delete item;
48			item = t;
49		}
50	}
51    free(main_array);
52}
53
54
55void
56SFHash::AddItem(HashItem* item) {
57	item->next = NULL;
58	int pos = item->key % size;
59
60	if (main_array[pos] == NULL)
61		main_array[pos] = item;
62	else {
63		HashItem* temp = main_array[pos];
64		while (temp->next != NULL) temp = temp->next;
65		temp->next = item;
66	}
67}
68
69
70HashItem*
71SFHash::GetItem(unsigned int key)
72{
73	int pos = key % size;
74	HashItem* item = main_array[pos];
75
76	while (item != NULL) {
77		if (item->key == key) return item;
78		item = item->next;
79	}
80
81	return NULL;
82}
83
84
85unsigned int
86SFHash::CountItems()
87{
88	unsigned int count = 0;
89	for (int x = 0; x < this->size; x++) {
90		HashItem* item = main_array[x];
91		while (item != NULL) {
92			count++;
93			item = item->next;
94		}
95	}
96
97	return count;
98}
99
100
101HashItem*
102SFHash::NextItem()
103{
104	if (iterate_pos >= size) {
105		Rewind();
106		return NULL;
107	}
108	HashItem* item;
109	while ((item = main_array[iterate_pos]) == NULL)
110		iterate_pos++;
111
112	for (int d = 0; d < iterate_depth; d++)
113		item = item->next;
114
115	if (item->next != NULL)
116		iterate_depth++;
117	else {
118		iterate_pos++;
119		iterate_depth = 0;
120	}
121
122	return item;
123}
124
125
126void
127SFHash::Rewind() {
128	iterate_pos = 0;
129	iterate_depth = 0;
130}
131