-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
69 lines (59 loc) · 1.67 KB
/
block.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
package simpledb
import (
"bytes"
"encoding/binary"
"os"
"unsafe"
"github.com/kkonat/simpledb/hash"
)
type blockHeader struct {
Length uint32 // uppercase, because must be exportable for binary encoding
Id ID
KeyHash hash.Type
KeyLen uint32 // can not be uint16, data is 32-bit word-aligned anyway, sizeof will return untrue no. of bytes
DataLen uint32 // can not be uint
}
func (b *blockHeader) read(file *os.File) (err error) {
return binary.Read(file, binary.LittleEndian, b)
}
func blockheadersSize() int {
return int(unsafe.Sizeof(blockHeader{}))
}
func (b *blockHeader) getBytes() (header []byte) {
buff := bytes.NewBuffer(header)
binary.Write(buff, binary.LittleEndian, b)
return buff.Bytes()
}
type block struct {
blockHeader
key string
value []byte
}
func NewBlock(id ID, key string, value []byte) *block {
var header blockHeader
headerLen := blockheadersSize()
blockLen := headerLen + len(key) + len(value)
header = blockHeader{
Id: id,
KeyHash: hash.Get(key),
KeyLen: uint32(len(key)),
DataLen: uint32(len(value)),
Length: uint32(blockLen),
}
block := &block{blockHeader: header, key: key, value: value}
return block
}
func (b *block) getBytes() []byte {
headerBytes := b.blockHeader.getBytes()
blockBytes := append(headerBytes, b.key...)
blockBytes = append(blockBytes, b.value...)
return blockBytes
}
func (b *block) setBytes(blockBytes []byte) {
buff := bytes.NewBuffer(blockBytes)
binary.Read(buff, binary.LittleEndian, &(b.blockHeader))
keyStart := int(unsafe.Sizeof(blockHeader{}))
valueStart := keyStart + int(b.blockHeader.KeyLen)
b.key = string(blockBytes[keyStart:valueStart])
b.value = blockBytes[valueStart:]
}