-
-
Notifications
You must be signed in to change notification settings - Fork 530
/
Copy pathadd.go
82 lines (74 loc) · 1.94 KB
/
add.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
package tag
import (
"fmt"
"math"
"strconv"
"time"
"github.com/BurntSushi/toml/internal"
)
// Add JSON tags to a data structure as expected by toml-test.
func Add(key string, tomlData any) any {
// Switch on the data type.
switch orig := tomlData.(type) {
default:
panic(fmt.Sprintf("Unknown type: %T", tomlData))
// A table: we don't need to add any tags, just recurse for every table
// entry.
case map[string]any:
typed := make(map[string]any, len(orig))
for k, v := range orig {
typed[k] = Add(k, v)
}
return typed
// An array: we don't need to add any tags, just recurse for every table
// entry.
case []map[string]any:
typed := make([]map[string]any, len(orig))
for i, v := range orig {
typed[i] = Add("", v).(map[string]any)
}
return typed
case []any:
typed := make([]any, len(orig))
for i, v := range orig {
typed[i] = Add("", v)
}
return typed
// Datetime: tag as datetime.
case time.Time:
switch orig.Location() {
default:
return tag("datetime", orig.Format("2006-01-02T15:04:05.999999999Z07:00"))
case internal.LocalDatetime:
return tag("datetime-local", orig.Format("2006-01-02T15:04:05.999999999"))
case internal.LocalDate:
return tag("date-local", orig.Format("2006-01-02"))
case internal.LocalTime:
return tag("time-local", orig.Format("15:04:05.999999999"))
}
// Tag primitive values: bool, string, int, and float64.
case bool:
return tag("bool", fmt.Sprintf("%v", orig))
case string:
return tag("string", orig)
case int64:
return tag("integer", fmt.Sprintf("%d", orig))
case float64:
switch {
case math.IsNaN(orig):
return tag("float", "nan")
case math.IsInf(orig, 1):
return tag("float", "inf")
case math.IsInf(orig, -1):
return tag("float", "-inf")
default:
return tag("float", strconv.FormatFloat(orig, 'f', -1, 64))
}
}
}
func tag(typeName string, data any) map[string]any {
return map[string]any{
"type": typeName,
"value": data,
}
}