-
Notifications
You must be signed in to change notification settings - Fork 7
/
value.go
560 lines (487 loc) · 13.1 KB
/
value.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package quad
import (
"crypto/sha1"
"fmt"
"hash"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cayleygraph/quad/voc"
"github.com/cayleygraph/quad/voc/schema"
"github.com/cayleygraph/quad/voc/xsd"
)
// IsValidValue checks if the value is valid. It returns false if the value is nil, an empty IRI or an empty BNode.
func IsValidValue(v Value) bool {
if v == nil {
return false
}
switch v := v.(type) {
case IRI:
return v != ""
case BNode:
return v != ""
}
return true
}
// Value is a type used by all quad directions.
type Value interface {
String() string
// Native converts Value to a closest native Go type.
//
// If type has no analogs in Go, Native return an object itself.
Native() interface{}
}
var (
_ Identifier = IRI("")
_ Identifier = BNode("")
)
// Identifier is a union of IRI and BNode.
type Identifier interface {
Value
isIdentifier()
}
type TypedStringer interface {
TypedString() TypedString
}
// Equaler interface is implemented by values, that needs a special equality check.
type Equaler interface {
Equal(v Value) bool
}
// HashSize is a size of the slice, returned by HashOf.
const HashSize = sha1.Size
var hashPool = sync.Pool{
New: func() interface{} { return sha1.New() },
}
// HashOf calculates a hash of value v.
func HashOf(v Value) []byte {
key := make([]byte, HashSize)
HashTo(v, key)
return key
}
// HashTo calculates a hash of value v, storing it in a slice p.
func HashTo(v Value, p []byte) {
h := hashPool.Get().(hash.Hash)
h.Reset()
defer hashPool.Put(h)
if len(p) < HashSize {
panic("buffer too small to fit the hash")
}
if v != nil {
// TODO(kortschak,dennwc) Remove dependence on String() method.
h.Write([]byte(v.String()))
}
h.Sum(p[:0])
}
// StringOf safely call v.String, returning empty string in case of nil Value.
func StringOf(v Value) string {
if v == nil {
return ""
}
return v.String()
}
// NativeOf safely call v.Native, returning nil in case of nil Value.
func NativeOf(v Value) interface{} {
if v == nil {
return nil
}
return v.Native()
}
// AsValue converts native type into closest Value representation.
// It returns false if type was not recognized.
func AsValue(v interface{}) (out Value, ok bool) {
if v == nil {
return nil, true
}
switch v := v.(type) {
case Value:
out = v
case string:
out = String(v)
case int:
out = Int(v)
case int8:
out = Int(v)
case int16:
out = Int(v)
case int32:
out = Int(v)
case int64:
out = Int(v)
case uint:
out = Int(v)
case uint8:
out = Int(v)
case uint16:
out = Int(v)
case uint32:
out = Int(v)
case uint64:
out = Int(v)
case float64:
out = Float(v)
case float32:
out = Float(v)
case bool:
out = Bool(v)
case time.Time:
out = Time(v)
default:
return nil, false
}
return out, true
}
// StringToValue is a function to convert strings to typed
// quad values.
//
// Warning: should not be used directly - will be deprecated.
func StringToValue(v string) Value {
if v == "" {
return nil
}
if len(v) > 2 {
if v[0] == '<' && v[len(v)-1] == '>' {
return IRI(v[1 : len(v)-1])
} else if v[:2] == "_:" {
return BNode(v[2:])
} else if i := strings.Index(v, `"^^<`); i > 0 && v[0] == '"' && v[len(v)-1] == '>' {
return TypedString{Value: String(v[1:i]), Type: IRI(v[i+4 : len(v)-1])}
} else if i := strings.Index(v, `"@`); i > 0 && v[0] == '"' && v[len(v)-1] != '"' {
return LangString{Value: String(v[1:i]), Lang: v[i+2:]}
}
}
return String(v)
}
// ToString casts a values to String or falls back to StringOf.
func ToString(v Value) string {
if s, ok := v.(String); ok {
return string(s)
}
return StringOf(v)
}
// Raw is a Turtle/NQuads-encoded value.
//
// Deprecated: use IRI or String instead.
func Raw(s string) Value {
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return String(s[1 : len(s)-1])
}
return StringToValue(s)
}
// String is an RDF string value (ex: "name").
type String string
var escaper = strings.NewReplacer(
"\\", "\\\\",
"\"", "\\\"",
"\n", "\\n",
"\r", "\\r",
"\t", "\\t",
)
func (s String) String() string {
//TODO(barakmich): Proper escaping.
return `"` + escaper.Replace(string(s)) + `"`
}
func (s String) GoString() string {
return "quad.String(" + strconv.Quote(string(s)) + ")"
}
func (s String) Native() interface{} { return string(s) }
// TypedString is an RDF value with type (ex: "name"^^<type>).
type TypedString struct {
Value String
Type IRI
}
func (s TypedString) String() string {
return s.Value.String() + `^^` + s.Type.String()
}
func (s TypedString) Native() interface{} {
if s.Type == "" {
return s.Value.Native()
}
if v, err := s.ParseValue(); err == nil && v != s {
return v.Native()
}
return s
}
// ParseValue will try to parse underlying string value using registered functions.
//
// It will return unchanged value if suitable function is not available.
//
// Error will be returned if the type was recognizes, but parsing failed.
func (s TypedString) ParseValue() (Value, error) {
fnc := knownConversions[s.Type.Full()]
if fnc == nil {
return s, nil
}
return fnc(string(s.Value))
}
// LangString is an RDF string with language (ex: "name"@lang).
type LangString struct {
Value String
Lang string
}
func (s LangString) String() string {
return s.Value.String() + `@` + s.Lang
}
func (s LangString) Native() interface{} { return s.Value.Native() }
// IRIFormat is a format of IRI.
type IRIFormat int
const (
// IRIDefault preserves current IRI formatting.
IRIDefault = IRIFormat(iota)
// IRIShort changes IRI to use a short namespace prefix (ex: <rdf:type>).
IRIShort
// IRIFull changes IRI to use full form (ex: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>).
IRIFull
)
// IRI is an RDF Internationalized Resource Identifier (ex: <name>).
type IRI string
// isIdentifier implements Identifier.
func (s IRI) isIdentifier() {}
// String prints IRI in "<iri>" form.
func (s IRI) String() string { return `<` + string(s) + `>` }
// Format the IRI according to selection.
func (s IRI) Format(format IRIFormat) IRI {
switch format {
case IRIShort:
return s.Short()
case IRIFull:
return s.Full()
}
return s
}
// GoString overrides IRI's %#v printing behaviour to include the type name.
func (s IRI) GoString() string {
return "quad.IRI(" + strconv.Quote(string(s)) + ")"
}
// Short uses voc package to convert a full IRI prefix (if any) to a short namespace prefix.
// The prefix must be registered in the voc package.
func (s IRI) Short() IRI {
return IRI(voc.ShortIRI(string(s)))
}
// Full uses voc package to convert a short namespace prefix (if any) to a full IRI prefix.
// The prefix must be registered in the voc package.
func (s IRI) Full() IRI {
return IRI(voc.FullIRI(string(s)))
}
// Native returns an IRI value unchanged (to not collide with String values).
func (s IRI) Native() interface{} {
return s
}
// ShortWith uses the provided namespace to convert a full IRI prefix (if any) to a short namespace prefix.
func (s IRI) ShortWith(n *voc.Namespaces) IRI {
return IRI(n.ShortIRI(string(s)))
}
// FullWith uses provided namespace to convert a short namespace prefix (if any) to a full IRI prefix.
func (s IRI) FullWith(n *voc.Namespaces) IRI {
return IRI(n.FullIRI(string(s)))
}
// BNode is an RDF Blank Node (ex: _:name).
type BNode string
// isIdentifier implements Identifier.
func (s BNode) isIdentifier() {}
func (s BNode) String() string { return `_:` + string(s) }
func (s BNode) GoString() string {
return "quad.BNode(" + strconv.Quote(string(s)) + ")"
}
func (s BNode) Native() interface{} { return s }
// Native support for basic types
// StringConversion is a function to convert string values with a
// specific IRI type to their native equivalents.
type StringConversion func(string) (Value, error)
// Following the JSON-LD specification: https://w3c.github.io/json-ld-syntax/#conversion-of-native-data-types
const (
defaultStringType IRI = xsd.String
defaultIntType IRI = xsd.Integer
defaultFloatType IRI = xsd.Double
defaultBoolType IRI = xsd.Boolean
defaultTimeType IRI = xsd.DateTime
)
// KnownIntTypes consists of known IRIs of integer types
var KnownIntTypes = []IRI{
defaultIntType,
xsd.Int,
xsd.Long,
schema.Integer,
}
// KnownBoolTypes consists of known IRIs of boolean types
var KnownBoolTypes = []IRI{
defaultBoolType,
schema.Boolean,
}
// KnownFloatTypes consists of known IRIs of floating-point numbers types
var KnownFloatTypes = []IRI{
defaultFloatType,
xsd.Float,
schema.Float,
schema.Number,
}
// KnownTimeTypes consists of known IRIs of datetime types
var KnownTimeTypes = []IRI{
defaultTimeType,
xsd.DateTime,
schema.DateTime,
}
func init() {
// string types
RegisterStringConversion(defaultStringType, stringToString)
// int types
RegisterStringConversions(KnownIntTypes, stringToInt)
// bool types
RegisterStringConversions(KnownBoolTypes, stringToBool)
// float types
RegisterStringConversions(KnownFloatTypes, stringToFloat)
// time types
RegisterStringConversions(KnownTimeTypes, stringToTime)
}
var knownConversions = make(map[IRI]StringConversion)
// RegisterStringConversion will register an automatic conversion of
// TypedString values with provided type to a native equivalent such as Int, Time, etc.
//
// If fnc is nil, automatic conversion from selected type will be removed.
func RegisterStringConversion(dataType IRI, fnc StringConversion) {
if fnc == nil {
delete(knownConversions, dataType)
} else {
knownConversions[dataType] = fnc
if short := dataType.Short(); short != dataType {
knownConversions[short] = fnc
}
if full := dataType.Full(); full != dataType {
knownConversions[full] = fnc
}
}
}
// RegisterStringConversions calls RegisterStringConversion with every IRI in dataTypes and fnc
func RegisterStringConversions(dataTypes []IRI, fnc StringConversion) {
for _, iri := range dataTypes {
RegisterStringConversion(iri, fnc)
}
}
// HasStringConversion returns whether IRI has a string conversion
func HasStringConversion(dataType IRI) bool {
_, ok := knownConversions[dataType]
return ok
}
func stringToString(s string) (Value, error) {
return String(s), nil
}
func stringToInt(s string) (Value, error) {
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return nil, err
}
return Int(v), nil
}
func stringToBool(s string) (Value, error) {
v, err := strconv.ParseBool(s)
if err != nil {
return nil, err
}
return Bool(v), nil
}
func stringToFloat(s string) (Value, error) {
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, err
}
return Float(v), nil
}
func stringToTime(s string) (Value, error) {
v, err := time.Parse(time.RFC3339, s)
if err != nil {
return nil, err
}
return Time(v), nil
}
// Int is a native wrapper for int64 type.
//
// It uses NQuad notation similar to TypedString.
type Int int64
func (s Int) String() string {
return s.TypedString().String()
}
func (s Int) Native() interface{} { return int64(s) }
func (s Int) TypedString() TypedString {
return TypedString{
Value: String(strconv.Itoa(int(s))),
Type: defaultIntType,
}
}
// Float is a native wrapper for float64 type.
//
// It uses NQuad notation similar to TypedString.
type Float float64
func (s Float) String() string {
return s.TypedString().String()
}
func (s Float) Native() interface{} { return float64(s) }
func (s Float) TypedString() TypedString {
return TypedString{
Value: String(strconv.FormatFloat(float64(s), 'E', -1, 64)),
Type: defaultFloatType,
}
}
// Bool is a native wrapper for bool type.
//
// It uses NQuad notation similar to TypedString.
type Bool bool
func (s Bool) String() string {
if bool(s) {
return `"True"^^<` + string(defaultBoolType) + `>`
}
return `"False"^^<` + string(defaultBoolType) + `>`
}
func (s Bool) Native() interface{} { return bool(s) }
func (s Bool) TypedString() TypedString {
v := "False"
if bool(s) {
v = "True"
}
return TypedString{
Value: String(v),
Type: defaultBoolType,
}
}
var _ Equaler = Time{}
// Time is a native wrapper for time.Time type.
//
// It uses NQuad notation similar to TypedString.
type Time time.Time
func (s Time) String() string {
return s.TypedString().String()
}
func (s Time) Native() interface{} { return time.Time(s) }
func (s Time) Equal(v Value) bool {
t, ok := v.(Time)
if !ok {
return false
}
return time.Time(s).Equal(time.Time(t))
}
func (s Time) TypedString() TypedString {
return TypedString{
// TODO(dennwc): this is used to compute hash, thus we might want to include nanos
Value: String(time.Time(s).UTC().Format(time.RFC3339)),
Type: defaultTimeType,
}
}
type ByValueString []Value
func (o ByValueString) Len() int { return len(o) }
func (o ByValueString) Less(i, j int) bool { return StringOf(o[i]) < StringOf(o[j]) }
func (o ByValueString) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
// Sequence is an object to generate a sequence of Blank Nodes.
type Sequence struct {
last uint64
}
// Next returns a new blank node. It's safe for concurrent use.
func (s *Sequence) Next() BNode {
n := atomic.AddUint64(&s.last, 1)
return BNode(fmt.Sprintf("n%d", n))
}
var randSource = rand.New(rand.NewSource(time.Now().UnixNano()))
// RandomBlankNode returns a randomly generated Blank Node.
func RandomBlankNode() BNode {
return BNode(fmt.Sprintf("n%d", randSource.Int()))
}