summaryrefslogtreecommitdiff
path: root/ns_hash.c
blob: 219de952bc9eb0bd6cfca8482812e068da22afaf (plain)
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
/* hash table */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ns_hash.h"
#include "hash.h"
#include "iftop.h"

#define hash_table_size 256

int ns_hash_compare(void* a, void* b) {
    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));
}

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

    hash = ( hash_uint32(addr6[0])
            + hash_uint32(addr6[1])
            + hash_uint32(addr6[2])
            + hash_uint32(addr6[3])) % 0xFF;

    return hash;
}

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

    copy = xmalloc(sizeof *copy);
    memcpy(copy, orig, sizeof *copy);

    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;
    hash_table = xcalloc(hash_table_size, sizeof *hash_table);
    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;
}