[performance] update go-structr and go-mutexes with memory usage improvements (#2909)
* update go-structr and go-mutexes with memory usage improvements * bump to go-structr v0.8.4
This commit is contained in:
parent
578a4e0cf5
commit
c06e6fb656
11
go.mod
11
go.mod
|
@ -1,11 +1,9 @@
|
|||
module github.com/superseriousbusiness/gotosocial
|
||||
|
||||
go 1.22
|
||||
go 1.22.2
|
||||
|
||||
replace modernc.org/sqlite => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.29.9-concurrency-workaround
|
||||
|
||||
toolchain go1.22.2
|
||||
|
||||
require (
|
||||
codeberg.org/gruf/go-bytes v1.0.2
|
||||
codeberg.org/gruf/go-bytesize v1.0.2
|
||||
|
@ -18,11 +16,12 @@ require (
|
|||
codeberg.org/gruf/go-kv v1.6.4
|
||||
codeberg.org/gruf/go-list v0.0.0-20240425093752-494db03d641f
|
||||
codeberg.org/gruf/go-logger/v2 v2.2.1
|
||||
codeberg.org/gruf/go-mutexes v1.4.1
|
||||
codeberg.org/gruf/go-mempool v0.0.0-20240507125005-cef10d64a760
|
||||
codeberg.org/gruf/go-mutexes v1.5.0
|
||||
codeberg.org/gruf/go-runners v1.6.2
|
||||
codeberg.org/gruf/go-sched v1.2.3
|
||||
codeberg.org/gruf/go-store/v2 v2.2.4
|
||||
codeberg.org/gruf/go-structr v0.8.2
|
||||
codeberg.org/gruf/go-structr v0.8.4
|
||||
codeberg.org/superseriousbusiness/exif-terminator v0.7.0
|
||||
github.com/DmitriyVTitov/size v1.5.0
|
||||
github.com/KimMachineGun/automemlimit v0.6.0
|
||||
|
@ -107,6 +106,8 @@ require (
|
|||
github.com/cornelk/hashmap v1.0.8 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/dolthub/maphash v0.1.0 // indirect
|
||||
github.com/dolthub/swiss v0.2.1 // indirect
|
||||
github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b // indirect
|
||||
github.com/dsoprea/go-iptc v0.0.0-20200610044640-bc9ca208b413 // indirect
|
||||
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
|
||||
|
|
14
go.sum
14
go.sum
|
@ -66,16 +66,18 @@ codeberg.org/gruf/go-mangler v1.3.0 h1:cf0vuuLJuEhoIukPHj+MUBIQSWxZcfEYt2Eo/r7Rs
|
|||
codeberg.org/gruf/go-mangler v1.3.0/go.mod h1:jnOA76AQoaO2kTHi0DlTTVaFYfRM+9fzs8f4XO6MsOk=
|
||||
codeberg.org/gruf/go-maps v1.0.3 h1:VDwhnnaVNUIy5O93CvkcE2IZXnMB1+IJjzfop9V12es=
|
||||
codeberg.org/gruf/go-maps v1.0.3/go.mod h1:D5LNDxlC9rsDuVQVM6JObaVGAdHB6g2dTdOdkh1aXWA=
|
||||
codeberg.org/gruf/go-mutexes v1.4.1 h1:SgsuktbbrkKYmgZ1reA5jMGEZbXJ6GQ54fSlKRN5iug=
|
||||
codeberg.org/gruf/go-mutexes v1.4.1/go.mod h1:1j/6/MBeBQUedAtAtysLLnBKogfOZAxdym0E3wlaBD8=
|
||||
codeberg.org/gruf/go-mempool v0.0.0-20240507125005-cef10d64a760 h1:m2/UCRXhjDwAg4vyji6iKCpomKw6P4PmBOUi5DvAMH4=
|
||||
codeberg.org/gruf/go-mempool v0.0.0-20240507125005-cef10d64a760/go.mod h1:E3RcaCFNq4zXpvaJb8lfpPqdUAmSkP5F1VmMiEUYTEk=
|
||||
codeberg.org/gruf/go-mutexes v1.5.0 h1:kDegqA/FYQhcn294zUJ3U3VBegfvhtcI7ObcAku1zkw=
|
||||
codeberg.org/gruf/go-mutexes v1.5.0/go.mod h1:rPEqQ/y6CmGITaZ3GPTMQVsoZAOzbsAHyIaLsJcOqVE=
|
||||
codeberg.org/gruf/go-runners v1.6.2 h1:oQef9niahfHu/wch14xNxlRMP8i+ABXH1Cb9PzZ4oYo=
|
||||
codeberg.org/gruf/go-runners v1.6.2/go.mod h1:Tq5PrZ/m/rBXbLZz0u5if+yP3nG5Sf6S8O/GnyEePeQ=
|
||||
codeberg.org/gruf/go-sched v1.2.3 h1:H5ViDxxzOBR3uIyGBCf0eH8b1L8wMybOXcdtUUTXZHk=
|
||||
codeberg.org/gruf/go-sched v1.2.3/go.mod h1:vT9uB6KWFIIwnG9vcPY2a0alYNoqdL1mSzRM8I+PK7A=
|
||||
codeberg.org/gruf/go-store/v2 v2.2.4 h1:8HO1Jh2gg7boQKA3hsDAIXd9zwieu5uXwDXEcTOD9js=
|
||||
codeberg.org/gruf/go-store/v2 v2.2.4/go.mod h1:zI4VWe5CpXAktYMtaBMrgA5QmO0sQH53LBRvfn1huys=
|
||||
codeberg.org/gruf/go-structr v0.8.2 h1:0zH5HuOZWTVOGqIq8o5W1jRi944CQWdPXUWZfKUbF0o=
|
||||
codeberg.org/gruf/go-structr v0.8.2/go.mod h1:K1FXkUyO6N/JKt8aWqyQ8rtW7Z9ZmXKWP8mFAQ2OJjE=
|
||||
codeberg.org/gruf/go-structr v0.8.4 h1:2eT1VOTWG6T9gIGZwF/1Jop6k6plvfdUY5yBcvbizVg=
|
||||
codeberg.org/gruf/go-structr v0.8.4/go.mod h1:c5UvVDSA3lZ1kv05V+7pXkO8u8Jea+VRWFDRFBCOxSA=
|
||||
codeberg.org/superseriousbusiness/exif-terminator v0.7.0 h1:Y6VApSXhKqExG0H2hZ2JelRK4xmWdjDQjn13CpEfzko=
|
||||
codeberg.org/superseriousbusiness/exif-terminator v0.7.0/go.mod h1:gCWKduudUWFzsnixoMzu0FYVdxHWG+AbXnZ50DqxsUE=
|
||||
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||
|
@ -148,6 +150,10 @@ github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1
|
|||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/dolthub/maphash v0.1.0 h1:bsQ7JsF4FkkWyrP3oCnFJgrCUAFbFf3kOl4L/QxPDyQ=
|
||||
github.com/dolthub/maphash v0.1.0/go.mod h1:gkg4Ch4CdCDu5h6PMriVLawB7koZ+5ijb9puGMV50a4=
|
||||
github.com/dolthub/swiss v0.2.1 h1:gs2osYs5SJkAaH5/ggVJqXQxRXtWshF6uE0lgR/Y3Gw=
|
||||
github.com/dolthub/swiss v0.2.1/go.mod h1:8AhKZZ1HK7g18j7v7k6c5cYIGEZJcPn0ARsai8cUrh0=
|
||||
github.com/dsoprea/go-exif/v2 v2.0.0-20200321225314-640175a69fe4/go.mod h1:Lm2lMM2zx8p4a34ZemkaUV95AnMl4ZvLbCUbwOvLC2E=
|
||||
github.com/dsoprea/go-exif/v3 v3.0.0-20200717053412-08f1b6708903/go.mod h1:0nsO1ce0mh5czxGeLo4+OCZ/C6Eo6ZlMWsz7rH/Gxv8=
|
||||
github.com/dsoprea/go-exif/v3 v3.0.0-20210428042052-dca55bf8ca15/go.mod h1:cg5SNYKHMmzxsr9X6ZeLh/nfBRHHp5PngtEPcujONtk=
|
||||
|
|
|
@ -20,24 +20,20 @@ package queue
|
|||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"codeberg.org/gruf/go-list"
|
||||
"codeberg.org/gruf/go-mempool"
|
||||
)
|
||||
|
||||
// frequency of GC cycles
|
||||
// per no. unlocks. i.e.
|
||||
// every 'gcfreq' unlocks.
|
||||
const gcfreq = 1024
|
||||
|
||||
// SimpleQueue provides a simple concurrency safe
|
||||
// queue using generics and a memory pool of list
|
||||
// elements to reduce overall memory usage.
|
||||
type SimpleQueue[T any] struct {
|
||||
l list.List[T]
|
||||
p elemPool[T]
|
||||
p mempool.UnsafePool
|
||||
w chan struct{}
|
||||
m sync.Mutex
|
||||
n uint32 // pop counter (safely wraps around)
|
||||
}
|
||||
|
||||
// Push will push given value to the queue.
|
||||
|
@ -45,7 +41,7 @@ func (q *SimpleQueue[T]) Push(value T) {
|
|||
q.m.Lock()
|
||||
|
||||
// Wrap in element.
|
||||
elem := q.p.alloc()
|
||||
elem := q.acquire()
|
||||
elem.Value = value
|
||||
|
||||
// Push new elem to queue.
|
||||
|
@ -75,14 +71,7 @@ func (q *SimpleQueue[T]) Pop() (value T, ok bool) {
|
|||
|
||||
// Remove tail.
|
||||
q.l.Remove(tail)
|
||||
q.p.free(tail)
|
||||
|
||||
// Every 'gcfreq' pops perform
|
||||
// a garbage collection to keep
|
||||
// us squeaky clean :]
|
||||
if q.n++; q.n%gcfreq == 0 {
|
||||
q.p.GC()
|
||||
}
|
||||
q.release(tail)
|
||||
}
|
||||
|
||||
q.m.Unlock()
|
||||
|
@ -134,14 +123,7 @@ func (q *SimpleQueue[T]) PopCtx(ctx context.Context) (value T, ok bool) {
|
|||
|
||||
// Remove element.
|
||||
q.l.Remove(elem)
|
||||
q.p.free(elem)
|
||||
|
||||
// Every 'gcfreq' pops perform
|
||||
// a garbage collection to keep
|
||||
// us squeaky clean :]
|
||||
if q.n++; q.n%gcfreq == 0 {
|
||||
q.p.GC()
|
||||
}
|
||||
q.release(elem)
|
||||
|
||||
// Done with lock.
|
||||
q.m.Unlock()
|
||||
|
@ -157,45 +139,20 @@ func (q *SimpleQueue[T]) Len() int {
|
|||
return l
|
||||
}
|
||||
|
||||
// elemPool is a very simple
|
||||
// list.Elem[T] memory pool.
|
||||
type elemPool[T any] struct {
|
||||
current []*list.Elem[T]
|
||||
victim []*list.Elem[T]
|
||||
// acquire will acquire list elem from pool, else alloc new.
|
||||
func (q *SimpleQueue[T]) acquire() *list.Elem[T] {
|
||||
if ptr := q.p.Get(); ptr != nil {
|
||||
return (*list.Elem[T])(ptr)
|
||||
}
|
||||
return new(list.Elem[T])
|
||||
}
|
||||
|
||||
func (p *elemPool[T]) alloc() *list.Elem[T] {
|
||||
// First try the current queue
|
||||
if l := len(p.current) - 1; l >= 0 {
|
||||
mu := p.current[l]
|
||||
p.current = p.current[:l]
|
||||
return mu
|
||||
}
|
||||
|
||||
// Next try the victim queue.
|
||||
if l := len(p.victim) - 1; l >= 0 {
|
||||
mu := p.victim[l]
|
||||
p.victim = p.victim[:l]
|
||||
return mu
|
||||
}
|
||||
|
||||
// Lastly, alloc new.
|
||||
mu := new(list.Elem[T])
|
||||
return mu
|
||||
}
|
||||
|
||||
// free will release given element to pool.
|
||||
func (p *elemPool[T]) free(elem *list.Elem[T]) {
|
||||
// release will reset list elem and release to pool.
|
||||
func (q *SimpleQueue[T]) release(e *list.Elem[T]) {
|
||||
var zero T
|
||||
elem.Next = nil
|
||||
elem.Prev = nil
|
||||
elem.Value = zero
|
||||
p.current = append(p.current, elem)
|
||||
}
|
||||
|
||||
// GC will clear out unused entries from the elemPool.
|
||||
func (p *elemPool[T]) GC() {
|
||||
current := p.current
|
||||
p.current = nil
|
||||
p.victim = current
|
||||
e.Next = nil
|
||||
e.Prev = nil
|
||||
e.Value = zero
|
||||
ptr := unsafe.Pointer(e)
|
||||
q.p.Put(ptr)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) gruf
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,3 @@
|
|||
# go-mempool
|
||||
|
||||
very simple memory pool implementation
|
|
@ -0,0 +1,99 @@
|
|||
package mempool
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const DefaultDirtyFactor = 128
|
||||
|
||||
// Pool provides a type-safe form
|
||||
// of UnsafePool using generics.
|
||||
//
|
||||
// Note it is NOT safe for concurrent
|
||||
// use, you must protect it yourself!
|
||||
type Pool[T any] struct {
|
||||
|
||||
// New is an optionally provided
|
||||
// allocator used when no value
|
||||
// is available for use in pool.
|
||||
New func() T
|
||||
|
||||
// Reset is an optionally provided
|
||||
// value resetting function called
|
||||
// on passed value to Put().
|
||||
Reset func(T)
|
||||
|
||||
UnsafePool
|
||||
}
|
||||
|
||||
func (p *Pool[T]) Get() T {
|
||||
if ptr := p.UnsafePool.Get(); ptr != nil {
|
||||
return *(*T)(ptr)
|
||||
} else if p.New != nil {
|
||||
return p.New()
|
||||
}
|
||||
var z T
|
||||
return z
|
||||
}
|
||||
|
||||
func (p *Pool[T]) Put(t T) {
|
||||
if p.Reset != nil {
|
||||
p.Reset(t)
|
||||
}
|
||||
ptr := unsafe.Pointer(&t)
|
||||
p.UnsafePool.Put(ptr)
|
||||
}
|
||||
|
||||
// UnsafePool provides an incredibly
|
||||
// simple memory pool implementation
|
||||
// that stores ptrs to memory values,
|
||||
// and regularly flushes internal pool
|
||||
// structures according to DirtyFactor.
|
||||
//
|
||||
// Note it is NOT safe for concurrent
|
||||
// use, you must protect it yourself!
|
||||
type UnsafePool struct {
|
||||
|
||||
// DirtyFactor determines the max
|
||||
// number of $dirty count before
|
||||
// pool is garbage collected. Where:
|
||||
// $dirty = len(current) - len(victim)
|
||||
DirtyFactor int
|
||||
|
||||
current []unsafe.Pointer
|
||||
victim []unsafe.Pointer
|
||||
}
|
||||
|
||||
func (p *UnsafePool) Get() unsafe.Pointer {
|
||||
// First try current list.
|
||||
if len(p.current) > 0 {
|
||||
ptr := p.current[len(p.current)-1]
|
||||
p.current = p.current[:len(p.current)-1]
|
||||
return ptr
|
||||
}
|
||||
|
||||
// Fallback to victim.
|
||||
if len(p.victim) > 0 {
|
||||
ptr := p.victim[len(p.victim)-1]
|
||||
p.victim = p.victim[:len(p.victim)-1]
|
||||
return ptr
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *UnsafePool) Put(ptr unsafe.Pointer) {
|
||||
p.current = append(p.current, ptr)
|
||||
|
||||
// Get dirty factor.
|
||||
df := p.DirtyFactor
|
||||
if df == 0 {
|
||||
df = DefaultDirtyFactor
|
||||
}
|
||||
|
||||
if len(p.current)-len(p.victim) > df {
|
||||
// Garbage collection!
|
||||
p.victim = p.current
|
||||
p.current = nil
|
||||
}
|
||||
}
|
|
@ -3,17 +3,16 @@ package mutexes
|
|||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
"codeberg.org/gruf/go-mempool"
|
||||
"github.com/dolthub/swiss"
|
||||
)
|
||||
|
||||
const (
|
||||
// possible lock types.
|
||||
lockTypeRead = uint8(1) << 0
|
||||
lockTypeWrite = uint8(1) << 1
|
||||
|
||||
// frequency of GC cycles
|
||||
// per no. unlocks. i.e.
|
||||
// every 'gcfreq' unlocks.
|
||||
gcfreq = 1024
|
||||
)
|
||||
|
||||
// MutexMap is a structure that allows read / write locking
|
||||
|
@ -28,15 +27,15 @@ const (
|
|||
// like structures for sleeping / awaking awaiting goroutines.
|
||||
type MutexMap struct {
|
||||
mapmu sync.Mutex
|
||||
mumap map[string]*rwmutex
|
||||
mupool rwmutexPool
|
||||
count uint32
|
||||
mumap *swiss.Map[string, *rwmutex]
|
||||
mupool mempool.UnsafePool
|
||||
}
|
||||
|
||||
// checkInit ensures MutexMap is initialized (UNSAFE).
|
||||
func (mm *MutexMap) checkInit() {
|
||||
if mm.mumap == nil {
|
||||
mm.mumap = make(map[string]*rwmutex)
|
||||
mm.mumap = swiss.NewMap[string, *rwmutex](0)
|
||||
mm.mupool.DirtyFactor = 256
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -58,13 +57,13 @@ func (mm *MutexMap) lock(key string, lt uint8) func() {
|
|||
mm.checkInit()
|
||||
|
||||
for {
|
||||
// Check map for mu.
|
||||
mu := mm.mumap[key]
|
||||
// Check map for mutex.
|
||||
mu, _ := mm.mumap.Get(key)
|
||||
|
||||
if mu == nil {
|
||||
// Allocate new mutex.
|
||||
mu = mm.mupool.Acquire()
|
||||
mm.mumap[key] = mu
|
||||
// Allocate mutex.
|
||||
mu = mm.acquire()
|
||||
mm.mumap.Put(key, mu)
|
||||
}
|
||||
|
||||
if !mu.Lock(lt) {
|
||||
|
@ -87,63 +86,58 @@ func (mm *MutexMap) unlock(key string, mu *rwmutex) {
|
|||
mm.mapmu.Lock()
|
||||
|
||||
// Unlock mutex.
|
||||
if mu.Unlock() {
|
||||
if !mu.Unlock() {
|
||||
|
||||
// Fast path. Mutex still
|
||||
// used so no map change.
|
||||
mm.mapmu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Mutex fully unlocked
|
||||
// with zero waiters. Self
|
||||
// evict and release it.
|
||||
delete(mm.mumap, key)
|
||||
mm.mupool.Release(mu)
|
||||
}
|
||||
mm.mumap.Delete(key)
|
||||
mm.release(mu)
|
||||
|
||||
if mm.count++; mm.count%gcfreq == 0 {
|
||||
// Every 'gcfreq' unlocks perform
|
||||
// a garbage collection to keep
|
||||
// us squeaky clean :]
|
||||
mm.mupool.GC()
|
||||
// Maximum load factor before
|
||||
// 'swiss' allocates new hmap:
|
||||
// maxLoad = 7 / 8
|
||||
//
|
||||
// So we apply the inverse/2, once
|
||||
// $maxLoad/2 % of hmap is empty we
|
||||
// compact the map to drop buckets.
|
||||
len := mm.mumap.Count()
|
||||
cap := mm.mumap.Capacity()
|
||||
if cap-len > (cap*7)/(8*2) {
|
||||
|
||||
// Create a new map only as big as required.
|
||||
mumap := swiss.NewMap[string, *rwmutex](uint32(len))
|
||||
mm.mumap.Iter(func(k string, v *rwmutex) (stop bool) {
|
||||
mumap.Put(k, v)
|
||||
return false
|
||||
})
|
||||
|
||||
// Set new map.
|
||||
mm.mumap = mumap
|
||||
}
|
||||
|
||||
// Done with map.
|
||||
mm.mapmu.Unlock()
|
||||
}
|
||||
|
||||
// rwmutexPool is a very simply memory rwmutexPool.
|
||||
type rwmutexPool struct {
|
||||
current []*rwmutex
|
||||
victim []*rwmutex
|
||||
// acquire will acquire mutex from memory pool, or alloc new.
|
||||
func (mm *MutexMap) acquire() *rwmutex {
|
||||
if ptr := mm.mupool.Get(); ptr != nil {
|
||||
return (*rwmutex)(ptr)
|
||||
}
|
||||
return new(rwmutex)
|
||||
}
|
||||
|
||||
// Acquire will returns a rwmutexState from rwmutexPool (or alloc new).
|
||||
func (p *rwmutexPool) Acquire() *rwmutex {
|
||||
// First try the current queue
|
||||
if l := len(p.current) - 1; l >= 0 {
|
||||
mu := p.current[l]
|
||||
p.current = p.current[:l]
|
||||
return mu
|
||||
}
|
||||
|
||||
// Next try the victim queue.
|
||||
if l := len(p.victim) - 1; l >= 0 {
|
||||
mu := p.victim[l]
|
||||
p.victim = p.victim[:l]
|
||||
return mu
|
||||
}
|
||||
|
||||
// Lastly, alloc new.
|
||||
mu := new(rwmutex)
|
||||
return mu
|
||||
}
|
||||
|
||||
// Release places a sync.rwmutexState back in the rwmutexPool.
|
||||
func (p *rwmutexPool) Release(mu *rwmutex) {
|
||||
p.current = append(p.current, mu)
|
||||
}
|
||||
|
||||
// GC will clear out unused entries from the rwmutexPool.
|
||||
func (p *rwmutexPool) GC() {
|
||||
current := p.current
|
||||
p.current = nil
|
||||
p.victim = current
|
||||
// release will release given mutex to memory pool.
|
||||
func (mm *MutexMap) release(mu *rwmutex) {
|
||||
ptr := unsafe.Pointer(mu)
|
||||
mm.mupool.Put(ptr)
|
||||
}
|
||||
|
||||
// rwmutex represents a RW mutex when used correctly within
|
||||
|
|
|
@ -289,9 +289,8 @@ func (c *Cache[T]) LoadOne(index *Index, key Key, load func() (T, error)) (T, er
|
|||
// Load new result.
|
||||
val, err = load()
|
||||
|
||||
// Check for ignored
|
||||
// (transient) errors.
|
||||
if ignore(err) {
|
||||
// Check for ignored error types.
|
||||
if err != nil && ignore(err) {
|
||||
return val, err
|
||||
}
|
||||
|
||||
|
@ -536,9 +535,10 @@ func (c *Cache[T]) Debug() map[string]any {
|
|||
m["indices"] = indices
|
||||
for i := range c.indices {
|
||||
var n uint64
|
||||
for _, list := range c.indices[i].data {
|
||||
n += uint64(list.len)
|
||||
}
|
||||
c.indices[i].data.Iter(func(_ string, l *list) (stop bool) {
|
||||
n += uint64(l.len)
|
||||
return
|
||||
})
|
||||
indices[c.indices[i].name] = n
|
||||
}
|
||||
c.mutex.Unlock()
|
||||
|
|
|
@ -7,6 +7,8 @@ import (
|
|||
"unsafe"
|
||||
|
||||
"codeberg.org/gruf/go-byteutil"
|
||||
|
||||
"github.com/dolthub/swiss"
|
||||
)
|
||||
|
||||
// IndexConfig defines config variables
|
||||
|
@ -70,7 +72,7 @@ type Index struct {
|
|||
// index_entry{} which also contains the exact
|
||||
// key each result is stored under. the hash map
|
||||
// only keys by the xxh3 hash checksum for speed.
|
||||
data map[string]*list // [*index_entry]
|
||||
data *swiss.Map[string, *list]
|
||||
|
||||
// struct fields encompassed by
|
||||
// keys (+ hashes) of this index.
|
||||
|
@ -153,13 +155,13 @@ func (i *Index) init(t reflect.Type, cfg IndexConfig, cap int) {
|
|||
}
|
||||
|
||||
// Initialize index_entry list store.
|
||||
i.data = make(map[string]*list, cap+1)
|
||||
i.data = swiss.NewMap[string, *list](uint32(cap))
|
||||
}
|
||||
|
||||
// get_one will fetch one indexed item under key.
|
||||
func (i *Index) get_one(key Key) *indexed_item {
|
||||
// Get list at hash.
|
||||
l := i.data[key.key]
|
||||
l, _ := i.data.Get(key.key)
|
||||
if l == nil {
|
||||
return nil
|
||||
}
|
||||
|
@ -182,7 +184,7 @@ func (i *Index) get(key Key, hook func(*indexed_item)) {
|
|||
}
|
||||
|
||||
// Get list at hash.
|
||||
l := i.data[key.key]
|
||||
l, _ := i.data.Get(key.key)
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
|
@ -220,7 +222,7 @@ func (i *Index) key(buf *byteutil.Buffer, parts []any) Key {
|
|||
for x, field := range i.fields {
|
||||
before := len(buf.B)
|
||||
buf.B = field.mangle(buf.B, parts[x])
|
||||
if string(buf.B[before:]) == field.zero {
|
||||
if string(buf.B[before:]) == field.zerostr {
|
||||
return Key{}
|
||||
}
|
||||
buf.B = append(buf.B, '.')
|
||||
|
@ -242,13 +244,13 @@ func (i *Index) key(buf *byteutil.Buffer, parts []any) Key {
|
|||
// of key collisions and overwriting 'unique' entries.
|
||||
func (i *Index) append(key Key, item *indexed_item) {
|
||||
// Look for existing.
|
||||
l := i.data[key.key]
|
||||
l, _ := i.data.Get(key.key)
|
||||
|
||||
if l == nil {
|
||||
|
||||
// Allocate new.
|
||||
l = new_list()
|
||||
i.data[key.key] = l
|
||||
i.data.Put(key.key, l)
|
||||
|
||||
} else if is_unique(i.flags) {
|
||||
|
||||
|
@ -284,7 +286,7 @@ func (i *Index) delete(key Key, hook func(*indexed_item)) {
|
|||
}
|
||||
|
||||
// Get list at hash.
|
||||
l := i.data[key.key]
|
||||
l, _ := i.data.Get(key.key)
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
|
@ -298,7 +300,7 @@ func (i *Index) delete(key Key, hook func(*indexed_item)) {
|
|||
}
|
||||
|
||||
// Delete data at hash.
|
||||
delete(i.data, key.key)
|
||||
i.data.Delete(key.key)
|
||||
|
||||
// Iterate entries in list.
|
||||
for x := 0; x < l.len; x++ {
|
||||
|
@ -328,7 +330,7 @@ func (i *Index) delete(key Key, hook func(*indexed_item)) {
|
|||
// delete_entry deletes the given index entry.
|
||||
func (i *Index) delete_entry(entry *index_entry) {
|
||||
// Get list at hash sum.
|
||||
l := i.data[entry.key.key]
|
||||
l, _ := i.data.Get(entry.key.key)
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
|
@ -338,7 +340,7 @@ func (i *Index) delete_entry(entry *index_entry) {
|
|||
|
||||
if l.len == 0 {
|
||||
// Remove entry list from map.
|
||||
delete(i.data, entry.key.key)
|
||||
i.data.Delete(entry.key.key)
|
||||
|
||||
// Release list.
|
||||
free_list(l)
|
||||
|
@ -348,6 +350,33 @@ func (i *Index) delete_entry(entry *index_entry) {
|
|||
entry.item.drop_index(entry)
|
||||
}
|
||||
|
||||
// compact will reduce the size of underlying
|
||||
// index map if the cap vastly exceeds len.
|
||||
func (i *Index) compact() {
|
||||
|
||||
// Maximum load factor before
|
||||
// 'swiss' allocates new hmap:
|
||||
// maxLoad = 7 / 8
|
||||
//
|
||||
// So we apply the inverse/2, once
|
||||
// $maxLoad/2 % of hmap is empty we
|
||||
// compact the map to drop buckets.
|
||||
len := i.data.Count()
|
||||
cap := i.data.Capacity()
|
||||
if cap-len > (cap*7)/(8*2) {
|
||||
|
||||
// Create a new map only as big as required.
|
||||
data := swiss.NewMap[string, *list](uint32(len))
|
||||
i.data.Iter(func(k string, v *list) (stop bool) {
|
||||
data.Put(k, v)
|
||||
return false
|
||||
})
|
||||
|
||||
// Set new map.
|
||||
i.data = data
|
||||
}
|
||||
}
|
||||
|
||||
// index_entry represents a single entry
|
||||
// in an Index{}, where it will be accessible
|
||||
// by Key{} pointing to a containing list{}.
|
||||
|
|
|
@ -214,9 +214,10 @@ func (q *Queue[T]) Debug() map[string]any {
|
|||
m["indices"] = indices
|
||||
for i := range q.indices {
|
||||
var n uint64
|
||||
for _, list := range q.indices[i].data {
|
||||
n += uint64(list.len)
|
||||
}
|
||||
q.indices[i].data.Iter(func(_ string, l *list) (stop bool) {
|
||||
n += uint64(l.len)
|
||||
return
|
||||
})
|
||||
indices[q.indices[i].name] = n
|
||||
}
|
||||
q.mutex.Unlock()
|
||||
|
@ -324,8 +325,14 @@ func (q *Queue[T]) delete(item *indexed_item) {
|
|||
entry := item.indexed[len(item.indexed)-1]
|
||||
item.indexed = item.indexed[:len(item.indexed)-1]
|
||||
|
||||
// Drop index_entry from index.
|
||||
entry.index.delete_entry(entry)
|
||||
// Get entry's index.
|
||||
index := entry.index
|
||||
|
||||
// Drop this index_entry.
|
||||
index.delete_entry(entry)
|
||||
|
||||
// Check compact.
|
||||
index.compact()
|
||||
}
|
||||
|
||||
// Drop entry from queue list.
|
||||
|
|
|
@ -73,9 +73,10 @@ func (q *QueueCtx[T]) Debug() map[string]any {
|
|||
m["indices"] = indices
|
||||
for i := range q.indices {
|
||||
var n uint64
|
||||
for _, list := range q.indices[i].data {
|
||||
n += uint64(list.len)
|
||||
}
|
||||
q.indices[i].data.Iter(func(_ string, l *list) (stop bool) {
|
||||
n += uint64(l.len)
|
||||
return
|
||||
})
|
||||
indices[q.indices[i].name] = n
|
||||
}
|
||||
q.mutex.Unlock()
|
||||
|
|
|
@ -29,10 +29,15 @@ type struct_field struct {
|
|||
// (i.e. fast serializing) fn.
|
||||
mangle mangler.Mangler
|
||||
|
||||
// zero value data, used when
|
||||
// nil encountered during ptr
|
||||
// offset following.
|
||||
zero unsafe.Pointer
|
||||
|
||||
// mangled zero value string,
|
||||
// if set this indicates zero
|
||||
// values of field not allowed
|
||||
zero string
|
||||
zerostr string
|
||||
}
|
||||
|
||||
// next_offset defines a next offset location
|
||||
|
@ -106,13 +111,14 @@ func find_field(t reflect.Type, names []string) (sfield struct_field) {
|
|||
|
||||
// Get field type as reflect2.
|
||||
sfield.type2 = reflect2.Type2(t)
|
||||
i := sfield.type2.New()
|
||||
|
||||
// Find mangler for field type.
|
||||
sfield.mangle = mangler.Get(t)
|
||||
|
||||
// Set possible mangled zero value.
|
||||
sfield.zero = string(sfield.mangle(nil, i))
|
||||
// Set possible zero value and its string.
|
||||
sfield.zero = sfield.type2.UnsafeNew()
|
||||
i := sfield.type2.UnsafeIndirect(sfield.zero)
|
||||
sfield.zerostr = string(sfield.mangle(nil, i))
|
||||
|
||||
return
|
||||
}
|
||||
|
@ -130,8 +136,11 @@ func extract_fields(ptr unsafe.Pointer, fields []struct_field) []any {
|
|||
for _, offset := range field.offsets {
|
||||
// Dereference any ptrs to offset.
|
||||
fptr = deref(fptr, offset.derefs)
|
||||
|
||||
if fptr == nil {
|
||||
return nil
|
||||
// Use zero value.
|
||||
fptr = field.zero
|
||||
break
|
||||
}
|
||||
|
||||
// Jump forward by offset to next ptr.
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
*.idea
|
||||
*.test
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,4 @@
|
|||
# maphash
|
||||
|
||||
Hash any `comparable` type using Golang's fast runtime hash.
|
||||
Uses [AES](https://en.wikipedia.org/wiki/AES_instruction_set) instructions when available.
|
|
@ -0,0 +1,48 @@
|
|||
// Copyright 2022 Dolthub, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package maphash
|
||||
|
||||
import "unsafe"
|
||||
|
||||
// Hasher hashes values of type K.
|
||||
// Uses runtime AES-based hashing.
|
||||
type Hasher[K comparable] struct {
|
||||
hash hashfn
|
||||
seed uintptr
|
||||
}
|
||||
|
||||
// NewHasher creates a new Hasher[K] with a random seed.
|
||||
func NewHasher[K comparable]() Hasher[K] {
|
||||
return Hasher[K]{
|
||||
hash: getRuntimeHasher[K](),
|
||||
seed: newHashSeed(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewSeed returns a copy of |h| with a new hash seed.
|
||||
func NewSeed[K comparable](h Hasher[K]) Hasher[K] {
|
||||
return Hasher[K]{
|
||||
hash: h.hash,
|
||||
seed: newHashSeed(),
|
||||
}
|
||||
}
|
||||
|
||||
// Hash hashes |key|.
|
||||
func (h Hasher[K]) Hash(key K) uint64 {
|
||||
// promise to the compiler that pointer
|
||||
// |p| does not escape the stack.
|
||||
p := noescape(unsafe.Pointer(&key))
|
||||
return uint64(h.hash(p, h.seed))
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
// Copyright 2022 Dolthub, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// This file incorporates work covered by the following copyright and
|
||||
// permission notice:
|
||||
//
|
||||
// Copyright 2022 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build go1.18 || go1.19
|
||||
// +build go1.18 go1.19
|
||||
|
||||
package maphash
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type hashfn func(unsafe.Pointer, uintptr) uintptr
|
||||
|
||||
func getRuntimeHasher[K comparable]() (h hashfn) {
|
||||
a := any(make(map[K]struct{}))
|
||||
i := (*mapiface)(unsafe.Pointer(&a))
|
||||
h = i.typ.hasher
|
||||
return
|
||||
}
|
||||
|
||||
func newHashSeed() uintptr {
|
||||
return uintptr(rand.Int())
|
||||
}
|
||||
|
||||
// noescape hides a pointer from escape analysis. It is the identity function
|
||||
// but escape analysis doesn't think the output depends on the input.
|
||||
// noescape is inlined and currently compiles down to zero instructions.
|
||||
// USE CAREFULLY!
|
||||
// This was copied from the runtime (via pkg "strings"); see issues 23382 and 7921.
|
||||
//
|
||||
//go:nosplit
|
||||
//go:nocheckptr
|
||||
func noescape(p unsafe.Pointer) unsafe.Pointer {
|
||||
x := uintptr(p)
|
||||
return unsafe.Pointer(x ^ 0)
|
||||
}
|
||||
|
||||
type mapiface struct {
|
||||
typ *maptype
|
||||
val *hmap
|
||||
}
|
||||
|
||||
// go/src/runtime/type.go
|
||||
type maptype struct {
|
||||
typ _type
|
||||
key *_type
|
||||
elem *_type
|
||||
bucket *_type
|
||||
// function for hashing keys (ptr to key, seed) -> hash
|
||||
hasher func(unsafe.Pointer, uintptr) uintptr
|
||||
keysize uint8
|
||||
elemsize uint8
|
||||
bucketsize uint16
|
||||
flags uint32
|
||||
}
|
||||
|
||||
// go/src/runtime/map.go
|
||||
type hmap struct {
|
||||
count int
|
||||
flags uint8
|
||||
B uint8
|
||||
noverflow uint16
|
||||
// hash seed
|
||||
hash0 uint32
|
||||
buckets unsafe.Pointer
|
||||
oldbuckets unsafe.Pointer
|
||||
nevacuate uintptr
|
||||
// true type is *mapextra
|
||||
// but we don't need this data
|
||||
extra unsafe.Pointer
|
||||
}
|
||||
|
||||
// go/src/runtime/type.go
|
||||
type tflag uint8
|
||||
type nameOff int32
|
||||
type typeOff int32
|
||||
|
||||
// go/src/runtime/type.go
|
||||
type _type struct {
|
||||
size uintptr
|
||||
ptrdata uintptr
|
||||
hash uint32
|
||||
tflag tflag
|
||||
align uint8
|
||||
fieldAlign uint8
|
||||
kind uint8
|
||||
equal func(unsafe.Pointer, unsafe.Pointer) bool
|
||||
gcdata *byte
|
||||
str nameOff
|
||||
ptrToThis typeOff
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
**/.idea/
|
||||
.vscode
|
||||
.run
|
||||
venv
|
||||
.DS_Store
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,54 @@
|
|||
# SwissMap
|
||||
|
||||
SwissMap is a hash table adapated from the "SwissTable" family of hash tables from [Abseil](https://abseil.io/blog/20180927-swisstables). It uses [AES](https://github.com/dolthub/maphash) instructions for fast-hashing and performs key lookups in parallel using [SSE](https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions) instructions. Because of these optimizations, SwissMap is faster and more memory efficient than Golang's built-in `map`. If you'd like to learn more about its design and implementation, check out this [blog post](https://www.dolthub.com/blog/2023-03-28-swiss-map/) announcing its release.
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
SwissMap exposes the same interface as the built-in `map`. Give it a try using this [Go playground](https://go.dev/play/p/JPDC5WhYN7g).
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/dolthub/swiss"
|
||||
|
||||
func main() {
|
||||
m := swiss.NewMap[string, int](42)
|
||||
|
||||
m.Put("foo", 1)
|
||||
m.Put("bar", 2)
|
||||
|
||||
m.Iter(func(k string, v int) (stop bool) {
|
||||
println("iter", k, v)
|
||||
return false // continue
|
||||
})
|
||||
|
||||
if x, ok := m.Get("foo"); ok {
|
||||
println(x)
|
||||
}
|
||||
if m.Has("bar") {
|
||||
x, _ := m.Get("bar")
|
||||
println(x)
|
||||
}
|
||||
|
||||
m.Put("foo", -1)
|
||||
m.Delete("bar")
|
||||
|
||||
if x, ok := m.Get("foo"); ok {
|
||||
println(x)
|
||||
}
|
||||
if m.Has("bar") {
|
||||
x, _ := m.Get("bar")
|
||||
println(x)
|
||||
}
|
||||
|
||||
m.Clear()
|
||||
|
||||
// Output:
|
||||
// iter foo 1
|
||||
// iter bar 2
|
||||
// 1
|
||||
// 2
|
||||
// -1
|
||||
}
|
||||
```
|
|
@ -0,0 +1,58 @@
|
|||
// Copyright 2023 Dolthub, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build !amd64 || nosimd
|
||||
|
||||
package swiss
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
groupSize = 8
|
||||
maxAvgGroupLoad = 7
|
||||
|
||||
loBits uint64 = 0x0101010101010101
|
||||
hiBits uint64 = 0x8080808080808080
|
||||
)
|
||||
|
||||
type bitset uint64
|
||||
|
||||
func metaMatchH2(m *metadata, h h2) bitset {
|
||||
// https://graphics.stanford.edu/~seander/bithacks.html##ValueInWord
|
||||
return hasZeroByte(castUint64(m) ^ (loBits * uint64(h)))
|
||||
}
|
||||
|
||||
func metaMatchEmpty(m *metadata) bitset {
|
||||
return hasZeroByte(castUint64(m) ^ hiBits)
|
||||
}
|
||||
|
||||
func nextMatch(b *bitset) uint32 {
|
||||
s := uint32(bits.TrailingZeros64(uint64(*b)))
|
||||
*b &= ^(1 << s) // clear bit |s|
|
||||
return s >> 3 // div by 8
|
||||
}
|
||||
|
||||
func hasZeroByte(x uint64) bitset {
|
||||
return bitset(((x - loBits) & ^(x)) & hiBits)
|
||||
}
|
||||
|
||||
func castUint64(m *metadata) uint64 {
|
||||
return *(*uint64)((unsafe.Pointer)(m))
|
||||
}
|
||||
|
||||
//go:linkname fastrand runtime.fastrand
|
||||
func fastrand() uint32
|
|
@ -0,0 +1,50 @@
|
|||
// Copyright 2023 Dolthub, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build amd64 && !nosimd
|
||||
|
||||
package swiss
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
_ "unsafe"
|
||||
|
||||
"github.com/dolthub/swiss/simd"
|
||||
)
|
||||
|
||||
const (
|
||||
groupSize = 16
|
||||
maxAvgGroupLoad = 14
|
||||
)
|
||||
|
||||
type bitset uint16
|
||||
|
||||
func metaMatchH2(m *metadata, h h2) bitset {
|
||||
b := simd.MatchMetadata((*[16]int8)(m), int8(h))
|
||||
return bitset(b)
|
||||
}
|
||||
|
||||
func metaMatchEmpty(m *metadata) bitset {
|
||||
b := simd.MatchMetadata((*[16]int8)(m), empty)
|
||||
return bitset(b)
|
||||
}
|
||||
|
||||
func nextMatch(b *bitset) (s uint32) {
|
||||
s = uint32(bits.TrailingZeros16(uint16(*b)))
|
||||
*b &= ^(1 << s) // clear bit |s|
|
||||
return
|
||||
}
|
||||
|
||||
//go:linkname fastrand runtime.fastrand
|
||||
func fastrand() uint32
|
|
@ -0,0 +1,359 @@
|
|||
// Copyright 2023 Dolthub, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package swiss
|
||||
|
||||
import (
|
||||
"github.com/dolthub/maphash"
|
||||
)
|
||||
|
||||
const (
|
||||
maxLoadFactor = float32(maxAvgGroupLoad) / float32(groupSize)
|
||||
)
|
||||
|
||||
// Map is an open-addressing hash map
|
||||
// based on Abseil's flat_hash_map.
|
||||
type Map[K comparable, V any] struct {
|
||||
ctrl []metadata
|
||||
groups []group[K, V]
|
||||
hash maphash.Hasher[K]
|
||||
resident uint32
|
||||
dead uint32
|
||||
limit uint32
|
||||
}
|
||||
|
||||
// metadata is the h2 metadata array for a group.
|
||||
// find operations first probe the controls bytes
|
||||
// to filter candidates before matching keys
|
||||
type metadata [groupSize]int8
|
||||
|
||||
// group is a group of 16 key-value pairs
|
||||
type group[K comparable, V any] struct {
|
||||
keys [groupSize]K
|
||||
values [groupSize]V
|
||||
}
|
||||
|
||||
const (
|
||||
h1Mask uint64 = 0xffff_ffff_ffff_ff80
|
||||
h2Mask uint64 = 0x0000_0000_0000_007f
|
||||
empty int8 = -128 // 0b1000_0000
|
||||
tombstone int8 = -2 // 0b1111_1110
|
||||
)
|
||||
|
||||
// h1 is a 57 bit hash prefix
|
||||
type h1 uint64
|
||||
|
||||
// h2 is a 7 bit hash suffix
|
||||
type h2 int8
|
||||
|
||||
// NewMap constructs a Map.
|
||||
func NewMap[K comparable, V any](sz uint32) (m *Map[K, V]) {
|
||||
groups := numGroups(sz)
|
||||
m = &Map[K, V]{
|
||||
ctrl: make([]metadata, groups),
|
||||
groups: make([]group[K, V], groups),
|
||||
hash: maphash.NewHasher[K](),
|
||||
limit: groups * maxAvgGroupLoad,
|
||||
}
|
||||
for i := range m.ctrl {
|
||||
m.ctrl[i] = newEmptyMetadata()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Has returns true if |key| is present in |m|.
|
||||
func (m *Map[K, V]) Has(key K) (ok bool) {
|
||||
hi, lo := splitHash(m.hash.Hash(key))
|
||||
g := probeStart(hi, len(m.groups))
|
||||
for { // inlined find loop
|
||||
matches := metaMatchH2(&m.ctrl[g], lo)
|
||||
for matches != 0 {
|
||||
s := nextMatch(&matches)
|
||||
if key == m.groups[g].keys[s] {
|
||||
ok = true
|
||||
return
|
||||
}
|
||||
}
|
||||
// |key| is not in group |g|,
|
||||
// stop probing if we see an empty slot
|
||||
matches = metaMatchEmpty(&m.ctrl[g])
|
||||
if matches != 0 {
|
||||
ok = false
|
||||
return
|
||||
}
|
||||
g += 1 // linear probing
|
||||
if g >= uint32(len(m.groups)) {
|
||||
g = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns the |value| mapped by |key| if one exists.
|
||||
func (m *Map[K, V]) Get(key K) (value V, ok bool) {
|
||||
hi, lo := splitHash(m.hash.Hash(key))
|
||||
g := probeStart(hi, len(m.groups))
|
||||
for { // inlined find loop
|
||||
matches := metaMatchH2(&m.ctrl[g], lo)
|
||||
for matches != 0 {
|
||||
s := nextMatch(&matches)
|
||||
if key == m.groups[g].keys[s] {
|
||||
value, ok = m.groups[g].values[s], true
|
||||
return
|
||||
}
|
||||
}
|
||||
// |key| is not in group |g|,
|
||||
// stop probing if we see an empty slot
|
||||
matches = metaMatchEmpty(&m.ctrl[g])
|
||||
if matches != 0 {
|
||||
ok = false
|
||||
return
|
||||
}
|
||||
g += 1 // linear probing
|
||||
if g >= uint32(len(m.groups)) {
|
||||
g = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Put attempts to insert |key| and |value|
|
||||
func (m *Map[K, V]) Put(key K, value V) {
|
||||
if m.resident >= m.limit {
|
||||
m.rehash(m.nextSize())
|
||||
}
|
||||
hi, lo := splitHash(m.hash.Hash(key))
|
||||
g := probeStart(hi, len(m.groups))
|
||||
for { // inlined find loop
|
||||
matches := metaMatchH2(&m.ctrl[g], lo)
|
||||
for matches != 0 {
|
||||
s := nextMatch(&matches)
|
||||
if key == m.groups[g].keys[s] { // update
|
||||
m.groups[g].keys[s] = key
|
||||
m.groups[g].values[s] = value
|
||||
return
|
||||
}
|
||||
}
|
||||
// |key| is not in group |g|,
|
||||
// stop probing if we see an empty slot
|
||||
matches = metaMatchEmpty(&m.ctrl[g])
|
||||
if matches != 0 { // insert
|
||||
s := nextMatch(&matches)
|
||||
m.groups[g].keys[s] = key
|
||||
m.groups[g].values[s] = value
|
||||
m.ctrl[g][s] = int8(lo)
|
||||
m.resident++
|
||||
return
|
||||
}
|
||||
g += 1 // linear probing
|
||||
if g >= uint32(len(m.groups)) {
|
||||
g = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete attempts to remove |key|, returns true successful.
|
||||
func (m *Map[K, V]) Delete(key K) (ok bool) {
|
||||
hi, lo := splitHash(m.hash.Hash(key))
|
||||
g := probeStart(hi, len(m.groups))
|
||||
for {
|
||||
matches := metaMatchH2(&m.ctrl[g], lo)
|
||||
for matches != 0 {
|
||||
s := nextMatch(&matches)
|
||||
if key == m.groups[g].keys[s] {
|
||||
ok = true
|
||||
// optimization: if |m.ctrl[g]| contains any empty
|
||||
// metadata bytes, we can physically delete |key|
|
||||
// rather than placing a tombstone.
|
||||
// The observation is that any probes into group |g|
|
||||
// would already be terminated by the existing empty
|
||||
// slot, and therefore reclaiming slot |s| will not
|
||||
// cause premature termination of probes into |g|.
|
||||
if metaMatchEmpty(&m.ctrl[g]) != 0 {
|
||||
m.ctrl[g][s] = empty
|
||||
m.resident--
|
||||
} else {
|
||||
m.ctrl[g][s] = tombstone
|
||||
m.dead++
|
||||
}
|
||||
var k K
|
||||
var v V
|
||||
m.groups[g].keys[s] = k
|
||||
m.groups[g].values[s] = v
|
||||
return
|
||||
}
|
||||
}
|
||||
// |key| is not in group |g|,
|
||||
// stop probing if we see an empty slot
|
||||
matches = metaMatchEmpty(&m.ctrl[g])
|
||||
if matches != 0 { // |key| absent
|
||||
ok = false
|
||||
return
|
||||
}
|
||||
g += 1 // linear probing
|
||||
if g >= uint32(len(m.groups)) {
|
||||
g = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Iter iterates the elements of the Map, passing them to the callback.
|
||||
// It guarantees that any key in the Map will be visited only once, and
|
||||
// for un-mutated Maps, every key will be visited once. If the Map is
|
||||
// Mutated during iteration, mutations will be reflected on return from
|
||||
// Iter, but the set of keys visited by Iter is non-deterministic.
|
||||
func (m *Map[K, V]) Iter(cb func(k K, v V) (stop bool)) {
|
||||
// take a consistent view of the table in case
|
||||
// we rehash during iteration
|
||||
ctrl, groups := m.ctrl, m.groups
|
||||
// pick a random starting group
|
||||
g := randIntN(len(groups))
|
||||
for n := 0; n < len(groups); n++ {
|
||||
for s, c := range ctrl[g] {
|
||||
if c == empty || c == tombstone {
|
||||
continue
|
||||
}
|
||||
k, v := groups[g].keys[s], groups[g].values[s]
|
||||
if stop := cb(k, v); stop {
|
||||
return
|
||||
}
|
||||
}
|
||||
g++
|
||||
if g >= uint32(len(groups)) {
|
||||
g = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear removes all elements from the Map.
|
||||
func (m *Map[K, V]) Clear() {
|
||||
for i, c := range m.ctrl {
|
||||
for j := range c {
|
||||
m.ctrl[i][j] = empty
|
||||
}
|
||||
}
|
||||
var k K
|
||||
var v V
|
||||
for i := range m.groups {
|
||||
g := &m.groups[i]
|
||||
for i := range g.keys {
|
||||
g.keys[i] = k
|
||||
g.values[i] = v
|
||||
}
|
||||
}
|
||||
m.resident, m.dead = 0, 0
|
||||
}
|
||||
|
||||
// Count returns the number of elements in the Map.
|
||||
func (m *Map[K, V]) Count() int {
|
||||
return int(m.resident - m.dead)
|
||||
}
|
||||
|
||||
// Capacity returns the number of additional elements
|
||||
// the can be added to the Map before resizing.
|
||||
func (m *Map[K, V]) Capacity() int {
|
||||
return int(m.limit - m.resident)
|
||||
}
|
||||
|
||||
// find returns the location of |key| if present, or its insertion location if absent.
|
||||
// for performance, find is manually inlined into public methods.
|
||||
func (m *Map[K, V]) find(key K, hi h1, lo h2) (g, s uint32, ok bool) {
|
||||
g = probeStart(hi, len(m.groups))
|
||||
for {
|
||||
matches := metaMatchH2(&m.ctrl[g], lo)
|
||||
for matches != 0 {
|
||||
s = nextMatch(&matches)
|
||||
if key == m.groups[g].keys[s] {
|
||||
return g, s, true
|
||||
}
|
||||
}
|
||||
// |key| is not in group |g|,
|
||||
// stop probing if we see an empty slot
|
||||
matches = metaMatchEmpty(&m.ctrl[g])
|
||||
if matches != 0 {
|
||||
s = nextMatch(&matches)
|
||||
return g, s, false
|
||||
}
|
||||
g += 1 // linear probing
|
||||
if g >= uint32(len(m.groups)) {
|
||||
g = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Map[K, V]) nextSize() (n uint32) {
|
||||
n = uint32(len(m.groups)) * 2
|
||||
if m.dead >= (m.resident / 2) {
|
||||
n = uint32(len(m.groups))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Map[K, V]) rehash(n uint32) {
|
||||
groups, ctrl := m.groups, m.ctrl
|
||||
m.groups = make([]group[K, V], n)
|
||||
m.ctrl = make([]metadata, n)
|
||||
for i := range m.ctrl {
|
||||
m.ctrl[i] = newEmptyMetadata()
|
||||
}
|
||||
m.hash = maphash.NewSeed(m.hash)
|
||||
m.limit = n * maxAvgGroupLoad
|
||||
m.resident, m.dead = 0, 0
|
||||
for g := range ctrl {
|
||||
for s := range ctrl[g] {
|
||||
c := ctrl[g][s]
|
||||
if c == empty || c == tombstone {
|
||||
continue
|
||||
}
|
||||
m.Put(groups[g].keys[s], groups[g].values[s])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Map[K, V]) loadFactor() float32 {
|
||||
slots := float32(len(m.groups) * groupSize)
|
||||
return float32(m.resident-m.dead) / slots
|
||||
}
|
||||
|
||||
// numGroups returns the minimum number of groups needed to store |n| elems.
|
||||
func numGroups(n uint32) (groups uint32) {
|
||||
groups = (n + maxAvgGroupLoad - 1) / maxAvgGroupLoad
|
||||
if groups == 0 {
|
||||
groups = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func newEmptyMetadata() (meta metadata) {
|
||||
for i := range meta {
|
||||
meta[i] = empty
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func splitHash(h uint64) (h1, h2) {
|
||||
return h1((h & h1Mask) >> 7), h2(h & h2Mask)
|
||||
}
|
||||
|
||||
func probeStart(hi h1, groups int) uint32 {
|
||||
return fastModN(uint32(hi), uint32(groups))
|
||||
}
|
||||
|
||||
// lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
|
||||
func fastModN(x, n uint32) uint32 {
|
||||
return uint32((uint64(x) * uint64(n)) >> 32)
|
||||
}
|
||||
|
||||
// randIntN returns a random number in the interval [0, n).
|
||||
func randIntN(n int) uint32 {
|
||||
return fastModN(fastrand(), uint32(n))
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
// Code generated by command: go run asm.go -out match.s -stubs match_amd64.go. DO NOT EDIT.
|
||||
|
||||
//go:build amd64
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
// func MatchMetadata(metadata *[16]int8, hash int8) uint16
|
||||
// Requires: SSE2, SSSE3
|
||||
TEXT ·MatchMetadata(SB), NOSPLIT, $0-18
|
||||
MOVQ metadata+0(FP), AX
|
||||
MOVBLSX hash+8(FP), CX
|
||||
MOVD CX, X0
|
||||
PXOR X1, X1
|
||||
PSHUFB X1, X0
|
||||
MOVOU (AX), X1
|
||||
PCMPEQB X1, X0
|
||||
PMOVMSKB X0, AX
|
||||
MOVW AX, ret+16(FP)
|
||||
RET
|
|
@ -0,0 +1,9 @@
|
|||
// Code generated by command: go run asm.go -out match.s -stubs match_amd64.go. DO NOT EDIT.
|
||||
|
||||
//go:build amd64
|
||||
|
||||
package simd
|
||||
|
||||
// MatchMetadata performs a 16-way probe of |metadata| using SSE instructions
|
||||
// nb: |metadata| must be an aligned pointer
|
||||
func MatchMetadata(metadata *[16]int8, hash int8) uint16
|
|
@ -49,8 +49,11 @@ codeberg.org/gruf/go-mangler
|
|||
# codeberg.org/gruf/go-maps v1.0.3
|
||||
## explicit; go 1.19
|
||||
codeberg.org/gruf/go-maps
|
||||
# codeberg.org/gruf/go-mutexes v1.4.1
|
||||
## explicit; go 1.14
|
||||
# codeberg.org/gruf/go-mempool v0.0.0-20240507125005-cef10d64a760
|
||||
## explicit; go 1.22.2
|
||||
codeberg.org/gruf/go-mempool
|
||||
# codeberg.org/gruf/go-mutexes v1.5.0
|
||||
## explicit; go 1.22.2
|
||||
codeberg.org/gruf/go-mutexes
|
||||
# codeberg.org/gruf/go-runners v1.6.2
|
||||
## explicit; go 1.19
|
||||
|
@ -62,7 +65,7 @@ codeberg.org/gruf/go-sched
|
|||
## explicit; go 1.19
|
||||
codeberg.org/gruf/go-store/v2/storage
|
||||
codeberg.org/gruf/go-store/v2/util
|
||||
# codeberg.org/gruf/go-structr v0.8.2
|
||||
# codeberg.org/gruf/go-structr v0.8.4
|
||||
## explicit; go 1.21
|
||||
codeberg.org/gruf/go-structr
|
||||
# codeberg.org/superseriousbusiness/exif-terminator v0.7.0
|
||||
|
@ -177,6 +180,13 @@ github.com/disintegration/imaging
|
|||
# github.com/docker/go-units v0.5.0
|
||||
## explicit
|
||||
github.com/docker/go-units
|
||||
# github.com/dolthub/maphash v0.1.0
|
||||
## explicit; go 1.18
|
||||
github.com/dolthub/maphash
|
||||
# github.com/dolthub/swiss v0.2.1
|
||||
## explicit; go 1.18
|
||||
github.com/dolthub/swiss
|
||||
github.com/dolthub/swiss/simd
|
||||
# github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b
|
||||
## explicit; go 1.12
|
||||
github.com/dsoprea/go-exif/v3
|
||||
|
|
Loading…
Reference in New Issue