├── .github └── workflows │ ├── build-test.yml │ └── release.yml ├── .gitignore ├── .golangci.yml ├── .goreleaser.yml ├── LICENSE ├── README.md ├── benchmark.png ├── concurrent_swiss_map.go ├── concurrent_swiss_map_benchmark_test.go ├── concurrent_swiss_map_test.go ├── example └── base │ └── base.go ├── go.mod ├── go.sum ├── img.png ├── maphash ├── .gitignore ├── LICENSE ├── README.md ├── hasher.go └── runtime.go └── swiss ├── .gitignore ├── LICENSE ├── README.md ├── bits.go ├── bits_amd64.go ├── map.go └── simd ├── match.s └── match_amd64.go /.github/workflows/build-test.yml: -------------------------------------------------------------------------------- 1 | name: 🔨 Build And Test 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | types: [opened, reopened, synchronize] 9 | 10 | concurrency: 11 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 12 | cancel-in-progress: true 13 | 14 | jobs: 15 | build: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v3 20 | with: 21 | fetch-depth: 1 22 | 23 | - name: Set up Go 24 | uses: actions/setup-go@v4 25 | with: 26 | go-version: 1.18 27 | 28 | - name: Install dependencies 29 | run: go get . 30 | 31 | - name: golangci-lint 32 | uses: golangci/golangci-lint-action@v3 33 | with: 34 | version: v1.52.2 35 | args: -c .golangci.yml --timeout=5m -v 36 | 37 | - name: Build 38 | run: go build -v ./... 39 | 40 | - name: Test 41 | run: go test -race -coverprofile=coverage.txt -covermode=atomic 42 | 43 | - name: Upload coverage to Codecov 44 | uses: codecov/codecov-action@v3 45 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: 🎉 Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | goreleaser: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | with: 18 | fetch-depth: 1 19 | 20 | - run: git tag ${{ github.event.inputs.tag }} 21 | 22 | - name: Set up Go 23 | uses: actions/setup-go@v3 24 | with: 25 | go-version: 1.18 26 | 27 | - name: Run GoReleaser 28 | uses: goreleaser/goreleaser-action@v4 29 | with: 30 | version: latest 31 | args: release --rm-dist 32 | env: 33 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | .idea 8 | 9 | # Test binary, built with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | # Dependency directories (remove the comment below to include it) 16 | # vendor/ -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | skip-dirs: 3 | - swiss 4 | - swiss/simd 5 | - maphash 6 | skip-files: 7 | - "concurrent_swiss_map_benchmark_test.go" 8 | skip-dirs-use-default: false 9 | 10 | linters-settings: 11 | lll: 12 | line-length: 140 13 | funlen: 14 | lines: 70 15 | 16 | linters: 17 | disable-all: true 18 | enable: 19 | - bodyclose 20 | - depguard 21 | - errcheck 22 | - exhaustive 23 | - funlen 24 | - goconst 25 | - gocritic 26 | - gocyclo 27 | - revive 28 | - gosimple 29 | - govet 30 | - gosec 31 | - ineffassign 32 | - lll 33 | - misspell 34 | - nakedret 35 | - gofumpt 36 | - staticcheck 37 | - stylecheck 38 | - typecheck 39 | - unconvert 40 | - unparam 41 | - whitespace 42 | 43 | service: 44 | golangci-lint-version: 1.50.x # use the fixed version to not introduce new linters unexpectedly 45 | prepare: 46 | - echo "here I can run custom commands, but no preparation needed for this repo" -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | project_name: concurrent-swiss-map 2 | 3 | release: 4 | github: 5 | name: concurrent-swiss-map 6 | owner: mhmtszr 7 | 8 | before: 9 | hooks: 10 | - go mod tidy 11 | 12 | builds: 13 | - skip: true 14 | 15 | changelog: 16 | sort: asc 17 | use: github 18 | filters: 19 | exclude: 20 | - '^test:' 21 | - '^docs:' 22 | - '^chore:' 23 | - 'merge conflict' 24 | - Merge pull request 25 | - Merge remote-tracking branch 26 | - Merge branch 27 | - go mod tidy -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Mehmet Sezer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Concurrent Swiss Map [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] [![Go Report Card][go-report-img]][go-report] 2 | 3 | **Concurrent Swiss Map** is an open-source Go library that provides a high-performance, thread-safe generic concurrent hash map implementation designed to handle concurrent access efficiently. It's built with a focus on simplicity, speed, and reliability, making it a solid choice for scenarios where concurrent access to a hash map is crucial. 4 | 5 | Uses [dolthub/swiss](https://github.com/dolthub/swiss) map implementation under the hood. 6 | 7 | ## Installation 8 | 9 | Supports 1.18+ Go versions because of Go Generics 10 | 11 | ``` 12 | go get github.com/mhmtszr/concurrent-swiss-map 13 | ``` 14 | 15 | ## Usage 16 | 17 | New functions will be added soon... 18 | 19 | ```go 20 | package main 21 | 22 | import ( 23 | "hash/fnv" 24 | 25 | csmap "github.com/mhmtszr/concurrent-swiss-map" 26 | ) 27 | 28 | func main() { 29 | myMap := csmap.New[string, int]( 30 | // set the number of map shards. the default value is 32. 31 | csmap.WithShardCount[string, int](32), 32 | 33 | // if don't set custom hasher, use the built-in maphash. 34 | csmap.WithCustomHasher[string, int](func(key string) uint64 { 35 | hash := fnv.New64a() 36 | hash.Write([]byte(key)) 37 | return hash.Sum64() 38 | }), 39 | 40 | // set the total capacity, every shard map has total capacity/shard count capacity. the default value is 0. 41 | csmap.WithSize[string, int](1000), 42 | ) 43 | 44 | key := "swiss-map" 45 | myMap.Store(key, 10) 46 | 47 | val, ok := myMap.Load(key) 48 | println("load val:", val, "exists:", ok) 49 | 50 | deleted := myMap.Delete(key) 51 | println("deleted:", deleted) 52 | 53 | ok = myMap.Has(key) 54 | println("has:", ok) 55 | 56 | empty := myMap.IsEmpty() 57 | println("empty:", empty) 58 | 59 | myMap.SetIfAbsent(key, 11) 60 | 61 | myMap.Range(func(key string, value int) (stop bool) { 62 | println("range:", key, value) 63 | return true 64 | }) 65 | 66 | count := myMap.Count() 67 | println("count:", count) 68 | 69 | // Output: 70 | // load val: 10 exists: true 71 | // deleted: true 72 | // has: false 73 | // empty: true 74 | // range: swiss-map 11 75 | // count: 1 76 | } 77 | ``` 78 | 79 | ## Basic Architecture 80 | ![img.png](img.png) 81 | 82 | ## Benchmark Test 83 | Benchmark was made on: 84 | - Apple M1 Max 85 | - 32 GB memory 86 | 87 | Benchmark test results can be obtained by running [this file](concurrent_swiss_map_benchmark_test.go) on local computers. 88 | 89 | ![benchmark.png](benchmark.png) 90 | 91 | ### Benchmark Results 92 | 93 | - Memory usage of the concurrent swiss map is better than other map implementations in all checked test scenarios. 94 | - In high concurrent systems, the concurrent swiss map is faster, but in systems containing few concurrent operations, it works similarly to RWMutexMap. 95 | 96 | [doc-img]: https://godoc.org/github.com/mhmtszr/concurrent-swiss-map?status.svg 97 | [doc]: https://godoc.org/github.com/mhmtszr/concurrent-swiss-map 98 | [ci-img]: https://github.com/mhmtszr/concurrent-swiss-map/actions/workflows/build-test.yml/badge.svg 99 | [ci]: https://github.com/mhmtszr/concurrent-swiss-map/actions/workflows/build-test.yml 100 | [cov-img]: https://codecov.io/gh/mhmtszr/concurrent-swiss-map/branch/master/graph/badge.svg 101 | [cov]: https://codecov.io/gh/mhmtszr/concurrent-swiss-map 102 | [go-report-img]: https://goreportcard.com/badge/github.com/mhmtszr/concurrent-swiss-map 103 | [go-report]: https://goreportcard.com/report/github.com/mhmtszr/concurrent-swiss-map -------------------------------------------------------------------------------- /benchmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhmtszr/concurrent-swiss-map/726f60ce3da7081874637600f490ae72cdf7e003/benchmark.png -------------------------------------------------------------------------------- /concurrent_swiss_map.go: -------------------------------------------------------------------------------- 1 | package csmap 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "sync" 7 | 8 | "github.com/mhmtszr/concurrent-swiss-map/maphash" 9 | 10 | "github.com/mhmtszr/concurrent-swiss-map/swiss" 11 | ) 12 | 13 | type CsMap[K comparable, V any] struct { 14 | hasher func(key K) uint64 15 | shards []shard[K, V] 16 | shardCount uint64 17 | size uint64 18 | } 19 | 20 | type HashShardPair[K comparable, V any] struct { 21 | shard shard[K, V] 22 | hash uint64 23 | } 24 | 25 | type shard[K comparable, V any] struct { 26 | items *swiss.Map[K, V] 27 | *sync.RWMutex 28 | } 29 | 30 | // OptFunc is a type that is used in New function for passing options. 31 | type OptFunc[K comparable, V any] func(o *CsMap[K, V]) 32 | 33 | // New function creates *CsMap[K, V]. 34 | func New[K comparable, V any](options ...OptFunc[K, V]) *CsMap[K, V] { 35 | m := CsMap[K, V]{ 36 | hasher: maphash.NewHasher[K]().Hash, 37 | shardCount: 32, 38 | } 39 | for _, option := range options { 40 | option(&m) 41 | } 42 | 43 | m.shards = make([]shard[K, V], m.shardCount) 44 | 45 | for i := 0; i < int(m.shardCount); i++ { 46 | m.shards[i] = shard[K, V]{items: swiss.NewMap[K, V](uint32((m.size / m.shardCount) + 1)), RWMutex: &sync.RWMutex{}} 47 | } 48 | return &m 49 | } 50 | 51 | // Create creates *CsMap. 52 | // 53 | // Deprecated: New function should be used instead. 54 | func Create[K comparable, V any](options ...func(options *CsMap[K, V])) *CsMap[K, V] { 55 | m := CsMap[K, V]{ 56 | hasher: maphash.NewHasher[K]().Hash, 57 | shardCount: 32, 58 | } 59 | for _, option := range options { 60 | option(&m) 61 | } 62 | 63 | m.shards = make([]shard[K, V], m.shardCount) 64 | 65 | for i := 0; i < int(m.shardCount); i++ { 66 | m.shards[i] = shard[K, V]{items: swiss.NewMap[K, V](uint32((m.size / m.shardCount) + 1)), RWMutex: &sync.RWMutex{}} 67 | } 68 | return &m 69 | } 70 | 71 | func WithShardCount[K comparable, V any](count uint64) func(csMap *CsMap[K, V]) { 72 | return func(csMap *CsMap[K, V]) { 73 | csMap.shardCount = count 74 | } 75 | } 76 | 77 | func WithCustomHasher[K comparable, V any](h func(key K) uint64) func(csMap *CsMap[K, V]) { 78 | return func(csMap *CsMap[K, V]) { 79 | csMap.hasher = h 80 | } 81 | } 82 | 83 | func WithSize[K comparable, V any](size uint64) func(csMap *CsMap[K, V]) { 84 | return func(csMap *CsMap[K, V]) { 85 | csMap.size = size 86 | } 87 | } 88 | 89 | func (m *CsMap[K, V]) getShard(key K) HashShardPair[K, V] { 90 | u := m.hasher(key) 91 | return HashShardPair[K, V]{ 92 | hash: u, 93 | shard: m.shards[u%m.shardCount], 94 | } 95 | } 96 | 97 | func (m *CsMap[K, V]) Store(key K, value V) { 98 | hashShardPair := m.getShard(key) 99 | shard := hashShardPair.shard 100 | shard.Lock() 101 | shard.items.PutWithHash(key, value, hashShardPair.hash) 102 | shard.Unlock() 103 | } 104 | 105 | func (m *CsMap[K, V]) Delete(key K) bool { 106 | hashShardPair := m.getShard(key) 107 | shard := hashShardPair.shard 108 | shard.Lock() 109 | defer shard.Unlock() 110 | return shard.items.DeleteWithHash(key, hashShardPair.hash) 111 | } 112 | 113 | func (m *CsMap[K, V]) DeleteIf(key K, condition func(value V) bool) bool { 114 | hashShardPair := m.getShard(key) 115 | shard := hashShardPair.shard 116 | shard.Lock() 117 | defer shard.Unlock() 118 | value, ok := shard.items.GetWithHash(key, hashShardPair.hash) 119 | if ok && condition(value) { 120 | return shard.items.DeleteWithHash(key, hashShardPair.hash) 121 | } 122 | return false 123 | } 124 | 125 | func (m *CsMap[K, V]) Load(key K) (V, bool) { 126 | hashShardPair := m.getShard(key) 127 | shard := hashShardPair.shard 128 | shard.RLock() 129 | defer shard.RUnlock() 130 | return shard.items.GetWithHash(key, hashShardPair.hash) 131 | } 132 | 133 | func (m *CsMap[K, V]) Has(key K) bool { 134 | hashShardPair := m.getShard(key) 135 | shard := hashShardPair.shard 136 | shard.RLock() 137 | defer shard.RUnlock() 138 | return shard.items.HasWithHash(key, hashShardPair.hash) 139 | } 140 | 141 | func (m *CsMap[K, V]) Clear() { 142 | for i := range m.shards { 143 | shard := m.shards[i] 144 | 145 | shard.Lock() 146 | shard.items.Clear() 147 | shard.Unlock() 148 | } 149 | } 150 | 151 | func (m *CsMap[K, V]) Count() int { 152 | count := 0 153 | for i := range m.shards { 154 | shard := m.shards[i] 155 | shard.RLock() 156 | count += shard.items.Count() 157 | shard.RUnlock() 158 | } 159 | return count 160 | } 161 | 162 | func (m *CsMap[K, V]) SetIfAbsent(key K, value V) { 163 | hashShardPair := m.getShard(key) 164 | shard := hashShardPair.shard 165 | shard.Lock() 166 | _, ok := shard.items.GetWithHash(key, hashShardPair.hash) 167 | if !ok { 168 | shard.items.PutWithHash(key, value, hashShardPair.hash) 169 | } 170 | shard.Unlock() 171 | } 172 | 173 | func (m *CsMap[K, V]) SetIf(key K, conditionFn func(previousVale V, previousFound bool) (value V, set bool)) { 174 | hashShardPair := m.getShard(key) 175 | shard := hashShardPair.shard 176 | shard.Lock() 177 | value, found := shard.items.GetWithHash(key, hashShardPair.hash) 178 | value, ok := conditionFn(value, found) 179 | if ok { 180 | shard.items.PutWithHash(key, value, hashShardPair.hash) 181 | } 182 | shard.Unlock() 183 | } 184 | 185 | func (m *CsMap[K, V]) SetIfPresent(key K, value V) { 186 | hashShardPair := m.getShard(key) 187 | shard := hashShardPair.shard 188 | shard.Lock() 189 | _, ok := shard.items.GetWithHash(key, hashShardPair.hash) 190 | if ok { 191 | shard.items.PutWithHash(key, value, hashShardPair.hash) 192 | } 193 | shard.Unlock() 194 | } 195 | 196 | func (m *CsMap[K, V]) IsEmpty() bool { 197 | return m.Count() == 0 198 | } 199 | 200 | type Tuple[K comparable, V any] struct { 201 | Key K 202 | Val V 203 | } 204 | 205 | // Range If the callback function returns true iteration will stop. 206 | func (m *CsMap[K, V]) Range(f func(key K, value V) (stop bool)) { 207 | ch := make(chan Tuple[K, V], m.Count()) 208 | 209 | ctx, cancel := context.WithCancel(context.Background()) 210 | defer cancel() 211 | 212 | listenCompleted := m.listen(f, ch) 213 | m.produce(ctx, ch) 214 | listenCompleted.Wait() 215 | } 216 | 217 | func (m *CsMap[K, V]) MarshalJSON() ([]byte, error) { 218 | tmp := make(map[K]V, m.Count()) 219 | m.Range(func(key K, value V) (stop bool) { 220 | tmp[key] = value 221 | return false 222 | }) 223 | return json.Marshal(tmp) 224 | } 225 | 226 | func (m *CsMap[K, V]) UnmarshalJSON(b []byte) error { 227 | tmp := make(map[K]V, m.Count()) 228 | 229 | if err := json.Unmarshal(b, &tmp); err != nil { 230 | return err 231 | } 232 | 233 | for key, val := range tmp { 234 | m.Store(key, val) 235 | } 236 | return nil 237 | } 238 | 239 | func (m *CsMap[K, V]) produce(ctx context.Context, ch chan Tuple[K, V]) { 240 | var wg sync.WaitGroup 241 | wg.Add(len(m.shards)) 242 | for i := range m.shards { 243 | go func(i int) { 244 | defer wg.Done() 245 | 246 | shard := m.shards[i] 247 | shard.RLock() 248 | shard.items.Iter(func(k K, v V) (stop bool) { 249 | select { 250 | case <-ctx.Done(): 251 | return true 252 | default: 253 | ch <- Tuple[K, V]{Key: k, Val: v} 254 | } 255 | return false 256 | }) 257 | shard.RUnlock() 258 | }(i) 259 | } 260 | go func() { 261 | wg.Wait() 262 | close(ch) 263 | }() 264 | } 265 | 266 | func (m *CsMap[K, V]) listen(f func(key K, value V) (stop bool), ch chan Tuple[K, V]) *sync.WaitGroup { 267 | var wg sync.WaitGroup 268 | wg.Add(1) 269 | go func() { 270 | defer wg.Done() 271 | for t := range ch { 272 | if stop := f(t.Key, t.Val); stop { 273 | return 274 | } 275 | } 276 | }() 277 | return &wg 278 | } 279 | -------------------------------------------------------------------------------- /concurrent_swiss_map_benchmark_test.go: -------------------------------------------------------------------------------- 1 | //nolint:all 2 | package csmap_test 3 | 4 | // import ( 5 | // "fmt" 6 | // "runtime" 7 | // "strconv" 8 | // "sync" 9 | // "testing" 10 | // 11 | // "github.com/mhmtszr/concurrent-swiss-map" 12 | //) 13 | // 14 | 15 | // var table = []struct { 16 | // total int 17 | // deletion int 18 | // }{ 19 | // { 20 | // total: 100, 21 | // deletion: 100, 22 | // }, 23 | // { 24 | // total: 5000000, 25 | // deletion: 5000000, 26 | // }, 27 | //} 28 | 29 | // func PrintMemUsage() { 30 | // var m runtime.MemStats 31 | // runtime.ReadMemStats(&m) 32 | // // For info on each, see: https://golang.org/pkg/runtime/#MemStats 33 | // fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc)) 34 | // fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc)) 35 | // fmt.Printf("\tSys = %v MiB", bToMb(m.Sys)) 36 | // fmt.Printf("\tNumGC = %v\n", m.NumGC) 37 | //} 38 | // 39 | // func bToMb(b uint64) uint64 { 40 | // return b / 1024 / 1024 41 | //} 42 | 43 | // func BenchmarkConcurrentSwissMapGoMaxProcs1(b *testing.B) { 44 | // runtime.GOMAXPROCS(1) 45 | // debug.SetGCPercent(-1) 46 | // debug.SetMemoryLimit(math.MaxInt64) 47 | // for _, v := range table { 48 | // b.Run(fmt.Sprintf("total: %d deletion: %d", v.total, v.deletion), func(b *testing.B) { 49 | // for i := 0; i < b.N; i++ { 50 | // m1 := csmap.Create[int, string]() 51 | // var wg sync.WaitGroup 52 | // wg.Add(3) 53 | // go func() { 54 | // defer wg.Done() 55 | // var wg2 sync.WaitGroup 56 | // wg2.Add(v.total) 57 | // for i := 0; i < v.total; i++ { 58 | // i := i 59 | // go func() { 60 | // defer wg2.Done() 61 | // m1.Store(i, strconv.Itoa(i)) 62 | // }() 63 | // } 64 | // wg2.Wait() 65 | // }() 66 | // 67 | // go func() { 68 | // defer wg.Done() 69 | // var wg2 sync.WaitGroup 70 | // wg2.Add(v.total) 71 | // for i := 0; i < v.total; i++ { 72 | // i := i 73 | // go func() { 74 | // defer wg2.Done() 75 | // m1.Store(i, strconv.Itoa(i)) 76 | // }() 77 | // } 78 | // wg2.Wait() 79 | // }() 80 | // 81 | // go func() { 82 | // defer wg.Done() 83 | // var wg2 sync.WaitGroup 84 | // wg2.Add(v.total) 85 | // for i := 0; i < v.total; i++ { 86 | // i := i 87 | // go func() { 88 | // defer wg2.Done() 89 | // m1.Store(10, strconv.Itoa(i)) 90 | // m1.Delete(10) 91 | // }() 92 | // } 93 | // wg2.Wait() 94 | // }() 95 | // wg.Wait() 96 | // 97 | // wg.Add(v.deletion + v.total) 98 | // for i := 0; i < v.deletion; i++ { 99 | // i := i 100 | // go func() { 101 | // defer wg.Done() 102 | // m1.Delete(i) 103 | // }() 104 | // } 105 | // 106 | // for i := 0; i < v.total; i++ { 107 | // i := i 108 | // go func() { 109 | // defer wg.Done() 110 | // m1.Load(i) 111 | // }() 112 | // } 113 | // wg.Wait() 114 | // } 115 | // }) 116 | // } 117 | // PrintMemUsage() 118 | //} 119 | 120 | // func BenchmarkSyncMapGoMaxProcs1(b *testing.B) { 121 | // runtime.GOMAXPROCS(1) 122 | // debug.SetGCPercent(-1) 123 | // debug.SetMemoryLimit(math.MaxInt64) 124 | // for _, v := range table { 125 | // b.Run(fmt.Sprintf("total: %d deletion: %d", v.total, v.deletion), func(b *testing.B) { 126 | // for i := 0; i < b.N; i++ { 127 | // var m1 sync.Map 128 | // var wg sync.WaitGroup 129 | // wg.Add(3) 130 | // go func() { 131 | // defer wg.Done() 132 | // var wg2 sync.WaitGroup 133 | // wg2.Add(v.total) 134 | // for i := 0; i < v.total; i++ { 135 | // i := i 136 | // go func() { 137 | // defer wg2.Done() 138 | // m1.Store(i, strconv.Itoa(i)) 139 | // }() 140 | // } 141 | // wg2.Wait() 142 | // }() 143 | // 144 | // go func() { 145 | // defer wg.Done() 146 | // var wg2 sync.WaitGroup 147 | // wg2.Add(v.total) 148 | // for i := 0; i < v.total; i++ { 149 | // i := i 150 | // go func() { 151 | // defer wg2.Done() 152 | // m1.Store(i, strconv.Itoa(i)) 153 | // }() 154 | // } 155 | // wg2.Wait() 156 | // }() 157 | // 158 | // go func() { 159 | // defer wg.Done() 160 | // var wg2 sync.WaitGroup 161 | // wg2.Add(v.total) 162 | // for i := 0; i < v.total; i++ { 163 | // i := i 164 | // go func() { 165 | // defer wg2.Done() 166 | // m1.Store(10, strconv.Itoa(i)) 167 | // m1.Delete(10) 168 | // }() 169 | // } 170 | // wg2.Wait() 171 | // }() 172 | // wg.Wait() 173 | // 174 | // wg.Add(v.deletion + v.total) 175 | // for i := 0; i < v.deletion; i++ { 176 | // i := i 177 | // go func() { 178 | // defer wg.Done() 179 | // m1.Delete(i) 180 | // }() 181 | // } 182 | // 183 | // for i := 0; i < v.total; i++ { 184 | // i := i 185 | // go func() { 186 | // defer wg.Done() 187 | // m1.Load(i) 188 | // }() 189 | // } 190 | // wg.Wait() 191 | // } 192 | // }) 193 | // } 194 | // PrintMemUsage() 195 | //} 196 | 197 | // func BenchmarkRWMutexMapGoMaxProcs1(b *testing.B) { 198 | // runtime.GOMAXPROCS(1) 199 | // debug.SetGCPercent(-1) 200 | // debug.SetMemoryLimit(math.MaxInt64) 201 | // for _, v := range table { 202 | // b.Run(fmt.Sprintf("total: %d deletion: %d", v.total, v.deletion), func(b *testing.B) { 203 | // for i := 0; i < b.N; i++ { 204 | // m1 := CreateTestRWMutexMap() 205 | // var wg sync.WaitGroup 206 | // wg.Add(3) 207 | // go func() { 208 | // defer wg.Done() 209 | // var wg2 sync.WaitGroup 210 | // wg2.Add(v.total) 211 | // for i := 0; i < v.total; i++ { 212 | // i := i 213 | // go func() { 214 | // defer wg2.Done() 215 | // m1.Store(i, strconv.Itoa(i)) 216 | // }() 217 | // } 218 | // wg2.Wait() 219 | // }() 220 | // 221 | // go func() { 222 | // defer wg.Done() 223 | // var wg2 sync.WaitGroup 224 | // wg2.Add(v.total) 225 | // for i := 0; i < v.total; i++ { 226 | // i := i 227 | // go func() { 228 | // defer wg2.Done() 229 | // m1.Store(i, strconv.Itoa(i)) 230 | // }() 231 | // } 232 | // wg2.Wait() 233 | // }() 234 | // 235 | // go func() { 236 | // defer wg.Done() 237 | // var wg2 sync.WaitGroup 238 | // wg2.Add(v.total) 239 | // for i := 0; i < v.total; i++ { 240 | // i := i 241 | // go func() { 242 | // defer wg2.Done() 243 | // m1.Store(10, strconv.Itoa(i)) 244 | // m1.Delete(10) 245 | // }() 246 | // } 247 | // wg2.Wait() 248 | // }() 249 | // wg.Wait() 250 | // 251 | // wg.Add(v.deletion + v.total) 252 | // for i := 0; i < v.deletion; i++ { 253 | // i := i 254 | // go func() { 255 | // defer wg.Done() 256 | // m1.Delete(i) 257 | // }() 258 | // } 259 | // 260 | // for i := 0; i < v.total; i++ { 261 | // i := i 262 | // go func() { 263 | // defer wg.Done() 264 | // m1.Load(i) 265 | // }() 266 | // } 267 | // wg.Wait() 268 | // } 269 | // }) 270 | // } 271 | // PrintMemUsage() 272 | //} 273 | 274 | // func BenchmarkConcurrentSwissMapGoMaxProcsCore(b *testing.B) { 275 | // debug.SetGCPercent(-1) 276 | // debug.SetMemoryLimit(math.MaxInt64) 277 | // for _, v := range table { 278 | // b.Run(fmt.Sprintf("total: %d deletion: %d", v.total, v.deletion), func(b *testing.B) { 279 | // for i := 0; i < b.N; i++ { 280 | // m1 := csmap.Create[int, string]() 281 | // var wg sync.WaitGroup 282 | // wg.Add(3) 283 | // go func() { 284 | // defer wg.Done() 285 | // var wg2 sync.WaitGroup 286 | // wg2.Add(v.total) 287 | // for i := 0; i < v.total; i++ { 288 | // i := i 289 | // go func() { 290 | // defer wg2.Done() 291 | // m1.Store(i, strconv.Itoa(i)) 292 | // }() 293 | // } 294 | // wg2.Wait() 295 | // }() 296 | // 297 | // go func() { 298 | // defer wg.Done() 299 | // var wg2 sync.WaitGroup 300 | // wg2.Add(v.total) 301 | // for i := 0; i < v.total; i++ { 302 | // i := i 303 | // go func() { 304 | // defer wg2.Done() 305 | // m1.Store(i, strconv.Itoa(i)) 306 | // }() 307 | // } 308 | // wg2.Wait() 309 | // }() 310 | // 311 | // go func() { 312 | // defer wg.Done() 313 | // var wg2 sync.WaitGroup 314 | // wg2.Add(v.total) 315 | // for i := 0; i < v.total; i++ { 316 | // i := i 317 | // go func() { 318 | // defer wg2.Done() 319 | // m1.Store(10, strconv.Itoa(i)) 320 | // m1.Delete(10) 321 | // }() 322 | // } 323 | // wg2.Wait() 324 | // }() 325 | // wg.Wait() 326 | // 327 | // wg.Add(v.deletion + v.total) 328 | // for i := 0; i < v.deletion; i++ { 329 | // i := i 330 | // go func() { 331 | // defer wg.Done() 332 | // m1.Delete(i) 333 | // }() 334 | // } 335 | // 336 | // for i := 0; i < v.total; i++ { 337 | // i := i 338 | // go func() { 339 | // defer wg.Done() 340 | // m1.Load(i) 341 | // }() 342 | // } 343 | // wg.Wait() 344 | // } 345 | // }) 346 | // } 347 | // PrintMemUsage() 348 | //} 349 | 350 | // func BenchmarkSyncMapGoMaxProcsCore(b *testing.B) { 351 | // debug.SetGCPercent(-1) 352 | // debug.SetMemoryLimit(math.MaxInt64) 353 | // for _, v := range table { 354 | // b.Run(fmt.Sprintf("total: %d deletion: %d", v.total, v.deletion), func(b *testing.B) { 355 | // for i := 0; i < b.N; i++ { 356 | // var m1 sync.Map 357 | // var wg sync.WaitGroup 358 | // wg.Add(3) 359 | // go func() { 360 | // defer wg.Done() 361 | // var wg2 sync.WaitGroup 362 | // wg2.Add(v.total) 363 | // for i := 0; i < v.total; i++ { 364 | // i := i 365 | // go func() { 366 | // defer wg2.Done() 367 | // m1.Store(i, strconv.Itoa(i)) 368 | // }() 369 | // } 370 | // wg2.Wait() 371 | // }() 372 | // 373 | // go func() { 374 | // defer wg.Done() 375 | // var wg2 sync.WaitGroup 376 | // wg2.Add(v.total) 377 | // for i := 0; i < v.total; i++ { 378 | // i := i 379 | // go func() { 380 | // defer wg2.Done() 381 | // m1.Store(i, strconv.Itoa(i)) 382 | // }() 383 | // } 384 | // wg2.Wait() 385 | // }() 386 | // 387 | // go func() { 388 | // defer wg.Done() 389 | // var wg2 sync.WaitGroup 390 | // wg2.Add(v.total) 391 | // for i := 0; i < v.total; i++ { 392 | // i := i 393 | // go func() { 394 | // defer wg2.Done() 395 | // m1.Store(10, strconv.Itoa(i)) 396 | // m1.Delete(10) 397 | // }() 398 | // } 399 | // wg2.Wait() 400 | // }() 401 | // wg.Wait() 402 | // 403 | // wg.Add(v.deletion + v.total) 404 | // for i := 0; i < v.deletion; i++ { 405 | // i := i 406 | // go func() { 407 | // defer wg.Done() 408 | // m1.Delete(i) 409 | // }() 410 | // } 411 | // 412 | // for i := 0; i < v.total; i++ { 413 | // i := i 414 | // go func() { 415 | // defer wg.Done() 416 | // m1.Load(i) 417 | // }() 418 | // } 419 | // wg.Wait() 420 | // } 421 | // }) 422 | // } 423 | // PrintMemUsage() 424 | //} 425 | 426 | // func BenchmarkRWMutexMapGoMaxProcsCore(b *testing.B) { 427 | // debug.SetGCPercent(-1) 428 | // debug.SetMemoryLimit(math.MaxInt64) 429 | // for _, v := range table { 430 | // b.Run(fmt.Sprintf("total: %d deletion: %d", v.total, v.deletion), func(b *testing.B) { 431 | // for i := 0; i < b.N; i++ { 432 | // m1 := CreateTestRWMutexMap() 433 | // var wg sync.WaitGroup 434 | // wg.Add(3) 435 | // go func() { 436 | // defer wg.Done() 437 | // var wg2 sync.WaitGroup 438 | // wg2.Add(v.total) 439 | // for i := 0; i < v.total; i++ { 440 | // i := i 441 | // go func() { 442 | // defer wg2.Done() 443 | // m1.Store(i, strconv.Itoa(i)) 444 | // }() 445 | // } 446 | // wg2.Wait() 447 | // }() 448 | // 449 | // go func() { 450 | // defer wg.Done() 451 | // var wg2 sync.WaitGroup 452 | // wg2.Add(v.total) 453 | // for i := 0; i < v.total; i++ { 454 | // i := i 455 | // go func() { 456 | // defer wg2.Done() 457 | // m1.Store(i, strconv.Itoa(i)) 458 | // }() 459 | // } 460 | // wg2.Wait() 461 | // }() 462 | // 463 | // go func() { 464 | // defer wg.Done() 465 | // var wg2 sync.WaitGroup 466 | // wg2.Add(v.total) 467 | // for i := 0; i < v.total; i++ { 468 | // i := i 469 | // go func() { 470 | // defer wg2.Done() 471 | // m1.Store(10, strconv.Itoa(i)) 472 | // m1.Delete(10) 473 | // }() 474 | // } 475 | // wg2.Wait() 476 | // }() 477 | // wg.Wait() 478 | // 479 | // wg.Add(v.deletion + v.total) 480 | // for i := 0; i < v.deletion; i++ { 481 | // i := i 482 | // go func() { 483 | // defer wg.Done() 484 | // m1.Delete(i) 485 | // }() 486 | // } 487 | // 488 | // for i := 0; i < v.total; i++ { 489 | // i := i 490 | // go func() { 491 | // defer wg.Done() 492 | // m1.Load(i) 493 | // }() 494 | // } 495 | // wg.Wait() 496 | // } 497 | // }) 498 | // } 499 | // PrintMemUsage() 500 | //} 501 | 502 | // type TestRWMutexMap struct { 503 | // m map[int]string 504 | // sync.RWMutex 505 | //} 506 | // 507 | // func CreateTestRWMutexMap() *TestRWMutexMap { 508 | // return &TestRWMutexMap{ 509 | // m: make(map[int]string), 510 | // } 511 | //} 512 | // 513 | // func (m *TestRWMutexMap) Store(key int, value string) { 514 | // m.Lock() 515 | // defer m.Unlock() 516 | // m.m[key] = value 517 | //} 518 | // 519 | // func (m *TestRWMutexMap) Delete(key int) { 520 | // m.Lock() 521 | // defer m.Unlock() 522 | // delete(m.m, key) 523 | //} 524 | // 525 | // func (m *TestRWMutexMap) Load(key int) *string { 526 | // m.RLock() 527 | // defer m.RUnlock() 528 | // s, ok := m.m[key] 529 | // if !ok { 530 | // return nil 531 | // } 532 | // return &s 533 | //} 534 | -------------------------------------------------------------------------------- /concurrent_swiss_map_test.go: -------------------------------------------------------------------------------- 1 | package csmap_test 2 | 3 | import ( 4 | "strconv" 5 | "sync" 6 | "testing" 7 | 8 | csmap "github.com/mhmtszr/concurrent-swiss-map" 9 | ) 10 | 11 | func TestHas(t *testing.T) { 12 | myMap := csmap.New[int, string]() 13 | myMap.Store(1, "test") 14 | if !myMap.Has(1) { 15 | t.Fatal("1 should exists") 16 | } 17 | } 18 | 19 | func TestLoad(t *testing.T) { 20 | myMap := csmap.New[int, string]() 21 | myMap.Store(1, "test") 22 | v, ok := myMap.Load(1) 23 | v2, ok2 := myMap.Load(2) 24 | if v != "test" || !ok { 25 | t.Fatal("1 should test") 26 | } 27 | if v2 != "" || ok2 { 28 | t.Fatal("2 should not exist") 29 | } 30 | } 31 | 32 | func TestDelete(t *testing.T) { 33 | myMap := csmap.New[int, string]() 34 | myMap.Store(1, "test") 35 | ok1 := myMap.Delete(20) 36 | ok2 := myMap.Delete(1) 37 | if myMap.Has(1) { 38 | t.Fatal("1 should be deleted") 39 | } 40 | if ok1 { 41 | t.Fatal("ok1 should be false") 42 | } 43 | if !ok2 { 44 | t.Fatal("ok2 should be true") 45 | } 46 | } 47 | 48 | func TestSetIfAbsent(t *testing.T) { 49 | myMap := csmap.New[int, string]() 50 | myMap.SetIfAbsent(1, "test") 51 | if !myMap.Has(1) { 52 | t.Fatal("1 should be exist") 53 | } 54 | } 55 | 56 | func TestSetIfPresent(t *testing.T) { 57 | myMap := csmap.New[int, string]() 58 | myMap.SetIfPresent(1, "test") 59 | if myMap.Has(1) { 60 | t.Fatal("1 should be not exist") 61 | } 62 | 63 | myMap.Store(1, "test") 64 | myMap.SetIfPresent(1, "new-test") 65 | val, _ := myMap.Load(1) 66 | if val != "new-test" { 67 | t.Fatal("val should be new-test") 68 | } 69 | } 70 | 71 | func TestSetIf(t *testing.T) { 72 | myMap := csmap.New[int, string]() 73 | valueA := "value a" 74 | myMap.SetIf(1, func(previousVale string, previousFound bool) (value string, set bool) { 75 | // operate like a SetIfAbsent... 76 | if !previousFound { 77 | return valueA, true 78 | } 79 | return "", false 80 | }) 81 | value, _ := myMap.Load(1) 82 | if value != valueA { 83 | t.Fatal("value should value a") 84 | } 85 | 86 | myMap.SetIf(1, func(previousVale string, previousFound bool) (value string, set bool) { 87 | // operate like a SetIfAbsent... 88 | if !previousFound { 89 | return "bad", true 90 | } 91 | return "", false 92 | }) 93 | value, _ = myMap.Load(1) 94 | if value != valueA { 95 | t.Fatal("value should value a") 96 | } 97 | } 98 | 99 | func TestDeleteIf(t *testing.T) { 100 | myMap := csmap.New[int, string]() 101 | myMap.Store(1, "value b") 102 | ok1 := myMap.DeleteIf(20, func(value string) bool { 103 | t.Fatal("condition function should not have been called") 104 | return false 105 | }) 106 | if ok1 { 107 | t.Fatal("ok1 should be false") 108 | } 109 | 110 | ok2 := myMap.DeleteIf(1, func(value string) bool { 111 | if value != "value b" { 112 | t.Fatal("condition function arg should be tests") 113 | } 114 | return false // don't delete 115 | }) 116 | if ok2 { 117 | t.Fatal("ok1 should be false") 118 | } 119 | 120 | ok3 := myMap.DeleteIf(1, func(value string) bool { 121 | if value != "value b" { 122 | t.Fatal("condition function arg should be tests") 123 | } 124 | return true // delete the entry 125 | }) 126 | if !ok3 { 127 | t.Fatal("ok2 should be true") 128 | } 129 | } 130 | 131 | func TestCount(t *testing.T) { 132 | myMap := csmap.New[int, string]() 133 | myMap.SetIfAbsent(1, "test") 134 | myMap.SetIfAbsent(2, "test2") 135 | if myMap.Count() != 2 { 136 | t.Fatal("count should be 2") 137 | } 138 | } 139 | 140 | func TestIsEmpty(t *testing.T) { 141 | myMap := csmap.New[int, string]() 142 | if !myMap.IsEmpty() { 143 | t.Fatal("map should be empty") 144 | } 145 | } 146 | 147 | func TestRangeStop(t *testing.T) { 148 | myMap := csmap.New[int, string]( 149 | csmap.WithShardCount[int, string](1), 150 | ) 151 | myMap.SetIfAbsent(1, "test") 152 | myMap.SetIfAbsent(2, "test2") 153 | myMap.SetIfAbsent(3, "test2") 154 | total := 0 155 | myMap.Range(func(key int, value string) (stop bool) { 156 | total++ 157 | return true 158 | }) 159 | if total != 1 { 160 | t.Fatal("total should be 1") 161 | } 162 | } 163 | 164 | func TestRange(t *testing.T) { 165 | myMap := csmap.New[int, string]() 166 | myMap.SetIfAbsent(1, "test") 167 | myMap.SetIfAbsent(2, "test2") 168 | total := 0 169 | myMap.Range(func(key int, value string) (stop bool) { 170 | total++ 171 | return 172 | }) 173 | if total != 2 { 174 | t.Fatal("total should be 2") 175 | } 176 | } 177 | 178 | func TestCustomHasherWithRange(t *testing.T) { 179 | myMap := csmap.New[int, string]( 180 | csmap.WithCustomHasher[int, string](func(key int) uint64 { 181 | return 0 182 | }), 183 | ) 184 | myMap.SetIfAbsent(1, "test") 185 | myMap.SetIfAbsent(2, "test2") 186 | myMap.SetIfAbsent(3, "test2") 187 | myMap.SetIfAbsent(4, "test2") 188 | total := 0 189 | myMap.Range(func(key int, value string) (stop bool) { 190 | total++ 191 | return true 192 | }) 193 | if total != 1 { 194 | t.Fatal("total should be 1, because currently range stops current shard only.") 195 | } 196 | } 197 | 198 | func TestDeleteFromRange(t *testing.T) { 199 | myMap := csmap.New[string, int]( 200 | csmap.WithSize[string, int](1024), 201 | ) 202 | 203 | myMap.Store("aaa", 10) 204 | myMap.Store("aab", 11) 205 | myMap.Store("aac", 15) 206 | myMap.Store("aad", 124) 207 | myMap.Store("aaf", 987) 208 | 209 | myMap.Range(func(key string, value int) (stop bool) { 210 | if value > 20 { 211 | myMap.Delete(key) 212 | } 213 | return false 214 | }) 215 | if myMap.Count() != 3 { 216 | t.Fatal("total should be 3, because currently range deletes values that bigger than 20.") 217 | } 218 | } 219 | 220 | func TestMarshal(t *testing.T) { 221 | myMap := csmap.New[string, int]( 222 | csmap.WithSize[string, int](1024), 223 | ) 224 | 225 | myMap.Store("aaa", 10) 226 | myMap.Store("aab", 11) 227 | 228 | b, _ := myMap.MarshalJSON() 229 | 230 | newMap := csmap.New[string, int]( 231 | csmap.WithSize[string, int](1024), 232 | ) 233 | 234 | _ = newMap.UnmarshalJSON(b) 235 | 236 | if myMap.Count() != 2 || !myMap.Has("aaa") || !myMap.Has("aab") { 237 | t.Fatal("count should be 2 after unmarshal") 238 | } 239 | } 240 | 241 | func TestBasicConcurrentWriteDeleteCount(t *testing.T) { 242 | myMap := csmap.New[int, string]( 243 | csmap.WithShardCount[int, string](32), 244 | csmap.WithSize[int, string](1000), 245 | ) 246 | 247 | var wg sync.WaitGroup 248 | wg.Add(1000000) 249 | for i := 0; i < 1000000; i++ { 250 | i := i 251 | go func() { 252 | defer wg.Done() 253 | myMap.Store(i, strconv.Itoa(i)) 254 | }() 255 | } 256 | wg.Wait() 257 | wg.Add(1000000) 258 | for i := 0; i < 1000000; i++ { 259 | i := i 260 | go func() { 261 | defer wg.Done() 262 | if !myMap.Has(i) { 263 | t.Error(strconv.Itoa(i) + " should exist") 264 | return 265 | } 266 | }() 267 | } 268 | 269 | wg.Wait() 270 | wg.Add(1000000) 271 | 272 | for i := 0; i < 1000000; i++ { 273 | i := i 274 | go func() { 275 | defer wg.Done() 276 | myMap.Delete(i) 277 | }() 278 | } 279 | 280 | wg.Wait() 281 | wg.Add(1000000) 282 | 283 | for i := 0; i < 1000000; i++ { 284 | i := i 285 | go func() { 286 | defer wg.Done() 287 | if myMap.Has(i) { 288 | t.Error(strconv.Itoa(i) + " should not exist") 289 | return 290 | } 291 | }() 292 | } 293 | 294 | wg.Wait() 295 | } 296 | 297 | func TestClear(t *testing.T) { 298 | myMap := csmap.New[int, string]() 299 | loop := 10000 300 | for i := 0; i < loop; i++ { 301 | myMap.Store(i, "test") 302 | } 303 | 304 | myMap.Clear() 305 | 306 | if !myMap.IsEmpty() { 307 | t.Fatal("count should be true") 308 | } 309 | 310 | // store again 311 | for i := 0; i < loop; i++ { 312 | myMap.Store(i, "test") 313 | } 314 | 315 | // get again 316 | for i := 0; i < loop; i++ { 317 | val, ok := myMap.Load(i) 318 | if ok != true { 319 | t.Fatal("ok should be true") 320 | } 321 | 322 | if val != "test" { 323 | t.Fatal("val should be test") 324 | } 325 | } 326 | 327 | // check again 328 | count := myMap.Count() 329 | if count != loop { 330 | t.Fatal("count should be 1000") 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /example/base/base.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "hash/fnv" 5 | 6 | csmap "github.com/mhmtszr/concurrent-swiss-map" 7 | ) 8 | 9 | func main() { 10 | myMap := csmap.New[string, int]( 11 | // set the number of map shards. the default value is 32. 12 | csmap.WithShardCount[string, int](32), 13 | 14 | // if don't set custom hasher, use the built-in maphash. 15 | csmap.WithCustomHasher[string, int](func(key string) uint64 { 16 | hash := fnv.New64a() 17 | hash.Write([]byte(key)) 18 | return hash.Sum64() 19 | }), 20 | 21 | // set the total capacity, every shard map has total capacity/shard count capacity. the default value is 0. 22 | csmap.WithSize[string, int](1000), 23 | ) 24 | 25 | key := "swiss-map" 26 | myMap.Store(key, 10) 27 | 28 | val, ok := myMap.Load(key) 29 | println("load val:", val, "exists:", ok) 30 | 31 | deleted := myMap.Delete(key) 32 | println("deleted:", deleted) 33 | 34 | ok = myMap.Has(key) 35 | println("has:", ok) 36 | 37 | empty := myMap.IsEmpty() 38 | println("empty:", empty) 39 | 40 | myMap.SetIfAbsent(key, 11) 41 | 42 | myMap.Range(func(key string, value int) (stop bool) { 43 | println("range:", key, value) 44 | return true 45 | }) 46 | 47 | count := myMap.Count() 48 | println("count:", count) 49 | 50 | // Output: 51 | // load val: 10 exists: true 52 | // deleted: true 53 | // has: false 54 | // empty: true 55 | // range: swiss-map 11 56 | // count: 1 57 | } 58 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mhmtszr/concurrent-swiss-map 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhmtszr/concurrent-swiss-map/726f60ce3da7081874637600f490ae72cdf7e003/go.sum -------------------------------------------------------------------------------- /img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhmtszr/concurrent-swiss-map/726f60ce3da7081874637600f490ae72cdf7e003/img.png -------------------------------------------------------------------------------- /maphash/.gitignore: -------------------------------------------------------------------------------- 1 | *.idea 2 | *.test -------------------------------------------------------------------------------- /maphash/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /maphash/README.md: -------------------------------------------------------------------------------- 1 | # maphash 2 | 3 | Hash any `comparable` type using Golang's fast runtime hash. 4 | Uses [AES](https://en.wikipedia.org/wiki/AES_instruction_set) instructions when available. -------------------------------------------------------------------------------- /maphash/hasher.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Dolthub, 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 maphash 16 | 17 | import "unsafe" 18 | 19 | // Hasher hashes values of type K. 20 | // Uses runtime AES-based hashing. 21 | type Hasher[K comparable] struct { 22 | hash hashfn 23 | seed uintptr 24 | } 25 | 26 | // NewHasher creates a new Hasher[K] with a random seed. 27 | func NewHasher[K comparable]() Hasher[K] { 28 | return Hasher[K]{ 29 | hash: getRuntimeHasher[K](), 30 | seed: newHashSeed(), 31 | } 32 | } 33 | 34 | // NewSeed returns a copy of |h| with a new hash seed. 35 | func NewSeed[K comparable](h Hasher[K]) Hasher[K] { 36 | return Hasher[K]{ 37 | hash: h.hash, 38 | seed: newHashSeed(), 39 | } 40 | } 41 | 42 | // Hash hashes |key|. 43 | func (h Hasher[K]) Hash(key K) uint64 { 44 | // promise to the compiler that pointer 45 | // |p| does not escape the stack. 46 | p := noescape(unsafe.Pointer(&key)) 47 | return uint64(h.hash(p, h.seed)) 48 | } 49 | -------------------------------------------------------------------------------- /maphash/runtime.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Dolthub, 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 | // This file incorporates work covered by the following copyright and 16 | // permission notice: 17 | // 18 | // Copyright 2022 The Go Authors. All rights reserved. 19 | // Use of this source code is governed by a BSD-style 20 | // license that can be found in the LICENSE file. 21 | 22 | //go:build go1.18 || go1.19 23 | // +build go1.18 go1.19 24 | 25 | package maphash 26 | 27 | import ( 28 | "math/rand" 29 | "unsafe" 30 | ) 31 | 32 | type hashfn func(unsafe.Pointer, uintptr) uintptr 33 | 34 | func getRuntimeHasher[K comparable]() (h hashfn) { 35 | a := any(make(map[K]struct{})) 36 | i := (*mapiface)(unsafe.Pointer(&a)) 37 | h = i.typ.hasher 38 | return 39 | } 40 | 41 | //nolint:gosec 42 | var hashSeed = rand.Int() 43 | 44 | func newHashSeed() uintptr { 45 | return uintptr(hashSeed) 46 | } 47 | 48 | // noescape hides a pointer from escape analysis. It is the identity function 49 | // but escape analysis doesn't think the output depends on the input. 50 | // noescape is inlined and currently compiles down to zero instructions. 51 | // USE CAREFULLY! 52 | // This was copied from the runtime (via pkg "strings"); see issues 23382 and 7921. 53 | // 54 | //go:nosplit 55 | //go:nocheckptr 56 | //nolint:staticcheck 57 | func noescape(p unsafe.Pointer) unsafe.Pointer { 58 | x := uintptr(p) 59 | return unsafe.Pointer(x ^ 0) 60 | } 61 | 62 | type mapiface struct { 63 | typ *maptype 64 | val *hmap 65 | } 66 | 67 | // go/src/runtime/type.go 68 | type maptype struct { 69 | typ _type 70 | key *_type 71 | elem *_type 72 | bucket *_type 73 | // function for hashing keys (ptr to key, seed) -> hash 74 | hasher func(unsafe.Pointer, uintptr) uintptr 75 | keysize uint8 76 | elemsize uint8 77 | bucketsize uint16 78 | flags uint32 79 | } 80 | 81 | // go/src/runtime/map.go 82 | type hmap struct { 83 | count int 84 | flags uint8 85 | B uint8 86 | noverflow uint16 87 | // hash seed 88 | hash0 uint32 89 | buckets unsafe.Pointer 90 | oldbuckets unsafe.Pointer 91 | nevacuate uintptr 92 | // true type is *mapextra 93 | // but we don't need this data 94 | extra unsafe.Pointer 95 | } 96 | 97 | // go/src/runtime/type.go 98 | type ( 99 | tflag uint8 100 | nameOff int32 101 | typeOff int32 102 | ) 103 | 104 | // go/src/runtime/type.go 105 | type _type struct { 106 | size uintptr 107 | ptrdata uintptr 108 | hash uint32 109 | tflag tflag 110 | align uint8 111 | fieldAlign uint8 112 | kind uint8 113 | equal func(unsafe.Pointer, unsafe.Pointer) bool 114 | gcdata *byte 115 | str nameOff 116 | ptrToThis typeOff 117 | } 118 | -------------------------------------------------------------------------------- /swiss/.gitignore: -------------------------------------------------------------------------------- 1 | **/.idea/ 2 | .vscode 3 | .run 4 | venv 5 | .DS_Store -------------------------------------------------------------------------------- /swiss/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /swiss/README.md: -------------------------------------------------------------------------------- 1 | # swiss 2 | Golang port of Abseil's flat_hash_map 3 | -------------------------------------------------------------------------------- /swiss/bits.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Dolthub, 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 | //go:build !amd64 || nosimd 15 | 16 | //nolint:all 17 | 18 | package swiss 19 | 20 | import ( 21 | "math/bits" 22 | "unsafe" 23 | ) 24 | 25 | const ( 26 | groupSize = 8 27 | maxAvgGroupLoad = 7 28 | 29 | loBits uint64 = 0x0101010101010101 30 | hiBits uint64 = 0x8080808080808080 31 | ) 32 | 33 | type bitset uint64 34 | 35 | func metaMatchH2(m *metadata, h h2) bitset { 36 | // https://graphics.stanford.edu/~seander/bithacks.html##ValueInWord 37 | return hasZeroByte(castUint64(m) ^ (loBits * uint64(h))) 38 | } 39 | 40 | func metaMatchEmpty(m *metadata) bitset { 41 | return hasZeroByte(castUint64(m) ^ hiBits) 42 | } 43 | 44 | func nextMatch(b *bitset) uint32 { 45 | s := uint32(bits.TrailingZeros64(uint64(*b))) 46 | *b &= ^(1 << s) // clear bit |s| 47 | return s >> 3 // div by 8 48 | } 49 | 50 | func hasZeroByte(x uint64) bitset { 51 | return bitset(((x - loBits) & ^(x)) & hiBits) 52 | } 53 | 54 | func castUint64(m *metadata) uint64 { 55 | return *(*uint64)((unsafe.Pointer)(m)) 56 | } 57 | 58 | //go:linkname fastrand runtime.fastrand 59 | func fastrand() uint32 60 | -------------------------------------------------------------------------------- /swiss/bits_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Dolthub, 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 | //nolint:all 15 | //go:build amd64 && !nosimd 16 | 17 | package swiss 18 | 19 | import ( 20 | "github.com/mhmtszr/concurrent-swiss-map/swiss/simd" 21 | "math/bits" 22 | _ "unsafe" 23 | ) 24 | 25 | const ( 26 | groupSize = 16 27 | maxAvgGroupLoad = 14 28 | ) 29 | 30 | type bitset uint16 31 | 32 | //nolint:all 33 | func metaMatchH2(m *metadata, h h2) bitset { 34 | b := simd.MatchMetadata((*[16]int8)(m), int8(h)) 35 | return bitset(b) 36 | } 37 | 38 | //nolint:all 39 | func metaMatchEmpty(m *metadata) bitset { 40 | b := simd.MatchMetadata((*[16]int8)(m), empty) 41 | return bitset(b) 42 | } 43 | 44 | //nolint:all 45 | func nextMatch(b *bitset) (s uint32) { 46 | s = uint32(bits.TrailingZeros16(uint16(*b))) 47 | *b &= ^(1 << s) // clear bit |s| 48 | return 49 | } 50 | 51 | //go:linkname fastrand runtime.fastrand 52 | func fastrand() uint32 53 | -------------------------------------------------------------------------------- /swiss/map.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Dolthub, 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 swiss 16 | 17 | import ( 18 | "github.com/mhmtszr/concurrent-swiss-map/maphash" 19 | ) 20 | 21 | const ( 22 | maxLoadFactor = float32(maxAvgGroupLoad) / float32(groupSize) 23 | ) 24 | 25 | // Map is an open-addressing hash map 26 | // based on Abseil's flat_hash_map. 27 | type Map[K comparable, V any] struct { 28 | ctrl []metadata 29 | groups []group[K, V] 30 | hash maphash.Hasher[K] 31 | resident uint32 32 | dead uint32 33 | limit uint32 34 | } 35 | 36 | // metadata is the h2 metadata array for a group. 37 | // find operations first probe the controls bytes 38 | // to filter candidates before matching keys 39 | type metadata [groupSize]int8 40 | 41 | // group is a group of 16 key-value pairs 42 | type group[K comparable, V any] struct { 43 | keys [groupSize]K 44 | values [groupSize]V 45 | } 46 | 47 | const ( 48 | h1Mask uint64 = 0xffff_ffff_ffff_ff80 49 | h2Mask uint64 = 0x0000_0000_0000_007f 50 | empty int8 = -128 // 0b1000_0000 51 | tombstone int8 = -2 // 0b1111_1110 52 | ) 53 | 54 | // h1 is a 57 bit hash prefix 55 | type h1 uint64 56 | 57 | // h2 is a 7 bit hash suffix 58 | type h2 int8 59 | 60 | // NewMap constructs a Map. 61 | func NewMap[K comparable, V any](sz uint32) (m *Map[K, V]) { 62 | groups := numGroups(sz) 63 | m = &Map[K, V]{ 64 | ctrl: make([]metadata, groups), 65 | groups: make([]group[K, V], groups), 66 | hash: maphash.NewHasher[K](), 67 | limit: groups * maxAvgGroupLoad, 68 | } 69 | for i := range m.ctrl { 70 | m.ctrl[i] = newEmptyMetadata() 71 | } 72 | return 73 | } 74 | 75 | func (m *Map[K, V]) HasWithHash(key K, hash uint64) (ok bool) { 76 | hi, lo := splitHash(hash) 77 | g := probeStart(hi, len(m.groups)) 78 | for { // inlined find loop 79 | matches := metaMatchH2(&m.ctrl[g], lo) 80 | for matches != 0 { 81 | s := nextMatch(&matches) 82 | if key == m.groups[g].keys[s] { 83 | ok = true 84 | return 85 | } 86 | } 87 | // |key| is not in group |g|, 88 | // stop probing if we see an empty slot 89 | matches = metaMatchEmpty(&m.ctrl[g]) 90 | if matches != 0 { 91 | ok = false 92 | return 93 | } 94 | g++ // linear probing 95 | if g >= uint32(len(m.groups)) { 96 | g = 0 97 | } 98 | } 99 | } 100 | 101 | func (m *Map[K, V]) GetWithHash(key K, hash uint64) (value V, ok bool) { 102 | hi, lo := splitHash(hash) 103 | g := probeStart(hi, len(m.groups)) 104 | for { // inlined find loop 105 | matches := metaMatchH2(&m.ctrl[g], lo) 106 | for matches != 0 { 107 | s := nextMatch(&matches) 108 | if key == m.groups[g].keys[s] { 109 | value, ok = m.groups[g].values[s], true 110 | return 111 | } 112 | } 113 | // |key| is not in group |g|, 114 | // stop probing if we see an empty slot 115 | matches = metaMatchEmpty(&m.ctrl[g]) 116 | if matches != 0 { 117 | ok = false 118 | return 119 | } 120 | g++ // linear probing 121 | if g >= uint32(len(m.groups)) { 122 | g = 0 123 | } 124 | } 125 | } 126 | 127 | // Put attempts to insert |key| and |value| 128 | func (m *Map[K, V]) Put(key K, value V) { 129 | if m.resident >= m.limit { 130 | m.rehash(m.nextSize()) 131 | } 132 | hi, lo := splitHash(m.hash.Hash(key)) 133 | g := probeStart(hi, len(m.groups)) 134 | for { // inlined find loop 135 | matches := metaMatchH2(&m.ctrl[g], lo) 136 | for matches != 0 { 137 | s := nextMatch(&matches) 138 | if key == m.groups[g].keys[s] { // update 139 | m.groups[g].keys[s] = key 140 | m.groups[g].values[s] = value 141 | return 142 | } 143 | } 144 | // |key| is not in group |g|, 145 | // stop probing if we see an empty slot 146 | matches = metaMatchEmpty(&m.ctrl[g]) 147 | if matches != 0 { // insert 148 | s := nextMatch(&matches) 149 | m.groups[g].keys[s] = key 150 | m.groups[g].values[s] = value 151 | m.ctrl[g][s] = int8(lo) 152 | m.resident++ 153 | return 154 | } 155 | g++ // linear probing 156 | if g >= uint32(len(m.groups)) { 157 | g = 0 158 | } 159 | } 160 | } 161 | 162 | // Put attempts to insert |key| and |value| 163 | func (m *Map[K, V]) PutWithHash(key K, value V, hash uint64) { 164 | if m.resident >= m.limit { 165 | m.rehash(m.nextSize()) 166 | } 167 | hi, lo := splitHash(hash) 168 | g := probeStart(hi, len(m.groups)) 169 | for { // inlined find loop 170 | matches := metaMatchH2(&m.ctrl[g], lo) 171 | for matches != 0 { 172 | s := nextMatch(&matches) 173 | if key == m.groups[g].keys[s] { // update 174 | m.groups[g].keys[s] = key 175 | m.groups[g].values[s] = value 176 | return 177 | } 178 | } 179 | // |key| is not in group |g|, 180 | // stop probing if we see an empty slot 181 | matches = metaMatchEmpty(&m.ctrl[g]) 182 | if matches != 0 { // insert 183 | s := nextMatch(&matches) 184 | m.groups[g].keys[s] = key 185 | m.groups[g].values[s] = value 186 | m.ctrl[g][s] = int8(lo) 187 | m.resident++ 188 | return 189 | } 190 | g++ // linear probing 191 | if g >= uint32(len(m.groups)) { 192 | g = 0 193 | } 194 | } 195 | } 196 | 197 | func (m *Map[K, V]) DeleteWithHash(key K, hash uint64) (ok bool) { 198 | hi, lo := splitHash(hash) 199 | g := probeStart(hi, len(m.groups)) 200 | for { 201 | matches := metaMatchH2(&m.ctrl[g], lo) 202 | for matches != 0 { 203 | s := nextMatch(&matches) 204 | if key == m.groups[g].keys[s] { 205 | ok = true 206 | // optimization: if |m.ctrl[g]| contains any empty 207 | // metadata bytes, we can physically delete |key| 208 | // rather than placing a tombstone. 209 | // The observation is that any probes into group |g| 210 | // would already be terminated by the existing empty 211 | // slot, and therefore reclaiming slot |s| will not 212 | // cause premature termination of probes into |g|. 213 | if metaMatchEmpty(&m.ctrl[g]) != 0 { 214 | m.ctrl[g][s] = empty 215 | m.resident-- 216 | } else { 217 | m.ctrl[g][s] = tombstone 218 | m.dead++ 219 | } 220 | var k K 221 | var v V 222 | m.groups[g].keys[s] = k 223 | m.groups[g].values[s] = v 224 | return 225 | } 226 | } 227 | // |key| is not in group |g|, 228 | // stop probing if we see an empty slot 229 | matches = metaMatchEmpty(&m.ctrl[g]) 230 | if matches != 0 { // |key| absent 231 | ok = false 232 | return 233 | } 234 | g++ // linear probing 235 | if g >= uint32(len(m.groups)) { 236 | g = 0 237 | } 238 | } 239 | } 240 | 241 | // Clear removes all elements from the Map. 242 | func (m *Map[K, V]) Clear() { 243 | for i, c := range m.ctrl { 244 | for j := range c { 245 | m.ctrl[i][j] = empty 246 | } 247 | } 248 | var k K 249 | var v V 250 | for i := range m.groups { 251 | g := &m.groups[i] 252 | for i := range g.keys { 253 | g.keys[i] = k 254 | g.values[i] = v 255 | } 256 | } 257 | m.resident, m.dead = 0, 0 258 | } 259 | 260 | // Iter iterates the elements of the Map, passing them to the callback. 261 | // It guarantees that any key in the Map will be visited only once, and 262 | // for un-mutated Maps, every key will be visited once. If the Map is 263 | // Mutated during iteration, mutations will be reflected on return from 264 | // Iter, but the set of keys visited by Iter is non-deterministic. 265 | // 266 | //nolint:gosec 267 | func (m *Map[K, V]) Iter(cb func(k K, v V) (stop bool)) bool { 268 | // take a consistent view of the table in case 269 | // we rehash during iteration 270 | ctrl, groups := m.ctrl, m.groups 271 | // pick a random starting group 272 | g := randIntN(len(groups)) 273 | for n := 0; n < len(groups); n++ { 274 | for s, c := range ctrl[g] { 275 | if c == empty || c == tombstone { 276 | continue 277 | } 278 | k, v := groups[g].keys[s], groups[g].values[s] 279 | if stop := cb(k, v); stop { 280 | return stop 281 | } 282 | } 283 | g++ 284 | if g >= uint32(len(groups)) { 285 | g = 0 286 | } 287 | } 288 | return false 289 | } 290 | 291 | // Count returns the number of elements in the Map. 292 | func (m *Map[K, V]) Count() int { 293 | return int(m.resident - m.dead) 294 | } 295 | 296 | func (m *Map[K, V]) nextSize() (n uint32) { 297 | n = uint32(len(m.groups)) * 2 298 | if m.dead >= (m.resident / 2) { 299 | n = uint32(len(m.groups)) 300 | } 301 | return 302 | } 303 | 304 | func (m *Map[K, V]) rehash(n uint32) { 305 | groups, ctrl := m.groups, m.ctrl 306 | m.groups = make([]group[K, V], n) 307 | m.ctrl = make([]metadata, n) 308 | for i := range m.ctrl { 309 | m.ctrl[i] = newEmptyMetadata() 310 | } 311 | m.hash = maphash.NewSeed(m.hash) 312 | m.limit = n * maxAvgGroupLoad 313 | m.resident, m.dead = 0, 0 314 | for g := range ctrl { 315 | for s := range ctrl[g] { 316 | c := ctrl[g][s] 317 | if c == empty || c == tombstone { 318 | continue 319 | } 320 | m.Put(groups[g].keys[s], groups[g].values[s]) 321 | } 322 | } 323 | } 324 | 325 | // numGroups returns the minimum number of groups needed to store |n| elems. 326 | func numGroups(n uint32) (groups uint32) { 327 | groups = (n + maxAvgGroupLoad - 1) / maxAvgGroupLoad 328 | if groups == 0 { 329 | groups = 1 330 | } 331 | return 332 | } 333 | 334 | func newEmptyMetadata() (meta metadata) { 335 | for i := range meta { 336 | meta[i] = empty 337 | } 338 | return 339 | } 340 | 341 | func splitHash(h uint64) (h1, h2) { 342 | return h1((h & h1Mask) >> 7), h2(h & h2Mask) 343 | } 344 | 345 | func probeStart(hi h1, groups int) uint32 { 346 | return fastModN(uint32(hi), uint32(groups)) 347 | } 348 | 349 | // lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ 350 | func fastModN(x, n uint32) uint32 { 351 | return uint32((uint64(x) * uint64(n)) >> 32) 352 | } 353 | 354 | // randIntN returns a random number in the interval [0, n). 355 | func randIntN(n int) uint32 { 356 | return fastModN(fastrand(), uint32(n)) 357 | } 358 | -------------------------------------------------------------------------------- /swiss/simd/match.s: -------------------------------------------------------------------------------- 1 | // Code generated by command: go run asm.go -out match.s -stubs match_amd64.go. DO NOT EDIT. 2 | //nolint 3 | //go:build amd64 4 | 5 | #include "textflag.h" 6 | 7 | // func MatchMetadata(metadata *[16]int8, hash int8) uint16 8 | // Requires: SSE2, SSSE3 9 | TEXT ·MatchMetadata(SB), NOSPLIT, $0-18 10 | MOVQ metadata+0(FP), AX 11 | MOVBLSX hash+8(FP), CX 12 | MOVD CX, X0 13 | PXOR X1, X1 14 | PSHUFB X1, X0 15 | MOVOU (AX), X1 16 | PCMPEQB X1, X0 17 | PMOVMSKB X0, AX 18 | MOVW AX, ret+16(FP) 19 | RET 20 | -------------------------------------------------------------------------------- /swiss/simd/match_amd64.go: -------------------------------------------------------------------------------- 1 | // Code generated by command: go run asm.go -out match.s -stubs match_amd64.go. DO NOT EDIT. 2 | //nolint:all 3 | //go:build amd64 4 | 5 | package simd 6 | 7 | // MatchMetadata performs a 16-way probe of |metadata| using SSE instructions 8 | // nb: |metadata| must be an aligned pointer 9 | func MatchMetadata(metadata *[16]int8, hash int8) uint16 10 | --------------------------------------------------------------------------------