github.com/alexflint/go-memdump@v1.1.0/alignment_test.go (about)

     1  package memdump
     2  
     3  import (
     4  	"bytes"
     5  	"reflect"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  type byteAndInt struct {
    13  	b *byte // should be aligned to a 1-byte boundary
    14  	i *int  // should be aligned to an 8-byte boundary
    15  }
    16  
    17  func newByte(b byte) *byte {
    18  	return &b
    19  }
    20  
    21  func newInt(i int) *int {
    22  	return &i
    23  }
    24  
    25  func assertAligned(t *testing.T, v reflect.Value) {
    26  	addr := v.UnsafeAddr()
    27  
    28  	assert.Zero(t, addr%uintptr(v.Type().Align()),
    29  		"alignment of %v was off by %d", v.Type(), addr%uintptr(v.Type().Align()))
    30  }
    31  
    32  func TestAlignment(t *testing.T) {
    33  	in := byteAndInt{
    34  		b: newByte(3),
    35  		i: newInt(4),
    36  	}
    37  
    38  	var buf bytes.Buffer
    39  	err := Encode(&buf, &in)
    40  	require.NoError(t, err)
    41  
    42  	var out *byteAndInt
    43  	err = Decode(&buf, &out)
    44  	require.NoError(t, err)
    45  
    46  	assertAligned(t, reflect.ValueOf(out.b).Elem())
    47  	assertAligned(t, reflect.ValueOf(out.i).Elem())
    48  }