-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreters.go
86 lines (75 loc) · 2.12 KB
/
interpreters.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
package xl8r
import "fmt"
var _ Interpreter[int, int] = (*convertr[int, int])(nil) //contract
type convertr[P, H any] struct {
codecs codecMap[P, H]
}
// creates a new Interpreter instance based on the specified Codecs
func New[P, H any](codecs ...Codec[P, H]) (r Interpreter[P, H], e error) {
cdMap := make(codecMap[P, H])
cdMap.addCodecs(codecs...)
if numCodecs := len(cdMap); numCodecs < 2 {
e = fmt.Errorf("need codecs > 1, received [ %d ]", numCodecs)
return
}
r = &convertr[P, H]{
codecs: cdMap,
}
return
}
func (x *convertr[P, H]) getCodecIf(name string) (c Codec[P, H], b bool) {
return x.codecs.getIf(name)
}
func (x *convertr[P, H]) To(dest, source string, content P, opts0 ...Opts) (r P, e error) {
if origin, hasOrigin := x.getCodecIf(source); hasOrigin {
if destination, hasDestination := x.getCodecIf(dest); hasDestination {
if hubData, err := origin.Encode(content, opts0...); err == nil {
r, e = destination.Decode(hubData, opts0...)
return
} else {
e = err
}
} else {
e = fmt.Errorf("no decoder [ '%s'<- ]", dest)
}
} else {
e = fmt.Errorf("no encoder [ <-'%s' ]", source)
}
return
}
func (x *convertr[P, H]) Decode(dest string, hubData H, opts0 ...Opts) (r P, e error) {
if destination, hasDestination := x.getCodecIf(dest); hasDestination {
r, e = destination.Decode(hubData, opts0...)
} else {
e = fmt.Errorf("no decoder [ '%s'<- ]", dest)
}
return
}
func (x *convertr[P, H]) Encode(source string, content P, opts0 ...Opts) (r H, e error) {
if origin, hasOrigin := x.getCodecIf(source); hasOrigin {
r, e = origin.Encode(content, opts0...)
} else {
e = fmt.Errorf("no encoder [ <-'%s' ]", source)
}
return
}
func (x *convertr[P, H]) Origins(content0 ...P) (r []string) {
if len(content0) == 0 {
r = x.codecs.keys()
return
}
codecs := make(codecMap[P, H])
for _, content := range content0 {
for name, origin := range x.codecs {
if _, exists := codecs.getIf(name); !exists && origin.Evaluate(content) {
codecs[name] = origin
}
}
}
r = codecs.keys()
return
}
func (x *convertr[P, H]) Knows(name string) (r bool) {
_, r = x.getCodecIf(name)
return
}