-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmem.go
106 lines (93 loc) · 2.13 KB
/
mem.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
98
99
100
101
102
103
104
105
106
package sharemem
import (
"fmt"
"reflect"
"sync"
"unsafe"
)
const (
ipcCreate = 00001000 // 不存在则创建
keyOriginSize = 16
keyLen = 17
dataLen = 4
)
type Mem struct {
l sync.RWMutex
blockSize int
m map[string]int
data []byte
ch chan int
}
func newMem(size, blockSize int, addr uintptr) (*Mem, error){
var data []byte
originLen := size / blockSize
sh := (*reflect.SliceHeader)(unsafe.Pointer(&data))
sh.Data = addr
sh.Len = size + (keyLen+1+dataLen)*originLen
sh.Cap = size + (keyLen+1+dataLen)*originLen
mem := &Mem{
l: sync.RWMutex{},
blockSize: blockSize + 1 + keyLen + dataLen,
data: data,
m: make(map[string]int),
ch: make(chan int, originLen),
}
for i := 0; i < originLen; i++ {
mem.ch <- i
}
return mem, nil
}
func checkkey(key string) ([keyLen]byte, error) {
var res [keyLen]byte
if len(key) > keyOriginSize {
return res, fmt.Errorf("key must <= 16")
}
res[0] = byte(len(key))
for idx, v := range key {
res[idx+1] = byte(v)
}
return res, nil
}
func checkData(data []byte, size int) ([]byte, error) {
if len(data) > size-1-keyLen-dataLen {
return nil, fmt.Errorf("data len over range")
}
res := make([]byte, len(data)+dataLen)
copy(res[:4], datalen(len(data)))
copy(res[4:], data)
return res, nil
}
func (m *Mem) dealBlocak(data []byte) (string, []byte, error) {
if len(data) != m.blockSize {
return "", nil, fmt.Errorf("block size error")
}
if data[0] == 0 {
return "", nil, nil
}
key := data[1:18]
return dealkey(key), dealData(data[18:]), nil
}
func dealkey(data []byte) string {
l := data[0]
res := make([]byte, l)
for i := 0; i < int(l); i++ {
res[i] = data[i+1]
}
return string(res)
}
func dealData(data []byte) []byte {
l := dataLenToInt(data[:5])
res := make([]byte, l)
for i := 0; i < l; i++ {
res[i] = data[i+dataLen]
}
return res
}
func datalen(l int) []byte {
res := make([]byte, 4)
res[0], res[1], res[2], res[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
return res
}
func dataLenToInt(data []byte) int {
return int(data[3]) | int(data[2])<<8 | int(data[1])<<16 | int(data[0])<<24
}