github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/spanz/hash_map_test.go (about) 1 // Copyright 2022 PingCAP, 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package spanz 15 16 import ( 17 "testing" 18 19 "github.com/pingcap/tiflow/cdc/processor/tablepb" 20 "github.com/stretchr/testify/require" 21 ) 22 23 func TestHashMap(t *testing.T) { 24 t.Parallel() 25 26 m := NewHashMap[int]() 27 28 // Insert then get. 29 m.ReplaceOrInsert(tablepb.Span{TableID: 1}, 1) 30 v, ok := m.Get(tablepb.Span{TableID: 1}) 31 require.Equal(t, v, 1) 32 require.True(t, ok) 33 require.Equal(t, 1, m.Len()) 34 require.True(t, m.Has(tablepb.Span{TableID: 1})) 35 36 // Insert then get again. 37 m.ReplaceOrInsert(tablepb.Span{TableID: 1, StartKey: []byte{1}}, 2) 38 require.Equal(t, 2, m.Len()) 39 v, ok = m.Get(tablepb.Span{TableID: 1, StartKey: []byte{1}}) 40 require.Equal(t, v, 2) 41 require.True(t, ok) 42 43 // Overwrite then get. 44 m.ReplaceOrInsert( 45 tablepb.Span{TableID: 1, StartKey: []byte{1}}, 3) 46 require.Equal(t, 2, m.Len()) 47 require.True(t, m.Has(tablepb.Span{TableID: 1, StartKey: []byte{1}})) 48 v, ok = m.Get(tablepb.Span{TableID: 1, StartKey: []byte{1}}) 49 require.Equal(t, v, 3) 50 require.True(t, ok) 51 52 // get value 53 v = m.GetV(tablepb.Span{TableID: 1, StartKey: []byte{1}}) 54 require.Equal(t, v, 3) 55 56 // Delete than get value 57 m.Delete(tablepb.Span{TableID: 1, StartKey: []byte{1}}) 58 require.Equal(t, 1, m.Len()) 59 require.False(t, m.Has(tablepb.Span{TableID: 1, StartKey: []byte{1}})) 60 v = m.GetV(tablepb.Span{TableID: 1, StartKey: []byte{1}}) 61 require.Equal(t, v, 0) 62 63 // Pointer value 64 mp := NewHashMap[*int]() 65 vp := &v 66 mp.ReplaceOrInsert(tablepb.Span{TableID: 1}, vp) 67 vp1, ok := mp.Get(tablepb.Span{TableID: 1}) 68 require.Equal(t, vp, vp1) 69 require.True(t, ok) 70 require.Equal(t, 1, m.Len()) 71 } 72 73 func TestHashMapIter(t *testing.T) { 74 t.Parallel() 75 76 m := NewHashMap[int]() 77 for i := 0; i < 4; i++ { 78 m.ReplaceOrInsert(tablepb.Span{TableID: int64(i)}, i) 79 } 80 81 j := 0 82 m.Range(func(span tablepb.Span, value int) bool { 83 _, ok := m.Get(span) 84 require.True(t, ok) 85 j++ 86 return true 87 }) 88 require.Equal(t, 4, j) 89 90 j = 0 91 m.Range(func(span tablepb.Span, value int) bool { 92 ok := m.Has(span) 93 require.True(t, ok) 94 j++ 95 return false 96 }) 97 require.Equal(t, 1, j) 98 }