-
Notifications
You must be signed in to change notification settings - Fork 0
/
constructor.go
62 lines (59 loc) · 1.03 KB
/
constructor.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
package constructor
import (
"encoding/json"
"fmt"
"io"
)
func Construct(r io.Reader) (Node, error) {
var v any
dec := json.NewDecoder(r)
dec.UseNumber()
if err := dec.Decode(&v); err != nil {
return nil, err
}
return constructAny(v)
}
func constructAny(v any) (Node, error) {
switch v := v.(type) {
case nil:
return &Optional{
Type: new(Any),
}, nil
case string:
return new(String), nil
case json.Number:
return new(Number), nil
case map[string]any:
types := make(map[string]Node)
for k, v := range v {
v, err := constructAny(v)
if err != nil {
return nil, err
}
types[k] = v
}
return NewStruct(types), nil
case []any:
var a Array
for _, v := range v {
v, err := constructAny(v)
if err != nil {
return nil, err
}
if a.Type != nil {
if !a.Type.Equals(v) {
t, err := a.Type.Combine(v)
if err != nil {
return nil, err
}
a.Type = t
}
} else {
a.Type = v
}
}
return &a, nil
default:
return nil, fmt.Errorf("unexpected type %T", v)
}
}