modified: tags
[yuchen.git] / sfhashfcn.c
blob09764284e8d5fc2daf8cc38df37dfdbd2093a77b
1 /****************************************************************************
3 * Copyright (C) 2003-2009 Sourcefire, Inc.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License Version 2 as
7 * published by the Free Software Foundation. You may not use, modify or
8 * distribute this program under any other version of the GNU General
9 * Public License.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 ****************************************************************************/
23 sfhashfcn.c
25 Each hash table must allocate it's own SFGHASH struct, this is because
26 sfghash_new uses the number of rows in the hash table to modulo the random
27 values.
29 Updates:
31 8/31/2006 - man - changed to use sfprimetable.c
34 #include "sfhashfcn.h"
35 #include "sfprimetable.h"
38 SFHASHFCN * sfhashfcn_new( int m )
40 SFHASHFCN * p;
41 static int one=1;
43 if( one ) /* one time init */
45 srand( (unsigned) time(0) );
46 one = 0;
49 // This can make all of the hashing static for testing.
50 //#define rand() 0
52 p = (SFHASHFCN*) calloc( 1,sizeof(SFHASHFCN) );
53 if( !p )
54 return 0;
57 p->seed = sf_nearest_prime( (rand()%m)+3191 );
58 p->scale = sf_nearest_prime( (rand()%m)+709 );
59 p->hardener = (rand()*rand()) + 133824503;
62 p->hash_fcn = &sfhashfcn_hash;
63 p->keycmp_fcn = &memcmp;
65 return p;
68 void sfhashfcn_free( SFHASHFCN * p )
70 if( p )
72 free( p);
76 void sfhashfcn_static( SFHASHFCN * p )
78 p->seed = 3193;
79 p->scale = 719;
80 p->hardener = 133824503;
83 unsigned sfhashfcn_hash( SFHASHFCN * p, unsigned char *d, int n )
85 #if 1
86 unsigned hash = p->seed;
87 while( n )
89 hash *= p->scale;
90 hash += *d++;
91 n--;
93 return hash ^ p->hardener;
94 #else
95 unsigned int hash = 5381;
96 while(n){
97 hash += (hash << 5) + (*d++);
98 n--;
100 return hash;
101 #endif
104 /**
105 * Make sfhashfcn use a separate set of operators for the backend.
107 * @param h sfhashfcn ptr
108 * @param hash_fcn user specified hash function
109 * @param keycmp_fcn user specified key comparisoin function
111 int sfhashfcn_set_keyops( SFHASHFCN *h,
112 unsigned (*hash_fcn)( SFHASHFCN * p,
113 unsigned char *d,
114 int n),
115 int (*keycmp_fcn)( const void *s1,
116 const void *s2,
117 size_t n))
119 if(h && hash_fcn && keycmp_fcn)
121 h->hash_fcn = hash_fcn;
122 h->keycmp_fcn = keycmp_fcn;
124 return 0;
127 return -1;