forked from naqvijafar91/cuteDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pair.go
86 lines (75 loc) · 2 KB
/
pair.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
package cutedb
import "encoding/binary"
import "fmt"
// 2+2+30+90 = 124
const pairSize = 124
const maxKeyLength = 30
const maxValueLength = 90
type pairs struct {
keyLen uint16 // 2
valueLen uint16 // 2
key string // 30
value string // 90
}
func (p *pairs) setKey(key string) {
p.key = key
p.keyLen = uint16(len(key))
}
func (p *pairs) setValue(value string) {
p.value = value
p.valueLen = uint16(len(value))
}
func (p *pairs) validate() error {
if len(p.key) > maxKeyLength {
return fmt.Errorf("Key length should not be more than 30, currently it is %d ", len(p.key))
}
if len(p.value) > maxValueLength {
return fmt.Errorf("Value length should not be more than 90, currently it is %d", len(p.value))
}
return nil
}
func newPair(key string, value string) *pairs {
pair := &pairs{}
pair.setKey(key)
pair.setValue(value)
return pair
}
func convertPairsToBytes(pair *pairs) []byte {
pairByte := make([]byte, pairSize)
var pairOffset uint16
pairOffset = 0
copy(pairByte[pairOffset:], uint16ToBytes(pair.keyLen))
pairOffset += 2
copy(pairByte[pairOffset:], uint16ToBytes(pair.valueLen))
pairOffset += 2
keyByte := []byte(pair.key)
copy(pairByte[pairOffset:], keyByte[:pair.keyLen])
pairOffset += pair.keyLen
valueByte := []byte(pair.value)
copy(pairByte[pairOffset:], valueByte[:pair.valueLen])
return pairByte
}
func convertBytesToPair(pairByte []byte) *pairs {
pair := &pairs{}
var pairOffset uint16
pairOffset = 0
//Read key length
pair.keyLen = uint16FromBytes(pairByte[pairOffset:])
pairOffset += 2
//Read value length
pair.valueLen = uint16FromBytes(pairByte[pairOffset:])
pairOffset += 2
pair.key = string(pairByte[pairOffset : pairOffset+pair.keyLen])
pairOffset += pair.keyLen
pair.value = string(pairByte[pairOffset : pairOffset+pair.valueLen])
return pair
}
func uint16FromBytes(b []byte) uint16 {
i := uint16(binary.LittleEndian.Uint64(b))
return i
}
func uint16ToBytes(value uint16) []byte {
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, uint16(value))
return b
}