summaryrefslogtreecommitdiff
path: root/lib/std/hashfuncs.myr
blob: 3046377deb79a2ad4c86f7adc27d024e7077f151 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use "alloc"
use "chartype"
use "die"
use "sleq"
use "slpush"
use "types"
use "utf"

pkg std =
	const strhash	: (s : byte[:]	-> uint32)
	const streq	: (a : byte[:], b : byte[:]	-> bool)

	const strcasehash	: (s : byte[:]	-> uint32)
	const strcaseeq	: (a : byte[:], b : byte[:]	-> bool)

	generic ptrhash	: (p : @a#	-> uint32)
	generic ptreq	: (a : @a#, b : @a#	-> bool)

	generic inthash	: (v : @a::(integral,numeric)	-> uint32)
	generic inteq	: (a : @a::(integral,numeric), b : @a::(integral,numeric) -> bool)

	const murmurhash2	: (data : byte[:], seed : uint32 -> uint32)

	generic slhash	: (sl : @a[:] -> uint32)
;;

const Seed = 1234

generic slhash = {data : @a[:]
	-> strhash(slbytes(data))
}

generic slbytes = {data : @a[:]
	var n

	n = data.len * sizeof(@a)
	-> (data : byte#)[:n]
}

const strhash = {s
	-> murmurhash2(s, Seed)
}

const strcaseeq = {a, b
	var ca, cb

	while true
		if a.len == 0 || b.len == 0
			break
		;;
		(ca, a) = std.strstep(a)
		(cb, b) = std.strstep(b)
		if std.tolower(ca) != std.tolower(cb)
			-> false
		;;
	;;
	-> a.len == b.len
}

const strcasehash = {s
	var chars
	var c, h

	chars = [][:]
	while s.len != 0
		(c, s) = std.strstep(s)
		std.slpush(&chars, std.tolower(c))
	;;
	h = murmurhash2(slbytes(chars), Seed)
	slfree(chars)
	-> h
}

const streq = {a, b
	-> sleq(a, b)
}

generic ptrhash = {p : @a#
	var x

	x = (&p : byte#)
	-> murmurhash2(x[0:sizeof(@a#)], Seed)
}

generic ptreq = {a, b
	-> a == b
}

generic inthash = {v : @a::(integral,numeric)
	var p

	p = (&v : byte#)
	-> murmurhash2(p[0:sizeof(@a)], Seed)
}

generic inteq = {a, b
	-> a == b
}

const murmurhash2 = {data, seed
	const m = 0x5bd1e995;
	const r = 24
	var h, k
	
	h = seed ^ data.len
	while data.len >= 4
		k = (data[0] : uint32)
		k |= (data[1] : uint32) << 8
		k |= (data[2] : uint32) << 16
		k |= (data[3] : uint32) << 24

		k *= m
		k ^= k >> r
		k *= m

		h *= m
		h ^= k
		data = data[4:]
	;;

	match data.len
	| 3:
		h ^= (data[2] : uint32) << 16
		h ^= (data[1] : uint32) << 8
		h ^= (data[0] : uint32)
		h *= m
	| 2:
		h ^= (data[1] : uint32) << 8
		h ^= (data[0] : uint32)
		h *= m
	| 1:
		h ^= (data[0] : uint32)
		h *= m
	| 0:	/* nothing */
	| _:	die("0 < len < 4 must be true")
	;;

	h ^= h >> 13
	h *= m
	h ^= h >> 15

	-> h
}