The hash module provides common hash functions implemented in pure Conjure. These are useful for hash tables, checksums, and data integrity checks.
import "conjure/hash"String Hashing
hashString
Computes a 32-bit FNV-1a hash of a string. This is the primary hash function and should be used for most hashing needs.
var h = hash.hashString("hello")
io.println("Hash: #{h}")Signature:
func hashString(s string) u32The FNV-1a algorithm provides good distribution and is fast for typical string lengths.
hashString64
Computes a 64-bit FNV-1a hash of a string. Use this when you need better distribution for larger hash tables or when collisions are particularly costly.
var h = hash.hashString64("hello world")Signature:
func hashString64(s string) u64Combining Hashes
combineHashes
Combines two 32-bit hash values into one. Useful for hashing composite data structures where you need to combine hashes of multiple fields.
struct Point {
x i32
y i32
}
func hashPoint(p Point) u32 {
var hx = hash.hashString("#{p.x}")
var hy = hash.hashString("#{p.y}")
return hash.combineHashes(hx, hy)
}Signature:
func combineHashes(h1 u32, h2 u32) u32combineHashes64
Combines two 64-bit hash values into one.
var h1 = hash.hashString64("key")
var h2 = hash.hashString64("value")
var combined = hash.combineHashes64(h1, h2)Signature:
func combineHashes64(h1 u64, h2 u64) u64Example: Simple Hash Map Bucket
import "conjure/hash"
const BUCKET_COUNT = 256
func getBucket(key string) u32 {
return hash.hashString(key) % BUCKET_COUNT
}Example: Hashing a Struct
import "conjure/hash"
struct User {
id i32
name string
email string
}
func hashUser(u User) u32 {
var h1 = hash.hashString("#{u.id}")
var h2 = hash.hashString(u.name)
var h3 = hash.hashString(u.email)
var combined = hash.combineHashes(h1, h2)
return hash.combineHashes(combined, h3)
}Hash Quality
The FNV-1a algorithm used by this module provides:
- Good distribution for typical inputs
- Fast computation
- Low collision rates for hash tables
For cryptographic purposes (password hashing, digital signatures), use a cryptographic hash function instead. The hashes in this module are designed for speed and distribution, not security.