forked from Velocidex/velociraptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrappers.go
111 lines (93 loc) · 2.18 KB
/
wrappers.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
package json
import (
"bytes"
"reflect"
"github.com/Velocidex/json"
)
type RawMessage = json.RawMessage
var (
EncoderCallbackSkip = json.EncoderCallbackSkip
)
func MarshalWithOptions(v interface{}, opts *json.EncOpts) ([]byte, error) {
if opts == nil {
return json.Marshal(v)
}
return json.MarshalWithOptions(v, opts)
}
func Marshal(v interface{}) ([]byte, error) {
opts := NewEncOpts()
return json.MarshalWithOptions(v, opts)
}
func MustMarshalIndent(v interface{}) []byte {
result, err := MarshalIndent(v)
if err != nil {
panic(err)
}
return result
}
func MustMarshalString(v interface{}) string {
result, err := Marshal(v)
if err != nil {
panic(err)
}
return string(result)
}
func StringIndent(v interface{}) string {
result, err := MarshalIndent(v)
if err != nil {
panic(err)
}
return string(result)
}
func MarshalIndent(v interface{}) ([]byte, error) {
opts := NewEncOpts()
return MarshalIndentWithOptions(v, opts)
}
func MarshalIndentWithOptions(v interface{}, opts *json.EncOpts) ([]byte, error) {
b, err := json.MarshalWithOptions(v, opts)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = json.Indent(&buf, b, "", " ")
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func MarshalJsonl(v interface{}) ([]byte, error) {
rt := reflect.TypeOf(v)
if rt == nil || rt.Kind() != reflect.Slice && rt.Kind() != reflect.Array {
return nil, json.EncoderCallbackSkip
}
a_slice := reflect.ValueOf(v)
options := NewEncOpts()
out := bytes.Buffer{}
for i := 0; i < a_slice.Len(); i++ {
row := a_slice.Index(i).Interface()
serialized, err := json.MarshalWithOptions(row, options)
if err != nil {
return nil, err
}
out.Write(serialized)
out.Write([]byte{'\n'})
}
return out.Bytes(), nil
}
func Unmarshal(b []byte, v interface{}) error {
return json.Unmarshal(b, v)
}
// Marshals into a normalized string with sorted keys - this is most
// important for tests.
func MarshalIndentNormalized(v interface{}) ([]byte, error) {
serialized, err := Marshal(v)
if err != nil {
return nil, err
}
data := make(map[string]interface{})
err = Unmarshal(serialized, &data)
if err != nil {
return nil, err
}
return MarshalIndent(data)
}