-
Notifications
You must be signed in to change notification settings - Fork 11
/
decode.go
301 lines (257 loc) · 6.3 KB
/
decode.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package triplestore
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
"sync"
)
type Decoder interface {
Decode() ([]Triple, error)
}
type DecodeResult struct {
Tri Triple
Err error
}
type StreamDecoder interface {
StreamDecode(context.Context) <-chan DecodeResult
}
// Use for retro compatibilty when changing file format on existing stores
func NewAutoDecoder(r io.Reader) Decoder {
ok, newR := IsNTFormat(r)
if ok {
return NewLenientNTDecoder(newR)
}
return NewBinaryDecoder(newR)
}
// Loosely detect if a ntriples format contrary to a binary format
// Used for retro compatibilty when changing file format on existing stores
// Detecttion work with ntriples format flushed by this library (i.e. no comment, no spaces, ...)
func IsNTFormat(r io.Reader) (bool, io.Reader) {
firstChar := make([]byte, 1)
multi := io.MultiReader(bytes.NewReader(firstChar), r)
if _, err := r.Read(firstChar); err != nil {
return false, multi
}
return bytes.Equal(firstChar, []byte{'<'}), multi
}
func NewLenientNTDecoder(r io.Reader) Decoder {
return &ntDecoder{r: r}
}
func NewLenientNTStreamDecoder(r io.Reader) StreamDecoder {
return &ntDecoder{r: r}
}
type ntDecoder struct {
r io.Reader
}
func (d *ntDecoder) Decode() ([]Triple, error) {
return newLenientNTParser(d.r).Parse()
}
func (d *ntDecoder) StreamDecode(ctx context.Context) <-chan DecodeResult {
decC := make(chan DecodeResult)
go func() {
defer close(decC)
scanner := bufio.NewScanner(d.r)
for {
select {
case <-ctx.Done():
return
default:
if scanner.Scan() {
tris, err := newLenientNTParser(strings.NewReader(scanner.Text())).Parse()
if err != nil {
decC <- DecodeResult{Err: err}
} else if len(tris) == 1 {
decC <- DecodeResult{Tri: tris[0]}
}
} else {
if err := scanner.Err(); err != nil {
decC <- DecodeResult{Err: err}
}
return
}
}
}
}()
return decC
}
type binaryDecoder struct {
r io.Reader
rc io.ReadCloser // for stream decoding
triples []Triple
}
func NewBinaryStreamDecoder(r io.ReadCloser) StreamDecoder {
return &binaryDecoder{rc: r}
}
func (dec *binaryDecoder) StreamDecode(ctx context.Context) <-chan DecodeResult {
decC := make(chan DecodeResult)
go func() {
defer close(decC)
for {
select {
case <-ctx.Done():
return
default:
tri, done, err := decodeTriple(dec.rc)
if done {
return
}
decC <- DecodeResult{Tri: tri, Err: err}
}
}
}()
return decC
}
func NewBinaryDecoder(r io.Reader) Decoder {
return &binaryDecoder{r: r}
}
func (dec *binaryDecoder) Decode() ([]Triple, error) {
var out []Triple
for {
tri, done, err := decodeTriple(dec.r)
if tri != nil {
out = append(out, tri)
}
if done {
break
} else if err != nil {
return out, err
}
}
return out, nil
}
func decodeTriple(r io.Reader) (Triple, bool, error) {
var isSubBNode bool
err := binary.Read(r, binary.BigEndian, &isSubBNode)
if err == io.EOF {
return nil, true, nil
} else if err != nil {
return nil, false, fmt.Errorf("is subject bnode: %s", err)
}
sub, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("subject: %s", err)
}
pred, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("predicate: %s", err)
}
var objType uint8
if err := binary.Read(r, binary.BigEndian, &objType); err != nil {
return nil, false, fmt.Errorf("object type: %s", err)
}
var decodedObj object
if objType == resourceTypeEncoding {
resource, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("resource: %s", err)
}
decodedObj.resource = string(resource)
} else if objType == bnodeTypeEncoding {
bnode, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("bnode object: %s", err)
}
decodedObj.bnode = string(bnode)
decodedObj.isBnode = true
} else {
decodedObj.isLit = true
var decodedLiteral literal
if objType == literalWithLangEncoding {
lang, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("lang: %s", err)
}
decodedLiteral.langtag = string(lang)
} else {
litType, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("literate type: %s", err)
}
decodedLiteral.typ = XsdType(litType)
}
val, err := readWord(r)
if err != nil {
return nil, false, fmt.Errorf("literate: %s", err)
}
if decodedLiteral.typ == XsdString || objType == literalWithLangEncoding {
decodedLiteral.val = unescapeStringLiteral(string(val))
} else {
decodedLiteral.val = string(val)
}
decodedObj.lit = decodedLiteral
}
return &triple{
isSubBnode: isSubBNode,
sub: string(sub),
pred: string(pred),
obj: decodedObj,
}, false, nil
}
func readWord(r io.Reader) ([]byte, error) {
var len wordLength
if err := binary.Read(r, binary.BigEndian, &len); err != nil {
return nil, err
}
word := make([]byte, len)
if _, err := io.ReadFull(r, word); err != nil {
return nil, fmt.Errorf("triplestore: binary: cannot decode word of length %d bytes: %s", len, err)
}
return word, nil
}
type datasetDecoder struct {
newDecoderFunc func(io.Reader) Decoder
rs []io.Reader
}
// NewDatasetDecoder - a dataset is a basically a collection of RDFGraph.
func NewDatasetDecoder(fn func(io.Reader) Decoder, readers ...io.Reader) Decoder {
return &datasetDecoder{newDecoderFunc: fn, rs: readers}
}
func (dec *datasetDecoder) Decode() ([]Triple, error) {
type result struct {
err error
tris []Triple
reader io.Reader
}
results := make(chan *result, len(dec.rs))
done := make(chan struct{})
defer close(done)
var wg sync.WaitGroup
for _, reader := range dec.rs {
wg.Add(1)
go func(r io.Reader) {
defer wg.Done()
tris, err := dec.newDecoderFunc(r).Decode()
select {
case results <- &result{tris: tris, err: err, reader: r}:
case <-done:
return
}
}(reader)
}
go func() {
wg.Wait()
close(results)
}()
var all []Triple
for r := range results {
if r.err != nil {
switch rr := r.reader.(type) {
case *os.File:
return all, fmt.Errorf("file '%s': %s", rr.Name(), r.err)
default:
return all, r.err
}
}
all = append(all, r.tris...)
}
return all, nil
}
var unescaper = strings.NewReplacer("\\n", "\n", "\\r", "\r")
func unescapeStringLiteral(s string) string {
return unescaper.Replace(s)
}