1// Copyright 2024 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package uniquelist 16 17import ( 18 "fmt" 19 "slices" 20 "testing" 21) 22 23func ExampleUniqueList() { 24 a := []string{"a", "b", "c", "d"} 25 uniqueA := Make(a) 26 b := slices.Clone(a) 27 uniqueB := Make(b) 28 fmt.Println(uniqueA == uniqueB) 29 fmt.Println(uniqueA.ToSlice()) 30 31 // Output: true 32 // [a b c d] 33} 34 35func testSlice(n int) []int { 36 var slice []int 37 for i := 0; i < n; i++ { 38 slice = append(slice, i) 39 } 40 return slice 41} 42 43func TestUniqueList(t *testing.T) { 44 testCases := []struct { 45 name string 46 in []int 47 }{ 48 { 49 name: "nil", 50 in: nil, 51 }, 52 { 53 name: "zero", 54 in: []int{}, 55 }, 56 { 57 name: "one", 58 in: testSlice(1), 59 }, 60 { 61 name: "nodeSize_minus_one", 62 in: testSlice(nodeSize - 1), 63 }, 64 { 65 name: "nodeSize", 66 in: testSlice(nodeSize), 67 }, 68 { 69 name: "nodeSize_plus_one", 70 in: testSlice(nodeSize + 1), 71 }, 72 { 73 name: "two_times_nodeSize_minus_one", 74 in: testSlice(2*nodeSize - 1), 75 }, 76 { 77 name: "two_times_nodeSize", 78 in: testSlice(2 * nodeSize), 79 }, 80 { 81 name: "two_times_nodeSize_plus_one", 82 in: testSlice(2*nodeSize + 1), 83 }, 84 { 85 name: "large", 86 in: testSlice(1000), 87 }, 88 } 89 90 for _, testCase := range testCases { 91 t.Run(testCase.name, func(t *testing.T) { 92 uniqueList := Make(testCase.in) 93 94 if g, w := uniqueList.ToSlice(), testCase.in; !slices.Equal(g, w) { 95 t.Errorf("incorrect ToSlice()\nwant: %q\ngot: %q", w, g) 96 } 97 98 if g, w := slices.Collect(uniqueList.Iter()), testCase.in; !slices.Equal(g, w) { 99 t.Errorf("incorrect Iter()\nwant: %q\ngot: %q", w, g) 100 } 101 102 if g, w := uniqueList.AppendTo([]int{-1}), append([]int{-1}, testCase.in...); !slices.Equal(g, w) { 103 t.Errorf("incorrect Iter()\nwant: %q\ngot: %q", w, g) 104 } 105 106 if g, w := uniqueList.Len(), len(testCase.in); g != w { 107 t.Errorf("incorrect Len(), want %v, got %v", w, g) 108 } 109 }) 110 } 111} 112