1 // Code created by gotmpl. DO NOT MODIFY. 2 // source: internal/shared/internaltest/alignment.go.tmpl 3 4 // Copyright The OpenTelemetry Authors 5 // 6 // Licensed under the Apache License, Version 2.0 (the "License"); 7 // you may not use this file except in compliance with the License. 8 // You may obtain a copy of the License at 9 // 10 // http://www.apache.org/licenses/LICENSE-2.0 11 // 12 // Unless required by applicable law or agreed to in writing, software 13 // distributed under the License is distributed on an "AS IS" BASIS, 14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 // See the License for the specific language governing permissions and 16 // limitations under the License. 17 18 package internaltest // import "go.opentelemetry.io/otel/sdk/internal/internaltest" 19 20 /* 21 This file contains common utilities and objects to validate memory alignment 22 of Go types. The primary use of this functionality is intended to ensure 23 `struct` fields that need to be 64-bit aligned so they can be passed as 24 arguments to 64-bit atomic operations. 25 26 The common workflow is to define a slice of `FieldOffset` and pass them to the 27 `Aligned8Byte` function from within a `TestMain` function from a package's 28 tests. It is important to make this call from the `TestMain` function prior 29 to running the rest of the test suit as it can provide useful diagnostics 30 about field alignment instead of ambiguous nil pointer dereference and runtime 31 panic. 32 33 For more information: 34 https://github.com/open-telemetry/opentelemetry-go/issues/341 35 */ 36 37 import ( 38 "fmt" 39 "io" 40 ) 41 42 // FieldOffset is a preprocessor representation of a struct field alignment. 43 type FieldOffset struct { 44 // Name of the field. 45 Name string 46 47 // Offset of the field in bytes. 48 // 49 // To compute this at compile time use unsafe.Offsetof. 50 Offset uintptr 51 } 52 53 // Aligned8Byte returns if all fields are aligned modulo 8-bytes. 54 // 55 // Error messaging is printed to out for any field determined misaligned. 56 func Aligned8Byte(fields []FieldOffset, out io.Writer) bool { 57 misaligned := make([]FieldOffset, 0) 58 for _, f := range fields { 59 if f.Offset%8 != 0 { 60 misaligned = append(misaligned, f) 61 } 62 } 63 64 if len(misaligned) == 0 { 65 return true 66 } 67 68 fmt.Fprintln(out, "struct fields not aligned for 64-bit atomic operations:") 69 for _, f := range misaligned { 70 fmt.Fprintf(out, " %s: %d-byte offset\n", f.Name, f.Offset) 71 } 72 73 return false 74 } 75