xref: /haiku/src/add-ons/translators/gif/SFHash.cpp (revision 820dca4df6c7bf955c46e8f6521b9408f50b2900)
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 
18 #include "SFHash.h"
19 #include <stdlib.h>
20 #include <stdio.h>
21 
22 SFHash::SFHash(int size) {
23 	fatalerror = false;
24 	this->size = size;
25 	iterate_pos = iterate_depth = 0;
26 	main_array = (HashItem **)malloc(this->size * sizeof(HashItem *));
27 
28     if (main_array == NULL) {
29 		fatalerror = true;
30 		return;
31 	}
32 	for (int x = 0; x < this->size; x++) {
33 		main_array[x] = NULL;
34 	}
35 }
36 
37 void SFHash::AddItem(HashItem *item) {
38 	item->next = NULL;
39 	int pos = item->key % size;
40 
41 	if (main_array[pos] == NULL) {
42 		main_array[pos] = item;
43 	}
44 	else {
45 		HashItem *temp = main_array[pos];
46 		while (temp->next != NULL) temp = temp->next;
47 		temp->next = item;
48 	}
49 }
50 
51 HashItem*
52 SFHash::GetItem(unsigned int key)
53 {
54 	int pos = key % size;
55 	HashItem *item = main_array[pos];
56 
57 	while (item != NULL) {
58 		if (item->key == key) return item;
59 		item = item->next;
60 	}
61 	return NULL;
62 }
63 
64 unsigned int
65 SFHash::CountItems()
66 {
67     unsigned int count = 0;
68     for (int x = 0; x < this->size; x++) {
69         HashItem *item = main_array[x];
70         while (item != NULL) {
71             count++;
72             item = item->next;
73         }
74     }
75     return count;
76 }
77 
78 HashItem*
79 SFHash::NextItem()
80 {
81     if (iterate_pos >= size) {
82         Rewind();
83         return NULL;
84     }
85     HashItem *item;
86     while ((item = main_array[iterate_pos]) == NULL) iterate_pos++;
87     for (int d = 0; d < iterate_depth; d++) {
88         item = item->next;
89     }
90 
91     if (item->next != NULL) iterate_depth++;
92     else {
93         iterate_pos++;
94         iterate_depth = 0;
95     }
96     return item;
97 }
98 
99 void SFHash::Rewind() {
100     iterate_pos = 0;
101     iterate_depth = 0;
102 }
103 
104 SFHash::~SFHash() {
105 	for (int x = 0; x < size; x++) {
106 		HashItem *item = main_array[x];
107 		while (item != NULL) {
108 			HashItem *t = item->next;
109 			delete item;
110 			item = t;
111 		}
112 	}
113     free(main_array);
114 }
115 
116