/
block.go
69 lines (58 loc) · 1.35 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
// Copyright 2015 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rio
import (
"bytes"
"reflect"
)
// Block manages and desribes a block of data
type Block struct {
raw rioBlock
typ reflect.Type
}
func newBlock(name string, version Version) Block {
block := Block{
raw: rioBlock{
Header: rioHeader{
Len: 0,
Frame: blkFrame,
},
Version: version,
Name: name,
},
}
return block
}
// Name returns the name of this block
func (blk *Block) Name() string {
return blk.raw.Name
}
// RioVersion returns the rio-binary version of the block
func (blk *Block) RioVersion() Version {
return blk.raw.Version
}
// Write writes data to the Writer, in the rio format
func (blk *Block) Write(data interface{}) error {
var err error
buf := new(bytes.Buffer) // FIXME(sbinet): use a sync.Pool
enc := encoder{w: buf}
err = enc.Encode(data)
if err != nil {
return err
}
blk.raw.Data = buf.Bytes()
blk.raw.Header.Len = uint32(len(blk.raw.Data))
return nil
}
// Read reads data from the Reader, in the rio format
func (blk *Block) Read(data interface{}) error {
var err error
buf := bytes.NewReader(blk.raw.Data) // FIXME(sbinet): use a sync.Pool
dec := decoder{r: buf}
err = dec.Decode(data)
if err != nil {
return err
}
return err
}