github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/sync/map_int_test.go (about) 1 // Copyright 2023 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package syncutils_test 4 5 import ( 6 "github.com/TeaOSLab/EdgeNode/internal/stats" 7 syncutils "github.com/TeaOSLab/EdgeNode/internal/utils/sync" 8 "github.com/iwind/TeaGo/assert" 9 "github.com/iwind/TeaGo/types" 10 "sync" 11 "testing" 12 ) 13 14 func TestIntMap(t *testing.T) { 15 var a = assert.NewAssertion(t) 16 17 var m = syncutils.NewIntMap[int, string]() 18 m.Put(1, "1") 19 a.IsTrue(m.Has(1)) 20 a.IsFalse(m.Has(2)) 21 m.Put(-1, "-1") 22 t.Log(m.Get(-1)) 23 t.Log(m.Len(), "values") 24 { 25 a.IsTrue(m.Has(-1)) 26 m.Delete(-1) 27 a.IsFalse(m.Has(-1)) 28 } 29 t.Log(m.Len(), "values") 30 } 31 32 func TestInt64Map(t *testing.T) { 33 var a = assert.NewAssertion(t) 34 35 var m = syncutils.NewIntMap[int64, string]() 36 m.Put(1, "1") 37 a.IsTrue(m.Has(1)) 38 a.IsFalse(m.Has(2)) 39 m.Put(-1, "-1") 40 t.Log(m.Get(-1)) 41 t.Log(m.Len(), "values") 42 { 43 a.IsTrue(m.Has(-1)) 44 m.Delete(-1) 45 a.IsFalse(m.Has(-1)) 46 } 47 m.Put(1024000000, "large int") 48 t.Log(m.Get(1024000000)) 49 t.Log(m.Len(), "values") 50 } 51 52 func TestIntMap_PutCompact(t *testing.T) { 53 var a = assert.NewAssertion(t) 54 55 var m = syncutils.NewIntMap[int, string]() 56 m.Put(1, "a") 57 m.Put(1, "b") 58 a.IsTrue(m.Get(1) == "b") 59 60 m.PutCompact(1, "c", func(oldV string, newV string) string { 61 return oldV + newV 62 }) 63 64 a.IsTrue(m.Get(1) == "bc") 65 } 66 67 func TestIntMap_ForEachRead(t *testing.T) { 68 var m = syncutils.NewIntMap[int, string]() 69 for i := 0; i < 100; i++ { 70 m.Put(i, "v"+types.String(i)) 71 } 72 73 t.Log(m.Len()) 74 75 m.ForEachRead(func(k int, v string) { 76 t.Log(k, v) 77 }) 78 } 79 80 func TestIntMap_ForEachWrite(t *testing.T) { 81 var m = syncutils.NewIntMap[int, string]() 82 for i := 0; i < 100; i++ { 83 m.Put(i, "v"+types.String(i)) 84 } 85 86 t.Log(m.Len()) 87 88 m.ForEachRead(func(k int, v string) { 89 t.Log(k, v) 90 m.DeleteUnsafe(k) 91 }) 92 t.Log(m.Len(), "elements left") 93 } 94 95 func BenchmarkNewIntMap(b *testing.B) { 96 var m = syncutils.NewIntMap[int, *stats.BandwidthStat]() 97 98 b.RunParallel(func(pb *testing.PB) { 99 var i int 100 for pb.Next() { 101 i++ 102 m.Put(i, &stats.BandwidthStat{ServerId: 100}) 103 _ = m.Get(i + 100) 104 } 105 }) 106 } 107 108 func BenchmarkNewIntMap2(b *testing.B) { 109 var m = map[int]*stats.BandwidthStat{} 110 var locker = sync.RWMutex{} 111 112 b.RunParallel(func(pb *testing.PB) { 113 var i int 114 for pb.Next() { 115 i++ 116 locker.Lock() 117 m[i] = &stats.BandwidthStat{ServerId: 100} 118 locker.Unlock() 119 120 locker.RLock() 121 _ = m[i+100] 122 locker.RUnlock() 123 } 124 }) 125 }