codekingpro/portable-devtools
114k
1/*2 * Utilities for working with hash values.3 *4 * Portions Copyright (c) 2017-2023, PostgreSQL Global Development Group5 */6 7#ifndef HASHFN_H8#define HASHFN_H9 10 11/*12 * Rotate the high 32 bits and the low 32 bits separately. The standard13 * hash function sometimes rotates the low 32 bits by one bit when14 * combining elements. We want extended hash functions to be compatible with15 * that algorithm when the seed is 0, so we can't just do a normal rotation.16 * This works, though.17 */18#define ROTATE_HIGH_AND_LOW_32BITS(v) \19 ((((v) << 1) & UINT64CONST(0xfffffffefffffffe)) | \20 (((v) >> 31) & UINT64CONST(0x100000001)))21 22 23extern uint32 hash_bytes(const unsigned char *k, int keylen);24extern uint64 hash_bytes_extended(const unsigned char *k,25 int keylen, uint64 seed);26extern uint32 hash_bytes_uint32(uint32 k);27extern uint64 hash_bytes_uint32_extended(uint32 k, uint64 seed);28 29#ifndef FRONTEND30static inline Datum31hash_any(const unsigned char *k, int keylen)32{33 return UInt32GetDatum(hash_bytes(k, keylen));34}35 36static inline Datum37hash_any_extended(const unsigned char *k, int keylen, uint64 seed)38{39 return UInt64GetDatum(hash_bytes_extended(k, keylen, seed));40}41 42static inline Datum43hash_uint32(uint32 k)44{45 return UInt32GetDatum(hash_bytes_uint32(k));46}47 48static inline Datum49hash_uint32_extended(uint32 k, uint64 seed)50{51 return UInt64GetDatum(hash_bytes_uint32_extended(k, seed));52}53#endif54 55extern uint32 string_hash(const void *key, Size keysize);56extern uint32 tag_hash(const void *key, Size keysize);57extern uint32 uint32_hash(const void *key, Size keysize);58 59#define oid_hash uint32_hash /* Remove me eventually */60 61/*62 * Combine two 32-bit hash values, resulting in another hash value, with63 * decent bit mixing.64 *65 * Similar to boost's hash_combine().66 */67static inline uint3268hash_combine(uint32 a, uint32 b)69{70 a ^= b + 0x9e3779b9 + (a << 6) + (a >> 2);71 return a;72}73 74/*75 * Combine two 64-bit hash values, resulting in another hash value, using the76 * same kind of technique as hash_combine(). Testing shows that this also77 * produces good bit mixing.78 */79static inline uint6480hash_combine64(uint64 a, uint64 b)81{82 /* 0x49a0f4dd15e5a8e3 is 64bit random data */83 a ^= b + UINT64CONST(0x49a0f4dd15e5a8e3) + (a << 54) + (a >> 7);84 return a;85}86 87/*88 * Simple inline murmur hash implementation hashing a 32 bit integer, for89 * performance.90 */91static inline uint3292murmurhash32(uint32 data)93{94 uint32 h = data;95 96 h ^= h >> 16;97 h *= 0x85ebca6b;98 h ^= h >> 13;99 h *= 0xc2b2ae35;100 h ^= h >> 16;101 return h;102}103 104#endif /* HASHFN_H */105 