Home | History | Annotate | Download | only in lhash
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com) * All rights reserved.
      2  *
      3  * This package is an SSL implementation written
      4  * by Eric Young (eay (at) cryptsoft.com).
      5  * The implementation was written so as to conform with Netscapes SSL.
      6  *
      7  * This library is free for commercial and non-commercial use as long as
      8  * the following conditions are aheared to.  The following conditions
      9  * apply to all code found in this distribution, be it the RC4, RSA,
     10  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     11  * included with this distribution is covered by the same copyright terms
     12  * except that the holder is Tim Hudson (tjh (at) cryptsoft.com).
     13  *
     14  * Copyright remains Eric Young's, and as such any Copyright notices in
     15  * the code are not to be removed.
     16  * If this package is used in a product, Eric Young should be given attribution
     17  * as the author of the parts of the library used.
     18  * This can be in the form of a textual message at program startup or
     19  * in documentation (online or textual) provided with the package.
     20  *
     21  * Redistribution and use in source and binary forms, with or without
     22  * modification, are permitted provided that the following conditions
     23  * are met:
     24  * 1. Redistributions of source code must retain the copyright
     25  *    notice, this list of conditions and the following disclaimer.
     26  * 2. Redistributions in binary form must reproduce the above copyright
     27  *    notice, this list of conditions and the following disclaimer in the
     28  *    documentation and/or other materials provided with the distribution.
     29  * 3. All advertising materials mentioning features or use of this software
     30  *    must display the following acknowledgement:
     31  *    "This product includes cryptographic software written by
     32  *     Eric Young (eay (at) cryptsoft.com)"
     33  *    The word 'cryptographic' can be left out if the rouines from the library
     34  *    being used are not cryptographic related :-).
     35  * 4. If you include any Windows specific code (or a derivative thereof) from
     36  *    the apps directory (application code) you must include an acknowledgement:
     37  *    "This product includes software written by Tim Hudson (tjh (at) cryptsoft.com)"
     38  *
     39  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     40  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     42  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     43  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     44  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     45  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     47  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     48  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     49  * SUCH DAMAGE.
     50  *
     51  * The licence and distribution terms for any publically available version or
     52  * derivative of this code cannot be changed.  i.e. this code cannot simply be
     53  * copied and put under another distribution licence
     54  * [including the GNU Public Licence.] */
     55 
     56 #include <openssl/lhash.h>
     57 
     58 #include <assert.h>
     59 #include <limits.h>
     60 
     61 #include <openssl/mem.h>
     62 
     63 /* kMinNumBuckets is the minimum size of the buckets array in an |_LHASH|. */
     64 static const size_t kMinNumBuckets = 16;
     65 
     66 /* kMaxAverageChainLength contains the maximum, average chain length. When the
     67  * average chain length exceeds this value, the hash table will be resized. */
     68 static const size_t kMaxAverageChainLength = 2;
     69 static const size_t kMinAverageChainLength = 1;
     70 
     71 _LHASH *lh_new(lhash_hash_func hash, lhash_cmp_func comp) {
     72   _LHASH *ret;
     73 
     74   ret = OPENSSL_malloc(sizeof(_LHASH));
     75   if (ret == NULL) {
     76     return NULL;
     77   }
     78   memset(ret, 0, sizeof(_LHASH));
     79 
     80   ret->num_buckets = kMinNumBuckets;
     81   ret->buckets = OPENSSL_malloc(sizeof(LHASH_ITEM *) * ret->num_buckets);
     82   if (ret->buckets == NULL) {
     83     OPENSSL_free(ret);
     84     return NULL;
     85   }
     86   memset(ret->buckets, 0, sizeof(LHASH_ITEM *) * ret->num_buckets);
     87 
     88   ret->comp = comp;
     89   if (ret->comp == NULL) {
     90     ret->comp = (lhash_cmp_func) strcmp;
     91   }
     92   ret->hash = hash;
     93   if (ret->hash == NULL) {
     94     ret->hash = (lhash_hash_func) lh_strhash;
     95   }
     96 
     97   return ret;
     98 }
     99 
    100 void lh_free(_LHASH *lh) {
    101   size_t i;
    102   LHASH_ITEM *n, *next;
    103 
    104   if (lh == NULL) {
    105     return;
    106   }
    107 
    108   for (i = 0; i < lh->num_buckets; i++) {
    109     for (n = lh->buckets[i]; n != NULL; n = next) {
    110       next = n->next;
    111       OPENSSL_free(n);
    112     }
    113   }
    114 
    115   OPENSSL_free(lh->buckets);
    116   OPENSSL_free(lh);
    117 }
    118 
    119 size_t lh_num_items(const _LHASH *lh) { return lh->num_items; }
    120 
    121 /* get_next_ptr_and_hash returns a pointer to the pointer that points to the
    122  * item equal to |data|. In other words, it searches for an item equal to |data|
    123  * and, if it's at the start of a chain, then it returns a pointer to an
    124  * element of |lh->buckets|, otherwise it returns a pointer to the |next|
    125  * element of the previous item in the chain. If an element equal to |data| is
    126  * not found, it returns a pointer that points to a NULL pointer. If |out_hash|
    127  * is not NULL, then it also puts the hash value of |data| in |*out_hash|. */
    128 static LHASH_ITEM **get_next_ptr_and_hash(const _LHASH *lh, uint32_t *out_hash,
    129                                           const void *data) {
    130   const uint32_t hash = lh->hash(data);
    131   LHASH_ITEM *cur, **ret;
    132 
    133   if (out_hash != NULL) {
    134     *out_hash = hash;
    135   }
    136 
    137   ret = &lh->buckets[hash % lh->num_buckets];
    138   for (cur = *ret; cur != NULL; cur = *ret) {
    139     if (lh->comp(cur->data, data) == 0) {
    140       break;
    141     }
    142     ret = &cur->next;
    143   }
    144 
    145   return ret;
    146 }
    147 
    148 void *lh_retrieve(const _LHASH *lh, const void *data) {
    149   LHASH_ITEM **next_ptr;
    150 
    151   next_ptr = get_next_ptr_and_hash(lh, NULL, data);
    152 
    153   if (*next_ptr == NULL) {
    154     return NULL;
    155   }
    156 
    157   return (*next_ptr)->data;
    158 }
    159 
    160 /* lh_rebucket allocates a new array of |new_num_buckets| pointers and
    161  * redistributes the existing items into it before making it |lh->buckets| and
    162  * freeing the old array. */
    163 static void lh_rebucket(_LHASH *lh, const size_t new_num_buckets) {
    164   LHASH_ITEM **new_buckets, *cur, *next;
    165   size_t i, alloc_size;
    166 
    167   alloc_size = sizeof(LHASH_ITEM *) * new_num_buckets;
    168   if (alloc_size / sizeof(LHASH_ITEM*) != new_num_buckets) {
    169     return;
    170   }
    171 
    172   new_buckets = OPENSSL_malloc(alloc_size);
    173   if (new_buckets == NULL) {
    174     return;
    175   }
    176   memset(new_buckets, 0, alloc_size);
    177 
    178   for (i = 0; i < lh->num_buckets; i++) {
    179     for (cur = lh->buckets[i]; cur != NULL; cur = next) {
    180       const size_t new_bucket = cur->hash % new_num_buckets;
    181       next = cur->next;
    182       cur->next = new_buckets[new_bucket];
    183       new_buckets[new_bucket] = cur;
    184     }
    185   }
    186 
    187   OPENSSL_free(lh->buckets);
    188 
    189   lh->num_buckets = new_num_buckets;
    190   lh->buckets = new_buckets;
    191 }
    192 
    193 /* lh_maybe_resize resizes the |buckets| array if needed. */
    194 static void lh_maybe_resize(_LHASH *lh) {
    195   size_t avg_chain_length;
    196 
    197   if (lh->callback_depth > 0) {
    198     /* Don't resize the hash if we are currently iterating over it. */
    199     return;
    200   }
    201 
    202   assert(lh->num_buckets >= kMinNumBuckets);
    203   avg_chain_length = lh->num_items / lh->num_buckets;
    204 
    205   if (avg_chain_length > kMaxAverageChainLength) {
    206     const size_t new_num_buckets = lh->num_buckets * 2;
    207 
    208     if (new_num_buckets > lh->num_buckets) {
    209       lh_rebucket(lh, new_num_buckets);
    210     }
    211   } else if (avg_chain_length < kMinAverageChainLength &&
    212              lh->num_buckets > kMinNumBuckets) {
    213     size_t new_num_buckets = lh->num_buckets / 2;
    214 
    215     if (new_num_buckets < kMinNumBuckets) {
    216       new_num_buckets = kMinNumBuckets;
    217     }
    218 
    219     lh_rebucket(lh, new_num_buckets);
    220   }
    221 }
    222 
    223 int lh_insert(_LHASH *lh, void **old_data, void *data) {
    224   uint32_t hash;
    225   LHASH_ITEM **next_ptr, *item;
    226 
    227   *old_data = NULL;
    228   next_ptr = get_next_ptr_and_hash(lh, &hash, data);
    229 
    230 
    231   if (*next_ptr != NULL) {
    232     /* An element equal to |data| already exists in the hash table. It will be
    233      * replaced. */
    234     *old_data = (*next_ptr)->data;
    235     (*next_ptr)->data = data;
    236     return 1;
    237   }
    238 
    239   /* An element equal to |data| doesn't exist in the hash table yet. */
    240   item = OPENSSL_malloc(sizeof(LHASH_ITEM));
    241   if (item == NULL) {
    242     return 0;
    243   }
    244 
    245   item->data = data;
    246   item->hash = hash;
    247   item->next = NULL;
    248   *next_ptr = item;
    249   lh->num_items++;
    250   lh_maybe_resize(lh);
    251 
    252   return 1;
    253 }
    254 
    255 void *lh_delete(_LHASH *lh, const void *data) {
    256   LHASH_ITEM **next_ptr, *item, *ret;
    257 
    258   next_ptr = get_next_ptr_and_hash(lh, NULL, data);
    259 
    260   if (*next_ptr == NULL) {
    261     /* No such element. */
    262     return NULL;
    263   }
    264 
    265   item = *next_ptr;
    266   *next_ptr = item->next;
    267   ret = item->data;
    268   OPENSSL_free(item);
    269 
    270   lh->num_items--;
    271   lh_maybe_resize(lh);
    272 
    273   return ret;
    274 }
    275 
    276 static void lh_doall_internal(_LHASH *lh, void (*no_arg_func)(void *),
    277                               void (*arg_func)(void *, void *), void *arg) {
    278   size_t i;
    279   LHASH_ITEM *cur, *next;
    280 
    281   if (lh == NULL) {
    282     return;
    283   }
    284 
    285   if (lh->callback_depth < UINT_MAX) {
    286     /* |callback_depth| is a saturating counter. */
    287     lh->callback_depth++;
    288   }
    289 
    290   for (i = 0; i < lh->num_buckets; i++) {
    291     for (cur = lh->buckets[i]; cur != NULL; cur = next) {
    292       next = cur->next;
    293       if (arg_func) {
    294         arg_func(cur->data, arg);
    295       } else {
    296         no_arg_func(cur->data);
    297       }
    298     }
    299   }
    300 
    301   if (lh->callback_depth < UINT_MAX) {
    302     lh->callback_depth--;
    303   }
    304 
    305   /* The callback may have added or removed elements and the non-zero value of
    306    * |callback_depth| will have suppressed any resizing. Thus any needed
    307    * resizing is done here. */
    308   lh_maybe_resize(lh);
    309 }
    310 
    311 void lh_doall(_LHASH *lh, void (*func)(void *)) {
    312   lh_doall_internal(lh, func, NULL, NULL);
    313 }
    314 
    315 void lh_doall_arg(_LHASH *lh, void (*func)(void *, void *), void *arg) {
    316   lh_doall_internal(lh, NULL, func, arg);
    317 }
    318 
    319 uint32_t lh_strhash(const char *c) {
    320   /* The following hash seems to work very well on normal text strings
    321    * no collisions on /usr/dict/words and it distributes on %2^n quite
    322    * well, not as good as MD5, but still good. */
    323   unsigned long ret = 0;
    324   long n;
    325   unsigned long v;
    326   int r;
    327 
    328   if ((c == NULL) || (*c == '\0')) {
    329     return (ret);
    330   }
    331 
    332   n = 0x100;
    333   while (*c) {
    334     v = n | (*c);
    335     n += 0x100;
    336     r = (int)((v >> 2) ^ v) & 0x0f;
    337     ret = (ret << r) | (ret >> (32 - r));
    338     ret &= 0xFFFFFFFFL;
    339     ret ^= v * v;
    340     c++;
    341   }
    342 
    343   return ((ret >> 16) ^ ret);
    344 }
    345