github.com/tursom/GoCollections@v0.3.10/collections/GoMap.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  	"github.com/tursom/GoCollections/exceptions"
    11  	"github.com/tursom/GoCollections/lang"
    12  )
    13  
    14  type (
    15  	GoMap[K lang.Object, V any] struct {
    16  		NodeMap[K, V]
    17  		m map[int32]*SimpleMapNode[K, V]
    18  	}
    19  	//goMapNode[K lang.Object, V any] struct {
    20  	//	key   K
    21  	//	value V
    22  	//	next  *goMapNode[K, V]
    23  	//}
    24  )
    25  
    26  func NewGoMap[K lang.Object, V any]() *GoMap[K, V] {
    27  	m := &GoMap[K, V]{m: make(map[int32]*SimpleMapNode[K, V])}
    28  	m.NodeMap.MapNodeFinder = NewMapNodeFinderBySlot[K, V](m)
    29  	return m
    30  }
    31  
    32  func (g *GoMap[K, V]) ToString() lang.String {
    33  	return MapToString[K, V](g)
    34  }
    35  
    36  func (g *GoMap[K, V]) String() string {
    37  	return g.ToString().GoString()
    38  }
    39  
    40  func (g *GoMap[K, V]) FindSlot(k K) MapNode[K, V] {
    41  	hashCode := lang.HashCode(k)
    42  	root := g.m[hashCode]
    43  	if root == nil {
    44  		root = &SimpleMapNode[K, V]{}
    45  		g.m[hashCode] = root
    46  	}
    47  	return root
    48  }
    49  
    50  //func (g *GoMap[K, V]) Put(k K, v V) (bool, exceptions.Exception) {
    51  //	node, _ := g.FindNode(k, true)
    52  //	node.value = v
    53  //	return true, nil
    54  //}
    55  //
    56  //func (g *GoMap[K, V]) Get(k K) (V, bool, exceptions.Exception) {
    57  //	node, _ := g.FindNode(k, false)
    58  //	if node == nil {
    59  //		return g.nil()
    60  //	} else {
    61  //		return node.value, true, nil
    62  //	}
    63  //}
    64  //
    65  //func (g *GoMap[K, V]) Remove(k K) (V, bool, exceptions.Exception) {
    66  //	node, prev := g.FindNode(k, false)
    67  //	if node == nil {
    68  //		return g.nil()
    69  //	} else {
    70  //		prev.next = node.next
    71  //		return node.value, true, nil
    72  //	}
    73  //}
    74  
    75  func (g *GoMap[K, V]) Loop(f func(K, V) exceptions.Exception) (err exceptions.Exception) {
    76  	for _, node := range g.m {
    77  		for node.next != nil {
    78  			node = node.next
    79  			err = f(node.key, node.value)
    80  			if err != nil {
    81  				return
    82  			}
    83  		}
    84  	}
    85  	return
    86  }
    87  
    88  func (g *GoMap[K, V]) nil() (V, bool, exceptions.Exception) {
    89  	return lang.Nil[V](), false, nil
    90  }