github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/dedupedslice_test.go (about) 1 // Copyright 2023 LiveKit, Inc. 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 15 package utils 16 17 import ( 18 "testing" 19 20 "github.com/stretchr/testify/require" 21 ) 22 23 func TestDedupedSlice(t *testing.T) { 24 t.Run("no_overflow", func(t *testing.T) { 25 dsInt := NewDedupedSlice[int](10) 26 for idx, v := range []int{1, 2, 3, 4, 6, 4, 7} { 27 if idx == 5 { 28 require.False(t, dsInt.Add(v)) 29 } else { 30 require.True(t, dsInt.Add(v)) 31 } 32 } 33 require.EqualValues(t, []int{1, 2, 3, 4, 6, 7}, dsInt.Get()) 34 require.Equal(t, 6, dsInt.Len()) 35 require.True(t, dsInt.Has(2)) 36 require.False(t, dsInt.Has(8)) 37 38 dsString := NewDedupedSlice[string](10) 39 for idx, v := range []string{"one", "two", "ten", "six", "six", "four"} { 40 if idx == 4 { 41 require.False(t, dsString.Add(v)) 42 } else { 43 require.True(t, dsString.Add(v)) 44 } 45 } 46 require.EqualValues(t, []string{"one", "two", "ten", "six", "four"}, dsString.Get()) 47 require.NotEqualValues(t, []string{"one", "two", "ten", "six", "six", "four"}, dsString.Get()) 48 require.Equal(t, 5, dsString.Len()) 49 require.True(t, dsString.Has("two")) 50 require.False(t, dsString.Has("eight")) 51 52 dsString.Clear() 53 require.Nil(t, dsString.Get()) 54 require.Equal(t, 0, dsString.Len()) 55 }) 56 57 t.Run("max_len", func(t *testing.T) { 58 dsInt := NewDedupedSlice[int](5) 59 for _, v := range []int{1, 2, 3, 4, 6, 4, 7} { 60 dsInt.Add(v) 61 } 62 require.EqualValues(t, []int{2, 3, 4, 6, 7}, dsInt.Get()) 63 require.Equal(t, 5, dsInt.Len()) 64 require.True(t, dsInt.Has(2)) 65 require.False(t, dsInt.Has(1)) 66 }) 67 }