-
Notifications
You must be signed in to change notification settings - Fork 0
/
schemadbwriter.go
66 lines (57 loc) · 1.73 KB
/
schemadbwriter.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
package goschema
import (
"io"
"github.com/chasingcarrots/gobinary"
)
type SchemaDBWriter struct {
schemaIndex map[SchemaID]SchemaDataEntry
stream *gobinary.StreamWriter
writer gobinary.HighLevelWriter
originalOffset int64
}
func MakeSchemaDBWriter(stream *gobinary.StreamWriter) SchemaDBWriter {
dbWriter := SchemaDBWriter{
schemaIndex: make(map[SchemaID]SchemaDataEntry),
stream: stream,
originalOffset: stream.Offset(),
writer: gobinary.MakeHighLevelWriter(stream),
}
// reserve 2 bytes for the number of schemas
dbWriter.writer.WriteUInt16(0)
return dbWriter
}
func (sd *SchemaDBWriter) FindSchema(id SchemaID) (SchemaDataEntry, bool) {
entry, ok := sd.schemaIndex[id]
return entry, ok
}
func (sd *SchemaDBWriter) RegisterSchema(schema Schema) int {
if entry, ok := sd.schemaIndex[schema.ID()]; ok {
return entry.index
}
entries := schema.Describe()
sd.writer.WriteUInt16(uint16(len(entries)))
for i := range entries {
sd.writer.WriteUInt16(uint16(len(entries[i].Name)))
sd.writer.WriteString(entries[i].Name)
sd.writer.WriteUInt8(uint8(entries[i].Type))
sd.writer.WriteUInt32(entries[i].Offset)
}
idx := len(sd.schemaIndex)
sd.schemaIndex[schema.ID()] = SchemaDataEntry{
schema: schema,
index: idx,
}
return idx
}
func (sd *SchemaDBWriter) Close() {
offset := sd.stream.Offset()
sd.stream.Seek(sd.originalOffset, io.SeekStart)
sd.writer.WriteUInt16(uint16(len(sd.schemaIndex)))
sd.stream.Seek(offset, io.SeekStart)
}
type SchemaDataEntry struct {
schema Schema
index int
}
func (sde *SchemaDataEntry) Schema() Schema { return sde.schema }
func (sde *SchemaDataEntry) Index() int { return sde.index }