Blame view

ns_hash.c 1.56 KB
pdw committed
1 2 3 4
/* hash table */

#include <stdio.h>
#include <stdlib.h>
5
#include <string.h>
pdw committed
6
#include <sys/types.h>
pdw committed
7
#include <sys/socket.h>
pdw committed
8
#include <netinet/in_systm.h>
pdw committed
9 10 11 12
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ns_hash.h"
#include "hash.h"
chris committed
13
#include "iftop.h"
pdw committed
14 15 16 17

#define hash_table_size 256

int ns_hash_compare(void* a, void* b) {
18 19 20 21 22 23 24 25 26 27
    struct in6_addr* aa = (struct in6_addr*)a;
    struct in6_addr* bb = (struct in6_addr*)b;
    return IN6_ARE_ADDR_EQUAL(aa, bb);
}

static int __inline__ hash_uint32(uint32_t n) {
    return ((n & 0x000000FF)
            + ((n & 0x0000FF00) >> 8)
            + ((n & 0x00FF0000) >> 16)
            + ((n & 0xFF000000) >> 24));
pdw committed
28 29 30 31
}

int ns_hash_hash(void* key) {
    int hash;
32
    uint32_t* addr6 = (uint32_t*)((struct in6_addr *) key)->s6_addr;
pdw committed
33

34 35 36 37
    hash = ( hash_uint32(addr6[0])
            + hash_uint32(addr6[1])
            + hash_uint32(addr6[2])
            + hash_uint32(addr6[3])) % 0xFF;
pdw committed
38 39 40 41 42

    return hash;
}

void* ns_hash_copy_key(void* orig) {
43 44
    struct in6_addr* copy;

chris committed
45
    copy = xmalloc(sizeof *copy);
46 47
    memcpy(copy, orig, sizeof *copy);

pdw committed
48 49 50 51 52 53 54 55 56 57 58 59
    return copy;
}

void ns_hash_delete_key(void* key) {
    free(key);
}

/*
 * Allocate and return a hash
 */
hash_type* ns_hash_create() {
    hash_type* hash_table;
chris committed
60
    hash_table = xcalloc(hash_table_size, sizeof *hash_table);
pdw committed
61 62 63 64 65 66 67 68 69
    hash_table->size = hash_table_size;
    hash_table->compare = &ns_hash_compare;
    hash_table->hash = &ns_hash_hash;
    hash_table->delete_key = &ns_hash_delete_key;
    hash_table->copy_key = &ns_hash_copy_key;
    hash_initialise(hash_table);
    return hash_table;
}