github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/unsafekit/slice_test.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package unsafekit
     7  
     8  import (
     9  	"reflect"
    10  	"runtime"
    11  	"testing"
    12  
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestUnwrapAsSlice(t *testing.T) {
    17  	if BigEndian {
    18  		t.SkipNow()
    19  	}
    20  
    21  	bytes := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    22  
    23  	s := WrapBytes(bytes)
    24  	st := MustMMapSliceType(reflect.TypeOf([]uint32(nil)), false)
    25  	slice := UnwrapAsSliceOf(s, st).([]uint32)
    26  	require.Equal(t, []uint32{0x03020100, 0x07060504, 0x0B0A0908}, slice)
    27  	bytes[0] = 0xFF
    28  	bytes[11] = 0xEE
    29  	require.Equal(t, []uint32{0x030201FF, 0x07060504, 0xEE0A0908}, slice)
    30  
    31  	runtime.KeepAlive(bytes)
    32  }
    33  
    34  func TestUnwrapEmptyAsSlice(t *testing.T) {
    35  	st := MustMMapSliceType(reflect.TypeOf([]struct{}{}), false)
    36  	slice := make([]struct{}, 10)
    37  
    38  	wrapped := WrapSliceOf(slice, st)
    39  	unwrapped := UnwrapAsSliceOf(wrapped, st).([]struct{})
    40  	require.Equal(t, 0, len(unwrapped))
    41  
    42  	slice = make([]struct{}, 0, 1)
    43  	wrapped = WrapSliceOf(slice, st)
    44  	unwrapped = UnwrapAsSliceOf(wrapped, st).([]struct{})
    45  	require.Equal(t, 0, len(unwrapped))
    46  
    47  	slice = nil
    48  	wrapped = WrapSliceOf(slice, st)
    49  	unwrapped = UnwrapAsSliceOf(wrapped, st).([]struct{})
    50  	require.Equal(t, 0, len(unwrapped))
    51  }