github.com/haraldrudell/parl@v0.4.176/pslices/set-length_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  )
    12  
    13  func TestSetLength(t *testing.T) {
    14  	var slice1, expSlice0, slice2 = []int{1}, []int{0}, []int{0, 0}
    15  	var length1, length2 = 1, 2
    16  
    17  	var slice, slice0 []int
    18  
    19  	// extend length from nil
    20  	slice = nil
    21  	SetLength(&slice, 1)
    22  	if !slices.Equal(slice, expSlice0) {
    23  		t.Errorf("SetLength 1 for nil: %v exp%v", slice, expSlice0)
    24  	}
    25  
    26  	// SetLength noop should do nothing to do return
    27  	slice = nil
    28  	SetLength(&slice, 0)
    29  	if slice != nil {
    30  		t.Errorf("SetLength 0 for nil non-nil: %v", slice)
    31  	}
    32  
    33  	// noZero should work
    34  	slice0 = slices.Clone(slice1)
    35  	slice = slice0
    36  	SetLength(&slice, 0, NoZeroOut)
    37  	if !slices.Equal(slice0, slice1) {
    38  		t.Errorf("SetLength 1 for nil: %v exp%v", slice, slice1)
    39  	}
    40  
    41  	// shortening with doZero
    42  	slice0 = slices.Clone(slice1)
    43  	slice = slice0
    44  	// SetLength 0 should zero-out element
    45  	SetLength(&slice, 0)
    46  	if !slices.Equal(slice0, expSlice0) {
    47  		t.Errorf("SetLength 0 for 1-slice: %v exp%v", slice, expSlice0)
    48  	}
    49  
    50  	// extend to cap
    51  	slice0 = slices.Clone(expSlice0)
    52  	slice = slice0[:0]
    53  	SetLength(&slice, length2)
    54  	if !slices.Equal(slice, slice2) {
    55  		t.Errorf("SetLength 2 for 1-cap slice: %v exp%v", slice, slice2)
    56  	}
    57  
    58  	// extend within cap
    59  	slice0 = slices.Clone(slice1)
    60  	slice = slice0[:0]
    61  	SetLength(&slice, length1)
    62  	if !slices.Equal(slice, expSlice0) {
    63  		t.Errorf("SetLength within cap: %v exp%v", slice, expSlice0)
    64  	}
    65  }