github.com/haraldrudell/parl@v0.4.176/pslices/shifter_test.go (about)

     1  /*
     2  © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pslices
     7  
     8  import (
     9  	"slices"
    10  	"testing"
    11  	"unsafe"
    12  )
    13  
    14  func TestShifter(t *testing.T) {
    15  	// the slice for all subsequent slices
    16  	var slice0 = []int{1, 2}
    17  	// index to use for slicing away at the beginning
    18  	var sliceAwayIndex = 1
    19  	// items to append
    20  	var items = []int{3}
    21  	// expected resulting slice
    22  	var sliceExp = []int{2, 3}
    23  
    24  	// Append()
    25  	var shifter *Shifter[int] = NewShifter(slice0)
    26  
    27  	shifter.Slice = shifter.Slice[sliceAwayIndex:]
    28  	shifter.Append(items...)
    29  
    30  	// resulting slice should match
    31  	if !slices.Equal(shifter.Slice, sliceExp) {
    32  		t.Errorf("Append %v exp %v", shifter.Slice, sliceExp)
    33  	}
    34  
    35  	// slice should not have been re-allocated
    36  	var shifterp = int(uintptr(unsafe.Pointer(&shifter.Slice[0])))
    37  	var slicep = int(uintptr(unsafe.Pointer(&slice0[0])))
    38  	if shifterp != slicep {
    39  		t.Errorf("shifterp\n0x%x exp\n0x%x", shifterp, slicep)
    40  	}
    41  }
    42  
    43  func TestShifterZeroFill(t *testing.T) {
    44  	// the initial slice for all subsequent slices
    45  	var slice0 = []int{1, 2, 3}
    46  	// index to use for slice away at the beginning
    47  	var sliceAway = 2
    48  	// items to append
    49  	var items = []int{4}
    50  	// expected slice result
    51  	var sliceExp = []int{3, 4}
    52  	// index in slice0 where zero-fill should have taken place
    53  	var zeroFillIndex = 2
    54  
    55  	var zeroValue int
    56  
    57  	// Append()
    58  	var shifter *Shifter[int] = NewShifter(slice0, ZeroFillingShifter)
    59  
    60  	// slice away at beginning
    61  	shifter.Slice = shifter.Slice[sliceAway:]
    62  	// append at end
    63  	shifter.Append(items...)
    64  
    65  	// slice result should match
    66  	if !slices.Equal(shifter.Slice, sliceExp) {
    67  		t.Errorf("Append %v exp %v", shifter.Slice, sliceExp)
    68  	}
    69  
    70  	// slice should not have been reallocated
    71  	var shifterp = int(uintptr(unsafe.Pointer(&shifter.Slice[0])))
    72  	var slicep = int(uintptr(unsafe.Pointer(&slice0[0])))
    73  	if shifterp != slicep {
    74  		t.Errorf("shifterp\n0x%x exp\n0x%x", shifterp, slicep)
    75  	}
    76  
    77  	// slice element should have been zero-filled
    78  	if slice0[zeroFillIndex] != zeroValue {
    79  		t.Error("zero-fill failed")
    80  	}
    81  }