Source file src/simd/archsimd/internal/simd_test/layout_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  //go:build goexperiment.simdstable && (amd64 || wasm || arm64)
     6  
     7  package simd_test
     8  
     9  import (
    10  	"reflect"
    11  	"simd/archsimd"
    12  	"testing"
    13  	"unsafe"
    14  )
    15  
    16  // TestLayout checks that the type checker, which computes unsafe.Sizeof,
    17  // Alignof and Offsetof, agrees with the compiler, which lays out the types and
    18  // reports their layout to reflect.
    19  func TestLayout(t *testing.T) {
    20  	type S struct {
    21  		a int32
    22  		v archsimd.Float32x4
    23  		b int8
    24  		m archsimd.Mask8x16
    25  	}
    26  	var s S
    27  	checkLayout(t, unsafe.Sizeof(s), unsafe.Alignof(s),
    28  		[]uintptr{unsafe.Offsetof(s.a), unsafe.Offsetof(s.v), unsafe.Offsetof(s.b), unsafe.Offsetof(s.m)},
    29  		reflect.TypeFor[S]())
    30  }
    31  
    32  // checkLayout checks that a struct type's size, alignment and field offsets
    33  // agree with what reflect reports for it.
    34  func checkLayout(t *testing.T, size, align uintptr, offsets []uintptr, rt reflect.Type) {
    35  	t.Helper()
    36  	if size != rt.Size() || align != uintptr(rt.Align()) {
    37  		t.Errorf("%v: unsafe size %d align %d, reflect size %d align %d", rt, size, align, rt.Size(), rt.Align())
    38  	}
    39  	for i, off := range offsets {
    40  		if f := rt.Field(i); off != f.Offset {
    41  			t.Errorf("%v.%s: unsafe offset %d, reflect offset %d", rt, f.Name, off, f.Offset)
    42  		}
    43  	}
    44  }
    45  

View as plain text