github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/tests/slice_test.go (about)

     1  // Package test provides tests for common low-level types and utilities for all aistore projects
     2  /*
     3   * Copyright (c) 2018-2024, NVIDIA CORPORATION. All rights reserved.
     4   */
     5  package tests_test
     6  
     7  import (
     8  	"strconv"
     9  	"testing"
    10  
    11  	"github.com/NVIDIA/aistore/cmn"
    12  	"github.com/NVIDIA/aistore/tools/tassert"
    13  )
    14  
    15  type discardEntriesTestCase struct {
    16  	entries cmn.LsoEntries
    17  	size    int
    18  }
    19  
    20  func generateEntries(size int) cmn.LsoEntries {
    21  	result := make(cmn.LsoEntries, 0, size)
    22  	for i := range size {
    23  		result = append(result, &cmn.LsoEnt{Name: strconv.Itoa(i)})
    24  	}
    25  	return result
    26  }
    27  
    28  func TestDiscardFirstEntries(t *testing.T) {
    29  	testCases := []discardEntriesTestCase{
    30  		{generateEntries(100), 1},
    31  		{generateEntries(1), 1},
    32  		{generateEntries(100), 0},
    33  		{generateEntries(1), 0},
    34  		{generateEntries(100), 50},
    35  		{generateEntries(1), 50},
    36  		{generateEntries(100), 100},
    37  		{generateEntries(100), 150},
    38  	}
    39  
    40  	for _, tc := range testCases {
    41  		t.Logf("testcase %d/%d", len(tc.entries), tc.size)
    42  		original := append(cmn.LsoEntries(nil), tc.entries...)
    43  		entries := discardFirstEntries(tc.entries, tc.size)
    44  		expSize := max(0, len(original)-tc.size)
    45  		tassert.Errorf(t, len(entries) == expSize, "incorrect size. expected %d; got %d", expSize, len(entries))
    46  		if len(entries) > 0 {
    47  			tassert.Errorf(t, entries[0] == original[tc.size],
    48  				"incorrect elements. expected %s, got %s", entries[0].Name, original[tc.size].Name)
    49  		}
    50  	}
    51  }
    52  
    53  func discardFirstEntries(entries cmn.LsoEntries, n int) cmn.LsoEntries {
    54  	if n == 0 {
    55  		return entries
    56  	}
    57  	if n >= len(entries) {
    58  		return entries[:0]
    59  	}
    60  
    61  	toDiscard := min(len(entries), n)
    62  
    63  	copy(entries, entries[toDiscard:])
    64  	for i := len(entries) - toDiscard; i < len(entries); i++ {
    65  		entries[i] = nil
    66  	}
    67  
    68  	return entries[:len(entries)-toDiscard]
    69  }