This repository has been archived by the owner on Mar 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.go
97 lines (80 loc) · 1.81 KB
/
node.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package thunder
import (
"encoding/gob"
"sync"
)
// DataMap is the map type containing the
// "generic" data of the nodes.
type DataMap map[interface{}]interface{}
// A Node contains the actual key-value data
// map where data handled with.
type Node struct {
mx *sync.Mutex
locked bool
Data DataMap
}
// lock locks the mutex of the Node if it is
// not already locked.
func (node *Node) lock() {
if node.mx != nil && !node.locked {
node.mx.Lock()
node.locked = true
}
}
// unlock unlocks the mutex of the Node if
// it is locked.
func (node *Node) unlock() {
if node.mx != nil && node.locked {
node.locked = false
node.mx.Unlock()
}
}
// NewNode initializes a new node.
func NewNode() *Node {
return &Node{
Data: make(DataMap),
}
}
// Get returns the value of the node by key.
// If there is no value existent, nil and false
// is returned.
func (node *Node) Get(key interface{}) (interface{}, bool) {
if node == nil {
return nil, false
}
value, ok := node.Data[key]
return value, ok
}
// Set sets the passed value to the passed key.
// If the node pointer is nil, this returns an
// ErrNodeNil error.
func (node *Node) Set(key, value interface{}) error {
if node == nil {
return ErrNodeNil
}
gob.Register(value)
node.Data[key] = value
return nil
}
// Remove deletes a key-value pair by the
// key. If the node pointer is nil, this
// returns an ErrNodeNil error.
func (node *Node) Remove(key interface{}) error {
if node == nil {
return ErrNodeNil
}
if _, ok := node.Data[key]; !ok {
return ErrNodeValueNotExist
}
delete(node.Data, key)
return nil
}
// GetData returns the raw data map inside
// the node. If the node pointer is nil, this
// returns an ErrNodeNil error.
func (node *Node) GetData() (DataMap, error) {
if node == nil {
return nil, ErrNodeNil
}
return node.Data, nil
}