Source file src/cmd/compile/internal/test/issue81887_test.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package test
     6  
     7  import (
     8  	"internal/testenv"
     9  	"os"
    10  	"path/filepath"
    11  	"testing"
    12  )
    13  
    14  // TestBinarySearchFuncInlinable checks that BinarySearchFunc stays within the
    15  // inliner's budget. Inlining it is what lets the calls to cmp be made directly
    16  // instead of through the func value, which is worth considerably more than the
    17  // code it costs: while BinarySearchFunc was over budget, searching with a
    18  // comparison function was substantially slower than the equivalent
    19  // sort.Search.
    20  //
    21  // The check cannot be made by compiling package slices itself, since the body
    22  // of a generic function is only checked for inlinability once instantiated, so
    23  // instantiate it in a package of our own and compile that.
    24  func TestBinarySearchFuncInlinable(t *testing.T) {
    25  	testenv.MustHaveGoBuild(t)
    26  	t.Parallel()
    27  
    28  	dir := t.TempDir()
    29  	src := filepath.Join(dir, "x.go")
    30  	const prog = `package x
    31  
    32  import "slices"
    33  
    34  var _ = slices.BinarySearchFunc[[]string, string, string]
    35  `
    36  	if err := os.WriteFile(src, []byte(prog), 0o644); err != nil {
    37  		t.Fatal(err)
    38  	}
    39  
    40  	cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-gcflags=-m", src)
    41  	cmd.Dir = dir
    42  	out, err := cmd.CombinedOutput()
    43  	if err != nil {
    44  		t.Fatalf("%v: %v\n%s", cmd, err, out)
    45  	}
    46  
    47  	inlCands := collectInlCands(string(out))
    48  	want := "slices.BinarySearchFunc[go.shape.[]string,go.shape.string,go.shape.string]"
    49  	if _, ok := inlCands[want]; !ok {
    50  		t.Errorf("BinarySearchFunc is no longer inlinable: %q not found in compiler output:\n%s", want, out)
    51  	}
    52  }
    53  

View as plain text