github.com/tursom/GoCollections@v0.3.10/concurrent/collections/GoSyncMap.go (about)

     1  /*
     2   * Copyright (c) 2022 tursom. All rights reserved.
     3   * Use of this source code is governed by a GPL-3
     4   * license that can be found in the LICENSE file.
     5   */
     6  
     7  package collections
     8  
     9  import (
    10  	"sync"
    11  
    12  	"github.com/tursom/GoCollections/collections"
    13  	"github.com/tursom/GoCollections/concurrent"
    14  	"github.com/tursom/GoCollections/exceptions"
    15  	"github.com/tursom/GoCollections/lang"
    16  )
    17  
    18  type (
    19  	// GoSyncMap an map use go sync.Map to store hash slot
    20  	GoSyncMap[K lang.Object, V any] struct {
    21  		collections.NodeMap[K, V]
    22  		m    sync.Map
    23  		lock concurrent.RWLock
    24  	}
    25  )
    26  
    27  func NewGoSyncMap[K lang.Object, V any]() *GoSyncMap[K, V] {
    28  	m := &GoSyncMap[K, V]{lock: &sync.RWMutex{}}
    29  	m.MapNodeFinder = collections.NewMapNodeFinderBySlot[K, V](m)
    30  	return m
    31  }
    32  
    33  func (g *GoSyncMap[K, V]) ToString() lang.String {
    34  	return collections.MapToString[K, V](g)
    35  }
    36  
    37  func (g *GoSyncMap[K, V]) FindSlot(k K) collections.MapNode[K, V] {
    38  	hashCode := lang.HashCode(k)
    39  	p, _ := g.m.Load(hashCode)
    40  	root := lang.Cast[*collections.SimpleMapNode[K, V]](p)
    41  	if root == nil {
    42  		root = &collections.SimpleMapNode[K, V]{}
    43  		g.m.Store(hashCode, root)
    44  	}
    45  	return root
    46  }
    47  
    48  func (g *GoSyncMap[K, V]) Put(k K, v V) (bool, exceptions.Exception) {
    49  	g.lock.Lock()
    50  	defer g.lock.Unlock()
    51  	return g.NodeMap.Put(k, v)
    52  }
    53  
    54  func (g *GoSyncMap[K, V]) Get(k K) (V, bool, exceptions.Exception) {
    55  	g.lock.RLock()
    56  	defer g.lock.RUnlock()
    57  	return g.NodeMap.Get(k)
    58  }
    59  
    60  func (g *GoSyncMap[K, V]) Remove(k K) (V, bool, exceptions.Exception) {
    61  	g.lock.Lock()
    62  	defer g.lock.Unlock()
    63  	return g.NodeMap.Remove(k)
    64  }
    65  
    66  func (g *GoSyncMap[K, V]) Loop(f func(K, V) exceptions.Exception) (err exceptions.Exception) {
    67  	g.lock.RLock()
    68  	defer g.lock.RUnlock()
    69  	g.m.Range(func(key, value any) bool {
    70  		err = f(lang.Cast[K](key), lang.Cast[V](value))
    71  		return err == nil
    72  	})
    73  	return
    74  }