Source file src/simd/internal/test_helpers/equal.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  //go:build goexperiment.simdstable
     6  
     7  package test_helpers
     8  
     9  import (
    10  	"fmt"
    11  	"math/rand/v2"
    12  	"reflect"
    13  	"slices"
    14  	"testing"
    15  )
    16  
    17  // == and != on vectors compare them as if they were structs with one field per
    18  // element, and on masks as if they were structs with one bool per element.
    19  
    20  // EqVector is a vector type T that can be compared element-wise with another T
    21  // to produce a mask of type M.
    22  type EqVector[T any, M EqMask] interface {
    23  	comparable
    24  	Equal(T) M
    25  	Len() int
    26  }
    27  
    28  // EqMask is a mask type, returned by Vec.Equal(Vec).
    29  type EqMask interface {
    30  	comparable
    31  	All() bool
    32  }
    33  
    34  // CheckVectorEqual checks == and != on vectors of type T against comparing
    35  // their elements one at a time, for many pairs of vectors loaded from values.
    36  //
    37  // eq and ne must be x == y and x != y, written for the concrete type T, so that
    38  // they test the compiler's direct lowering of ==. CheckVectorEqual also tests
    39  // == in generic code, on structs and arrays containing vectors, on interfaces,
    40  // through reflect, and on map keys.
    41  func CheckVectorEqual[T EqVector[T, M], M EqMask, E number](t *testing.T, load func([]E) T, eq, ne func(x, y T) bool, values []E) {
    42  	t.Helper()
    43  	values = distinct(values)
    44  	var zero T
    45  	a, b := make([]E, zero.Len()), make([]E, zero.Len())
    46  
    47  	check := func(a, b []E) {
    48  		t.Helper()
    49  		x, y := load(a), load(b)
    50  		want := slices.Equal(a, b)
    51  		if got := eq(x, y); got != want {
    52  			t.Fatalf("%v == %v is %v, want %v", a, b, got, want)
    53  		}
    54  		if got := ne(x, y); got == want {
    55  			t.Fatalf("%v != %v is %v, want %v", a, b, got, !want)
    56  		}
    57  		if got := x.Equal(y).All(); got != want {
    58  			t.Fatalf("%v.Equal(%v).All() is %v, want %v", a, b, got, want)
    59  		}
    60  		checkEqualForms(t, x, y, want, func() string { return fmt.Sprintf("%v and %v", a, b) })
    61  	}
    62  
    63  	// Starting from several random vectors a, compare a to itself, and to
    64  	// each vector that differs from it in one element, setting that element
    65  	// to each of the values in turn.
    66  	r := rand.New(rand.NewPCG(1, 2))
    67  	for range 10 {
    68  		pickN(r, a, values)
    69  		copy(b, a)
    70  		check(a, b)
    71  		for i := range b {
    72  			for _, v := range values {
    73  				b[i] = v
    74  				check(a, b)
    75  			}
    76  			b[i] = a[i]
    77  		}
    78  	}
    79  
    80  	// Check that random vectors work as map keys.
    81  	for range 20 {
    82  		pickN(r, a, values)
    83  		x := load(a)
    84  		m := map[T]int{x: 1}
    85  		m[load(a)]++
    86  		// x == x is false exactly when x has a NaN element. Like a NaN key
    87  		// in a map of floats, such a vector is a new key every time it's
    88  		// stored, and can never be found.
    89  		if x == x {
    90  			if len(m) != 1 || m[x] != 2 {
    91  				t.Fatalf("map keyed by %v twice is %v, want one key with value 2", a, m)
    92  			}
    93  		} else {
    94  			if len(m) != 2 {
    95  				t.Fatalf("map keyed by %v (which has a NaN) twice has %d keys, want 2", a, len(m))
    96  			}
    97  			if _, ok := m[x]; ok {
    98  				t.Fatalf("found key %v, which has a NaN, in map", a)
    99  			}
   100  		}
   101  	}
   102  
   103  	if !reflect.TypeFor[T]().Comparable() {
   104  		t.Errorf("reflect reports %T as not comparable", zero)
   105  	}
   106  }
   107  
   108  // CheckMaskEqual checks == and != on masks of type M against comparing their
   109  // elements one at a time. It makes each mask by using load to make a vector of
   110  // type T whose elements are zero where the mask should be true, and comparing
   111  // that vector to zero.
   112  //
   113  // eq and ne must be x == y and x != y, written for the concrete type M, so that
   114  // they test the compiler's direct lowering of ==. CheckMaskEqual also tests ==
   115  // in generic code, on structs and arrays containing masks, on interfaces,
   116  // through reflect, and on map keys.
   117  func CheckMaskEqual[T EqVector[T, M], M EqMask, E number](t *testing.T, load func([]E) T, eq, ne func(x, y M) bool) {
   118  	t.Helper()
   119  	var zeroVec T
   120  	n := zeroVec.Len()
   121  	a, b, zeros := make([]bool, n), make([]bool, n), load(make([]E, n))
   122  	toMask := func(s []bool) M {
   123  		v := make([]E, n)
   124  		for i, b := range s {
   125  			if !b {
   126  				v[i] = 1
   127  			}
   128  		}
   129  		return load(v).Equal(zeros)
   130  	}
   131  
   132  	check := func(a, b []bool) {
   133  		t.Helper()
   134  		x, y := toMask(a), toMask(b)
   135  		want := slices.Equal(a, b)
   136  		if got := eq(x, y); got != want {
   137  			t.Fatalf("mask %v == %v is %v, want %v", a, b, got, want)
   138  		}
   139  		if got := ne(x, y); got == want {
   140  			t.Fatalf("mask %v != %v is %v, want %v", a, b, got, !want)
   141  		}
   142  		checkEqualForms(t, x, y, want, func() string { return fmt.Sprintf("masks %v and %v", a, b) })
   143  	}
   144  
   145  	// Starting from several random masks a, compare a to itself, and to
   146  	// every mask that differs from it in one element.
   147  	r := rand.New(rand.NewPCG(1, 2))
   148  	for range 10 {
   149  		pickN(r, a, []bool{false, true})
   150  		copy(b, a)
   151  		check(a, b)
   152  		for i := range b {
   153  			b[i] = !b[i]
   154  			check(a, b)
   155  			b[i] = a[i]
   156  		}
   157  	}
   158  
   159  	// Check that random masks work as map keys.
   160  	for range 20 {
   161  		pickN(r, a, []bool{false, true})
   162  		m := map[M]int{toMask(a): 1}
   163  		m[toMask(a)]++
   164  		if len(m) != 1 || m[toMask(a)] != 2 {
   165  			t.Fatalf("map keyed by mask %v twice is %v, want one key with value 2", a, m)
   166  		}
   167  	}
   168  
   169  	if !reflect.TypeFor[M]().Comparable() {
   170  		t.Errorf("reflect reports %T as not comparable", zeroVec.Equal(zeroVec))
   171  	}
   172  }
   173  
   174  // checkEqualForms checks that the forms of == other than a direct comparison of
   175  // two values of a concrete vector or mask type report want for x and y. desc
   176  // describes x and y for failure messages.
   177  //
   178  // Since V is a type parameter, x == y here tests == in generic code. Which of
   179  // these comparisons the compiler lowers directly and which call V's generated
   180  // equality function depends on how it stencils generic code and on how it
   181  // compares structs and arrays. Currently, generic code is stenciled for V's
   182  // shape, which is V's SIMD struct type, so x == y and the struct comparison are
   183  // lowered directly, while the array comparison, interfaces and reflect call an
   184  // equality function.
   185  func checkEqualForms[V comparable](t *testing.T, x, y V, want bool, desc func() string) {
   186  	t.Helper()
   187  	if got := x == y; got != want {
   188  		t.Fatalf("generic == on %s is %v, want %v", desc(), got, want)
   189  	}
   190  	if got := any(x) == any(y); got != want {
   191  		t.Fatalf("== on %s as interfaces is %v, want %v", desc(), got, want)
   192  	}
   193  	if got := (struct {
   194  		v V
   195  		n int
   196  	}{x, 1} == struct {
   197  		v V
   198  		n int
   199  	}{y, 1}); got != want {
   200  		t.Fatalf("== on structs containing %s is %v, want %v", desc(), got, want)
   201  	}
   202  	if got := [2]V{x, x} == [2]V{x, y}; got != want {
   203  		t.Fatalf("== on arrays containing %s is %v, want %v", desc(), got, want)
   204  	}
   205  	if got := reflect.ValueOf(x).Equal(reflect.ValueOf(y)); got != want {
   206  		t.Fatalf("reflect.Value.Equal on %s is %v, want %v", desc(), got, want)
   207  	}
   208  	if !reflect.ValueOf(x).Comparable() {
   209  		t.Fatalf("reflect.Value.Comparable on %s is false", desc())
   210  	}
   211  }
   212  
   213  // pickN sets each element of out to a random element of options.
   214  func pickN[E any](r *rand.Rand, out, options []E) {
   215  	for i := range out {
   216  		out[i] = options[r.IntN(len(options))]
   217  	}
   218  }
   219  
   220  // distinct returns values without repeats, in order. It treats all NaNs as the
   221  // same, since they all compare the same way, but keeps +0 and -0 apart.
   222  func distinct[E number](values []E) []E {
   223  	same := func(x, y E) bool {
   224  		// The same test CheckSlicesLogInput uses with no flakiness.
   225  		if x != y {
   226  			return isSameFloat(x, y, 0)
   227  		}
   228  		return !isDifferentSignZero(x, y)
   229  	}
   230  	var out []E
   231  	for _, v := range values {
   232  		if !slices.ContainsFunc(out, func(w E) bool { return same(v, w) }) {
   233  			out = append(out, v)
   234  		}
   235  	}
   236  	return out
   237  }
   238  

View as plain text