Skip to content

Commit 0873615

Browse files
committed
add documentation on how hashing works
1 parent 845a010 commit 0873615

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/go/token/token.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,11 +290,25 @@ func init() {
290290
// keywordsIndex maps an identifier to an index in keywords array.
291291
func keywordsIndex(maybeKeyword string) uint8 {
292292
if len(maybeKeyword) <= 3 {
293+
// If adding a 2 or 3 letter keyword that starts with `i`(if),`f`(for) or `g`(go)
294+
// you'd need to add logic to this if statement to differentiate between them.
293295
if len(maybeKeyword) == 0 {
294296
return 0
295297
}
296298
return maybeKeyword[0]
297299
}
300+
// This hash was adjusted by hand. Finding the working combinations
301+
// for this hash is quite straightforward, even when restricting all
302+
// operations to power-of-two multiplications and addition/subtractions
303+
// for performance reasons since multiplication of an integer by a power-of-two
304+
// can be optimized to a bitshift which is faster on some architectures.
305+
//
306+
// Here is a list of hashes that also works for current keyword set:
307+
// h = v0 + v1*2 + v2*4 + v3*8
308+
// h = v0 + v1*4 + v2*8 + v3
309+
// h = v0 + v1*2 + (v2+v3)*2
310+
// h = v0*4 + v1*2 + v2*2 + v3*2
311+
// h = v0*4 + v1*2 + v2*v3
298312
v0 := maybeKeyword[0]
299313
v1 := maybeKeyword[1]
300314
v2 := maybeKeyword[2]

0 commit comments

Comments
 (0)