-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashmap.go
More file actions
91 lines (71 loc) · 1.66 KB
/
hashmap.go
File metadata and controls
91 lines (71 loc) · 1.66 KB
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
//
// Copyright (C) 2023 Dmitry Kolesnikov
//
// This file may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
// https://github.com/kshard/symbol
//
package atom
import (
"encoding/binary"
"sync"
"unsafe"
)
//------------------------------------------------------------------------------
type ephemeral struct {
sync.RWMutex
kv map[Atom]string
}
func NewEphemeralMap() HashMap {
return &ephemeral{
kv: make(map[Atom]string),
}
}
func (m *ephemeral) Get(key Atom) (string, error) {
m.RLock()
val, has := m.kv[key]
m.RUnlock()
if !has {
return "", nil
}
return val, nil
}
func (m *ephemeral) Put(key Atom, val string) error {
m.Lock()
m.kv[key] = val
m.Unlock()
return nil
}
//------------------------------------------------------------------------------
type permanent struct {
store Store
}
func NewPermanentMap(store Store) HashMap {
return &permanent{store: store}
}
func (m *permanent) Get(key Atom) (string, error) {
var bkey [5]byte
bkey[0] = ':'
binary.LittleEndian.PutUint32(bkey[1:], key)
val, err := m.store.Get(bkey[:])
if err != nil {
return "", err
}
// This is copied from runtime. It relies on the string
// header being a prefix of the slice header!
str := *(*string)(unsafe.Pointer(&val))
return str, nil
}
func (m *permanent) Put(key Atom, val string) error {
var bkey [5]byte
bkey[0] = ':'
binary.LittleEndian.PutUint32(bkey[1:], key)
// This is copied from runtime. It relies on the string
// header being a prefix of the slice header!
bval := *(*[]byte)(unsafe.Pointer(&val))
err := m.store.Put(bkey[:], bval)
if err != nil {
return err
}
return nil
}