forked from knakk/rdf
-
Notifications
You must be signed in to change notification settings - Fork 2
/
encoder.go
411 lines (373 loc) · 10.5 KB
/
encoder.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package rdf
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"sort"
)
// ErrEncoderClosed is the error returned from Encode() when the Triple/Quad-Encoder is closed
var ErrEncoderClosed = errors.New("Encoder is closed and cannot encode anymore")
// TripleEncoder serializes RDF Triples into one of the following formats:
// N-Triples, Turtle, RDF/XML.
//
// For streaming serialization, use the Encode() method to encode a single Triple
// at a time. Or, if you want to encode multiple triples in one batch, use EncodeAll().
// In either case; when done serializing, Close() must be called, to ensure
// that all writes are persisted, since the Encoder uses buffered IO.
type TripleEncoder struct {
format Format // Serialization format.
w *errWriter // Buffered writer. Set to nil when Encoder is closed.
Namespaces map[string]string // IRI->prefix custom mappings.
ns map[string]string // IRI->prefix mappings.
nsCount int // Counter to generate unique namespace prefixes
curSubj Subject // Keep track of current subject, to enable encoding of predicate lists.
curPred Predicate // Keep track of current subject, to enable encoding of object list.
OpenStatement bool // True when triple statement hasn't been closed (i.e. in a predicate/object list)
GenerateNamespaces bool // True to auto generate namespaces, false if you give it some custom namespaces and do not want generated ones
}
// NewTripleEncoder returns a new TripleEncoder capable of serializing into the
// given io.Writer in the given serialization format.
func NewTripleEncoder(w io.Writer, f Format) *TripleEncoder {
return &TripleEncoder{
format: f,
w: &errWriter{w: bufio.NewWriter(w)},
Namespaces: make(map[string]string),
ns: make(map[string]string),
GenerateNamespaces: true,
}
}
// Encode serializes a single Triple to the io.Writer of the TripleEncoder.
func (e *TripleEncoder) Encode(t Triple) error {
if e.w == nil {
return ErrEncoderClosed
}
switch e.format {
case NTriples:
_, err := e.w.w.Write([]byte(t.Serialize(e.format)))
if err != nil {
return err
}
case Turtle:
var s, p, o string
// object is allways rendered the same
o = e.prefixify(t.Obj)
if e.OpenStatement {
// potentially predicate/object list
// curSubj and curPred is set
if TermsEqual(e.curSubj, t.Subj) {
// In predicate or object list
if TermsEqual(e.curPred, t.Pred) {
// in object list
s = " ,\n\t"
p = ""
} else {
// in predicate list
p = e.prefixify(t.Pred)
// check if predicate introduced new prefix directive
if e.OpenStatement {
// in predicate list
s = " ;\n"
e.curPred = t.Pred
} else {
// previous statement closed
e.curSubj = t.Subj
s = e.prefixify(t.Subj)
e.curPred = t.Pred
}
}
} else {
// not in predicate/ojbect list
// close previous statement
e.w.write([]byte(" .\n"))
e.OpenStatement = false
p = e.prefixify(t.Pred)
e.curSubj = t.Subj
s = e.prefixify(t.Subj)
e.curPred = t.Pred
}
} else {
// either first statement, or after a prefix directive
p = e.prefixify(t.Pred)
s = e.prefixify(t.Subj)
e.curSubj = t.Subj
e.curPred = t.Pred
}
// allways keep statement open, in case next triple can mean predicate/object list
e.OpenStatement = true
e.w.write([]byte(s))
e.w.write([]byte("\t"))
e.w.write([]byte(p))
e.w.write([]byte("\t"))
e.w.write([]byte(o))
if e.w.err != nil {
return e.w.err
}
default:
panic("TODO")
}
return nil
}
// EncodeAll serializes a slice of Triples to the io.Writer of the TripleEncoder.
// It will ignore duplicate triples.
//
// Note that this function will modify the given slice of triples by sorting it in-place.
func (e *TripleEncoder) EncodeAll(ts []Triple) error {
if e.w == nil {
return ErrEncoderClosed
}
switch e.format {
case NTriples:
for _, t := range ts {
_, err := e.w.w.Write([]byte(t.Serialize(e.format)))
if err != nil {
return err
}
}
case Turtle:
// Sort triples by Subject, then Predicate, to maximize predicate and object lists.
sort.Sort(bySubjectThenPred(triples(ts)))
var s, p, o string
for i, t := range ts {
// object is allways rendered the same
o = e.prefixify(t.Obj)
if e.OpenStatement {
// potentially predicate/object list
// curSubj and curPred is set
if TermsEqual(e.curSubj, t.Subj) {
// In predicate or object list
if TermsEqual(e.curPred, t.Pred) {
// in object list
// check if this triple is a duplicate of the preceeding triple
if i > 0 && TermsEqual(t.Obj, ts[i-1].Obj) {
continue
}
s = " ,\n\t"
p = ""
} else {
// in predicate list
p = e.prefixify(t.Pred)
// check if predicate introduced new prefix directive
if e.OpenStatement {
// in predicate list
s = " ;\n"
e.curPred = t.Pred
} else {
// previous statement closed
e.curSubj = t.Subj
s = e.prefixify(t.Subj)
e.curPred = t.Pred
}
}
} else {
// not in predicate/ojbect list
// close previous statement
e.w.write([]byte(" .\n"))
e.OpenStatement = false
p = e.prefixify(t.Pred)
e.curSubj = t.Subj
s = e.prefixify(t.Subj)
e.curPred = t.Pred
}
} else {
// either first statement, or after a prefix directive
p = e.prefixify(t.Pred)
s = e.prefixify(t.Subj)
e.curSubj = t.Subj
e.curPred = t.Pred
}
// allways keep statement open, in case next triple can mean predicate/object list
e.OpenStatement = true
e.w.write([]byte(s))
e.w.write([]byte("\t"))
e.w.write([]byte(p))
e.w.write([]byte("\t"))
e.w.write([]byte(o))
if e.w.err != nil {
return e.w.err
}
}
default:
panic("TODO")
}
return nil
}
// Close finalizes an encoding session, ensuring that any concluding tokens are
// written should it be needed (eg.g close the root tag for RDF/XML) and
// flushes the underlying buffered writer of the encoder.
//
// The encoder cannot encode anymore when Close() has been called.
func (e *TripleEncoder) Close() error {
if e.OpenStatement {
e.w.write([]byte(" .")) // Close final statement
if e.w.err != nil {
return e.w.err
}
}
err := e.w.w.Flush()
e.w = nil
return err
}
func (e *TripleEncoder) prefixify(t Term) string {
if t.Type() == TermIRI {
if t.(IRI).str == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" {
return "a"
}
first, rest := t.(IRI).Split()
if first == "" {
// cannot split into prefix and namespace
return t.Serialize(Turtle)
}
prefix, ok := e.ns[first]
if !ok {
custom, ok := e.Namespaces[first]
if ok {
//we have a custom namespace specified, use that
prefix = custom
} else {
if !e.GenerateNamespaces {
return t.Serialize(Turtle)
}
prefix = fmt.Sprintf("ns%d", e.nsCount)
e.nsCount++
}
e.ns[first] = prefix
if e.OpenStatement {
e.w.write([]byte(" .\n"))
}
e.w.write([]byte(fmt.Sprintf("@prefix %s:\t<%s> .\n", prefix, first)))
e.OpenStatement = false
}
return fmt.Sprintf("%s:%s", prefix, rest)
}
if t.Type() == TermLiteral {
switch t.(Literal).DataType {
case xsdString, xsdInteger, xsdBoolean, xsdDouble, xsdDecimal, rdfLangString:
// serialize normally in Literal.Serialize method
break
default:
first, rest := t.(Literal).DataType.Split()
if first == "" {
return t.Serialize(Turtle)
}
prefix, ok := e.ns[first]
if !ok {
custom, ok := e.Namespaces[first]
if ok {
//we have a custom namespace specified, use that
prefix = custom
} else {
if !e.GenerateNamespaces {
return t.Serialize(Turtle)
}
prefix = fmt.Sprintf("ns%d", e.nsCount)
e.nsCount++
}
e.ns[first] = prefix
if e.OpenStatement {
e.w.write([]byte(" .\n"))
}
e.w.write([]byte(fmt.Sprintf("@prefix %s:\t<%s> .\n", prefix, first)))
e.OpenStatement = false
}
return fmt.Sprintf("\"%s\"^^%s:%s", t.Serialize(formatInternal), prefix, rest)
}
}
return t.Serialize(Turtle)
}
func escapeLocal(rest string) string {
// escape rest according to PN_LOCAL
// http://www.w3.org/TR/turtle/#reserved
var b bytes.Buffer
for _, r := range rest {
if int(r) <= 126 && int(r) >= 33 {
// only bother to check if rune is in range
switch r {
case '_', '~', '.', '-', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', '/', '?', '#', '@', '%':
b.WriteRune('\\')
b.WriteRune(r)
default:
b.WriteRune(r)
}
} else {
b.WriteRune(r)
}
}
// TODO should also ensure that last character is not '.'
return b.String()
}
type triples []Triple
type bySubjectThenPred triples
func (t bySubjectThenPred) Len() int {
return len(t)
}
func (t bySubjectThenPred) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t bySubjectThenPred) Less(i, j int) bool {
// todo implement custom comparestring function wich returns -1 0 1 for less, equal, greater
// https://groups.google.com/forum/#!topic/golang-nuts/5mMdKvkxWxo
// see also bytes.Compare
p, q := t[i].Subj.Serialize(NTriples), t[j].Subj.Serialize(NTriples)
switch {
case p < q:
return true
case q < p:
return false
default:
// subjects are equal, continue by comparing predicates
return t[i].Pred.Serialize(NTriples) < t[j].Pred.Serialize(NTriples)
}
}
type errWriter struct {
w *bufio.Writer
err error
}
func (ew *errWriter) write(buf []byte) {
if ew.err != nil {
return
}
_, ew.err = ew.w.Write(buf)
}
// QuadEncoder serializes RDF Quads. Currently only supports N-Quads.
type QuadEncoder struct {
w *errWriter
}
// NewQuadEncoder returns a new QuadEncoder on the given writer. The only supported
// format is NQuads.
func NewQuadEncoder(w io.Writer, f Format) *QuadEncoder {
if f != NQuads {
panic("NewQuadEncoder: only N-Quads format supported ATM")
}
return &QuadEncoder{
w: &errWriter{w: bufio.NewWriter(w)},
}
}
// Encode encodes a Quad.
func (e *QuadEncoder) Encode(q Quad) error {
_, err := e.w.w.Write([]byte(q.Serialize(NQuads)))
if err != nil {
return err
}
return nil
}
// EncodeAll encodes all quads.
func (e *QuadEncoder) EncodeAll(qs []Quad) error {
if e.w == nil {
return ErrEncoderClosed
}
for _, q := range qs {
_, err := e.w.w.Write([]byte(q.Serialize(NQuads)))
if err != nil {
return err
}
}
return nil
}
// Close closes the encoder and flushes the underlying buffering writer.
func (e *QuadEncoder) Close() error {
err := e.w.w.Flush()
e.w = nil
return err
}