gecko-dev/rdf/opendir/hash.c

112 строки
2.6 KiB
C
Исходник Обычный вид История

1998-12-10 02:08:59 +03:00
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
1998-12-10 02:08:59 +03:00
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
1998-12-10 02:08:59 +03:00
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
1998-12-10 02:08:59 +03:00
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
1998-12-10 02:08:59 +03:00
*/
/* This file holds a temporary implementation of hash tables. It will
be replaced with STL or NSPR
*/
#include "rdf-int.h"
typedef struct _HashEntryStruct {
struct _HashEntryStruct* next; /* hash chain linkage */
char* key;
void* value;
} HashEntryStruct;
typedef HashEntryStruct* HashEntry;
typedef struct _HashTableStruct {
int size;
HashEntry* buckets; /* vector of hash buckets */
} HashTableStruct;
1998-12-10 02:08:59 +03:00
int
hashKey (HashTable ht, char* key) {
size_t len = strlen(key);
int sum = 0;
size_t n = 0;
int ans;
1998-12-10 02:08:59 +03:00
for (n = 0; n < len; n++) sum = sum + (int)key[n];
ans = sum & ht->size;
if (ans == ht->size) ans = ans-1;
return ans;
1998-12-10 02:08:59 +03:00
}
HashTable
NewHashTable(int size) {
HashTable ht = (HashTable)getMem(sizeof(HashTableStruct));
ht->size = size;
ht->buckets = (HashEntry*)getMem(sizeof(HashEntry) * size);
return ht;
}
void*
HashLookup(HashTable ht, char* key) {
int offset = hashKey(ht, key);
HashEntry he = ht->buckets[offset];
while (he) {
if (strcmp(he->key, key) == 0) return he->value;
he = he->next;
}
return NULL;
}
1998-12-15 03:11:09 +03:00
int catCount = 0;
int itemCount = 0;
1998-12-10 02:08:59 +03:00
void
HashAdd (HashTable ht, char* key, void* value) {
int offset = hashKey(ht, key);
HashEntry he = ht->buckets[offset];
HashEntry prev = he;
while (he) {
if (strcmp(he->key, key) == 0) {
if (value == he->value) {
return;
} else {
he->value = value;
return;
}
}
prev = he;
he = he->next;
}
1998-12-15 03:11:09 +03:00
if (startsWith("http://", key)) {
itemCount++;
} else {
catCount++;
}
he = (HashEntry) fgetMem(sizeof(HashEntryStruct));
1998-12-10 02:08:59 +03:00
he->value = value;
he->key = key;
if (prev) {
prev->next = he;
1998-12-10 02:08:59 +03:00
} else {
ht->buckets[offset] = he;
1998-12-10 02:08:59 +03:00
}
}