mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-03 02:27:48 +00:00
compiler: support compile-time hashmap with int keys
This commit is contained in:
+16
-2
@@ -1016,8 +1016,22 @@ func (c *Compiler) getInterpretedValue(value Value) (llvm.Value, error) {
|
||||
return llvm.Value{}, nil
|
||||
}
|
||||
|
||||
keyString := constant.StringVal(key.(*ConstValue).Expr.Value)
|
||||
hash := stringhash(&keyString)
|
||||
constVal := key.(*ConstValue).Expr
|
||||
var keyBuf []byte
|
||||
switch constVal.Type().Underlying().(*types.Basic).Kind() {
|
||||
case types.String:
|
||||
keyBuf = []byte(constant.StringVal(constVal.Value))
|
||||
case types.Int:
|
||||
keyBuf = make([]byte, c.targetData.TypeAllocSize(c.intType))
|
||||
n, _ := constant.Uint64Val(constVal.Value)
|
||||
for i := range keyBuf {
|
||||
keyBuf[i] = byte(n)
|
||||
n >>= 8
|
||||
}
|
||||
default:
|
||||
return llvm.Value{}, errors.New("todo: init: map key not implemented: " + constVal.Type().Underlying().String())
|
||||
}
|
||||
hash := hashmapHash(keyBuf)
|
||||
|
||||
if i%8 == 0 && i != 0 {
|
||||
// Bucket is full, create a new one.
|
||||
|
||||
@@ -6,10 +6,10 @@ package main
|
||||
// Get FNV-1a hash of this string.
|
||||
//
|
||||
// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash
|
||||
func stringhash(s *string) uint32 {
|
||||
func hashmapHash(data []byte) uint32 {
|
||||
var result uint32 = 2166136261 // FNV offset basis
|
||||
for i := 0; i < len(*s); i++ {
|
||||
result ^= uint32((*s)[i])
|
||||
for _, c := range data {
|
||||
result ^= uint32(c)
|
||||
result *= 16777619 // FNV prime
|
||||
}
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user