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

     1  // Copyright 2024 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  	"reflect"
     9  	"testing"
    10  )
    11  
    12  //go:noinline
    13  func foo() string { return "foo" }
    14  
    15  //go:noinline
    16  func empty() string { return "" }
    17  
    18  func TestConcatBytes(t *testing.T) {
    19  	empty := empty()
    20  	s := foo()
    21  	tests := map[string]struct {
    22  		got  []byte
    23  		want []byte
    24  	}{
    25  		"two empty elements":                 {got: []byte(empty + empty), want: []byte{}},
    26  		"two nonempty elements":              {got: []byte(s + s), want: []byte("foofoo")},
    27  		"one empty and one nonempty element": {got: []byte(s + empty), want: []byte("foo")},
    28  		"multiple empty elements":            {got: []byte(empty + empty + empty + empty + empty + empty), want: []byte{}},
    29  		"multiple nonempty elements":         {got: []byte("1" + "2" + "3" + "4" + "5" + "6"), want: []byte("123456")},
    30  	}
    31  
    32  	for name, test := range tests {
    33  		if !reflect.DeepEqual(test.got, test.want) {
    34  			t.Errorf("[%s] got: %s, want: %s", name, test.got, test.want)
    35  		}
    36  	}
    37  }
    38  
    39  func TestConcatBytesAllocations(t *testing.T) {
    40  	empty := empty()
    41  	s := foo()
    42  	tests := map[string]struct {
    43  		f      func() []byte
    44  		allocs float64
    45  	}{
    46  		"two empty elements":      {f: func() []byte { return []byte(empty + empty) }, allocs: 0},
    47  		"multiple empty elements": {f: func() []byte { return []byte(empty + empty + empty + empty + empty + empty) }, allocs: 0},
    48  
    49  		"two elements":                       {f: func() []byte { return []byte(s + s) }, allocs: 1},
    50  		"three elements":                     {f: func() []byte { return []byte(s + s + s) }, allocs: 1},
    51  		"four elements":                      {f: func() []byte { return []byte(s + s + s + s) }, allocs: 1},
    52  		"five elements":                      {f: func() []byte { return []byte(s + s + s + s + s) }, allocs: 1},
    53  		"one empty and one nonempty element": {f: func() []byte { return []byte(s + empty) }, allocs: 1},
    54  		"two empty and two nonempty element": {f: func() []byte { return []byte(s + empty + s + empty) }, allocs: 1},
    55  	}
    56  	for name, test := range tests {
    57  		allocs := testing.AllocsPerRun(100, func() { test.f() })
    58  		if allocs != test.allocs {
    59  			t.Errorf("concatbytes [%s]: %v allocs, want %v", name, allocs, test.allocs)
    60  		}
    61  	}
    62  }
    63  

View as plain text