Skip to content

Commit 504c82a

Browse files
kyegupovaykevl
authored andcommitted
compiler: support for byte arrays as keys in maps
1 parent f8a1e5f commit 504c82a

File tree

4 files changed

+25
-0
lines changed

4 files changed

+25
-0
lines changed

compiler/map.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,10 @@ func hashmapIsBinaryKey(keyType types.Type) bool {
120120
}
121121
}
122122
return true
123+
case *types.Array:
124+
return hashmapIsBinaryKey(keyType.Elem())
125+
case *types.Named:
126+
return hashmapIsBinaryKey(keyType.Underlying())
123127
default:
124128
return false
125129
}

interp/values.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,13 @@ func (v *MapValue) Value() llvm.Value {
451451
keyBuf[i] = byte(n)
452452
n >>= 8
453453
}
454+
} else if key.Type().TypeKind() == llvm.ArrayTypeKind &&
455+
key.Type().ElementType().TypeKind() == llvm.IntegerTypeKind &&
456+
key.Type().ElementType().IntTypeWidth() == 8 {
457+
keyBuf = make([]byte, v.Eval.TargetData.TypeAllocSize(key.Type()))
458+
for i := range keyBuf {
459+
keyBuf[i] = byte(llvm.ConstExtractValue(llvmKey, []uint32{uint32(i)}).ZExtValue())
460+
}
454461
} else {
455462
panic("interp: map key type not implemented: " + key.Type().String())
456463
}

testdata/map.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ var testmap2 = map[string]int{
1515
"eleven": 11,
1616
"twelve": 12,
1717
}
18+
19+
type ArrayKey [4]byte
20+
21+
var testMapArrayKey = map[ArrayKey]int{
22+
ArrayKey([4]byte{1, 2, 3, 4}): 1234,
23+
ArrayKey([4]byte{4, 3, 2, 1}): 4321,
24+
}
1825
var testmapIntInt = map[int]int{1: 1, 2: 4, 3: 9}
1926

2027
func main() {
@@ -35,6 +42,11 @@ func main() {
3542
println(testmapIntInt[2])
3643
testmapIntInt[2] = 42
3744
println(testmapIntInt[2])
45+
46+
arrKey := ArrayKey([4]byte{4, 3, 2, 1})
47+
println(testMapArrayKey[arrKey])
48+
testMapArrayKey[arrKey] = 5555
49+
println(testMapArrayKey[arrKey])
3850
}
3951

4052
func readMap(m map[string]int, key string) {

testdata/map.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,5 @@ false true 2
5252
true false 0
5353
4
5454
42
55+
4321
56+
5555

0 commit comments

Comments
 (0)