#include <ctype.h>
#include "hashfuncs.h"

/*
 * Multiplicative hash function.
 *
 * The value "2654435769" is the bottom 32 bits of
 * (sqrt(5) - 1)/2 * 2^32.
 *
 * This hash function is mentioned in "Cormen, Leiserson, Rivest"
 * as one recommended by Knuth.
 */

int hash_int(int x) {
    /*
     * Multiply by a constant and take the bottom bits of the
     * result.
     */

    return (int) ((((unsigned int) x) * 2654435769u) & 0x7fffffff);
}

/* String hashing out of The Dragon Book. */
int hash_string(char const* x) {
    char const* p;
    unsigned int h = 0;
    unsigned int g;

    for (p = x; *p != '\0'; p++) {
        h = (h << 4) + *p;
        if ((g = h & 0xf0000000)) {
            h = h ^ (g >> 24);
            h = h ^ g;
        }
    }
    return (int) h;
}

int hash_string_lowercase(char const* x) {
    char const* p;
    unsigned int h = 0;
    unsigned int g;

    for (p = x; *p != '\0'; p++) {
        h = (h << 4) + tolower(*p);
        if ((g = h & 0xf0000000)) {
            h = h ^ (g >> 24);
            h = h ^ g;
        }
    }
    return (int) h;
}
