-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
141 lines (117 loc) · 2.31 KB
/
table.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package hio
import (
"bytes"
"encoding/gob"
"fmt"
"github.com/go-hep/rio"
)
type tableHeader struct {
Name string
Version uint32
Entries int64
}
func NewTable(f *File, name string) (*Table, error) {
var err error
table := &Table{
hdr: tableHeader{
Name: name,
Version: 0,
Entries: 0,
},
stream: f.f,
}
err = f.Set(name, table)
if err != nil {
return nil, err
}
return table, err
}
type Table struct {
hdr tableHeader
stream *rio.Stream
rec *rio.Record
doclose bool // whether we need to close the stream ourselves
}
func (table *Table) MarshalBinary(buf *bytes.Buffer) error {
enc := gob.NewEncoder(buf)
err := enc.Encode(&table.hdr)
return err
}
func (table *Table) UnmarshalBinary(buf *bytes.Buffer) error {
dec := gob.NewDecoder(buf)
err := dec.Decode(&table.hdr)
return err
}
func (table *Table) Name() string {
return table.hdr.Name
}
func (table *Table) Version() uint32 {
return table.hdr.Version
}
func (table *Table) setStream(w *rio.Stream) {
table.stream = w
}
func (table *Table) Close() error {
var err error
if table.stream != nil {
err = table.stream.Sync()
if err != nil {
return err
}
if table.doclose {
err = table.stream.Close()
if err != nil {
return err
}
}
}
table.stream = nil
return err
}
func (table *Table) Entries() int64 {
return table.hdr.Entries
}
func (table *Table) Write(ptr interface{}) error {
if table.rec == nil {
rec := table.stream.Record(table.hdr.Name)
if rec == nil {
return fmt.Errorf("hio: no such table [%s]", table.hdr.Name)
}
rec.SetCompress(true)
table.rec = rec
}
rec := table.rec
err := rec.Connect(table.hdr.Name, ptr)
if err != nil && err != rio.ErrBlockConnected {
return err
}
err = table.stream.WriteRecord(rec)
table.hdr.Entries++
return err
}
func (table *Table) Read(ptr interface{}) error {
if table.rec == nil {
rec := table.stream.Record(table.hdr.Name)
if rec == nil {
return fmt.Errorf("hio: no such table [%s]", table.hdr.Name)
}
rec.SetUnpack(true)
table.rec = rec
}
rec := table.rec
err := rec.Connect(table.hdr.Name, ptr)
if err != nil && err != rio.ErrBlockConnected {
return err
}
for {
rec, err = table.stream.ReadRecord()
if err != nil {
return err
}
if rec.Name() == table.hdr.Name {
break
}
}
return err
}
// EOF