-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoding.go
More file actions
70 lines (53 loc) · 1.73 KB
/
encoding.go
File metadata and controls
70 lines (53 loc) · 1.73 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
package bigcache
import (
"encoding/binary"
)
/*
storage like this.
--------------------------------------------------
|timestampSize|keyHashSize|keySize|keyValue|entry|
--------------------------------------------------
*/
const (
timestampSize = 8
keyHashSize = 8
keySize = 2
headSize = timestampSize + keyHashSize + keySize
)
func wrapEntry(timestamp int64, hash uint64, key string, entry []byte, buffer *[]byte) []byte {
lenKey := len(key)
// lenData := len(entry) just use once,so don't use it.
entryLen := headSize + lenKey + len(entry)
if entryLen > cap(*buffer) {
*buffer = make([]byte, entryLen)
}
// if dont't have this, will appear (*buffer)[],too cumbrous
blob := *buffer
binary.LittleEndian.PutUint64(blob, uint64(timestamp))
binary.LittleEndian.PutUint64(blob[timestampSize:], hash)
binary.LittleEndian.PutUint16(blob[timestampSize+keyHashSize:], uint16(lenKey))
copy(blob[headSize:], key)
copy(blob[headSize+lenKey:], entry)
return blob[:entryLen]
}
func readEntry(buffer []byte) []byte {
keyLen := binary.LittleEndian.Uint16(buffer[timestampSize+keyHashSize:])
returnBuffer := make([]byte, len(buffer)-headSize-int(keyLen))
copy(returnBuffer, buffer[headSize+keyLen:])
return returnBuffer
}
func hashKeyToZero(buffer []byte) {
binary.LittleEndian.PutUint64(buffer[timestampSize:], 0)
}
func getHashKey(buffer []byte) uint64 {
return binary.LittleEndian.Uint64(buffer[timestampSize:])
}
func getKey(buffer []byte) []byte {
keyLen := binary.LittleEndian.Uint16(buffer[timestampSize+keyHashSize:])
returnBuffer := make([]byte, keyLen)
copy(returnBuffer, buffer[headSize:])
return returnBuffer
}
func readTimestamp(buffer []byte) uint64 {
return binary.LittleEndian.Uint64(buffer[0:timestampSize])
}