Debian Codegraph @

internal/encoder/vm_jump_table_test.go

raw
1 package encoder_test
2
3 import (
4 "os/exec"
5 "regexp"
6 "runtime"
7 "strings"
8 "testing"
9 )
10
11 // The switch of Run of every VM must be compiled to a jump table: the opcode is dispatched by one indirect
12 // jump, which is what makes the switch faster than a call per opcode. The compiler does it for an integer switch
13 // of at least 8 cases whose values are dense, so it holds as long as the opcodes are numbered without gaps.
14 func TestVMDispatchIsJumpTable(t *testing.T) {
15 if _, err := exec.LookPath("go"); err != nil {
16 t.Skip("the go command is not found")
17 }
18 if runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
19 t.Skipf("the compiler doesn't use a jump table on %s", runtime.GOARCH)
20 }
21 for _, vm := range []string{"vm", "vm_indent", "vm_color", "vm_color_indent"} {
22 t.Run(vm, func(t *testing.T) {
23 cmd := exec.Command("go", "build", "-gcflags=-S", "github.com/goccy/go-json/internal/encoder/"+vm)
24 out, err := cmd.CombinedOutput()
25 if err != nil {
26 t.Fatalf("go build: %v\n%s", err, out)
27 }
28 text := string(out)
29 i := strings.Index(text, vm+".Run STEXT")
30 if i < 0 {
31 t.Fatal("the code of Run is not found")
32 }
33 run := text[i:]
34 if j := strings.Index(run[20:], " STEXT "); j >= 0 {
35 run = run[:20+j]
36 }
37 if !regexp.MustCompile(`Run\.jump\d+`).MatchString(run) {
38 t.Fatal("the switch of Run is not compiled to a jump table")
39 }
40 })
41 }
42 }