forked from Velocidex/velociraptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.go
79 lines (65 loc) · 1.84 KB
/
string.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
package json
import (
"encoding/base64"
"fmt"
"regexp"
"strconv"
"time"
"github.com/Velocidex/json"
"www.velocidex.com/golang/vfilter"
)
var (
number_regex = regexp.MustCompile(
`^(?i)(?P<Number>[-+]?\d*\.?\d+([eE][-+]?\d+)?)$`)
// Strings that look like this will be escaped because they
// might be confused with other things.
protected_prefix = regexp.MustCompile(
`(?i)^( |\{|\[|true|false|[+-]?inf|base64:)`)
)
func AnyToString(item vfilter.Any, opts *json.EncOpts) string {
value := ""
switch t := item.(type) {
case float32:
value = strconv.FormatFloat(float64(t), 'f', -1, 64)
case float64:
value = strconv.FormatFloat(t, 'f', -1, 64)
case time.Time:
// Use the encoding options to control how to serialize the
// time into the correct timezone.
serialized, err := MarshalIndentWithOptions(t, opts)
if err != nil || len(serialized) < 10 {
return ""
}
// Strip the quote marks so it is a bare string value.
return string(serialized[1 : len(serialized)-1])
case int, int16, int32, int64, uint16, uint32, uint64, bool:
value = fmt.Sprintf("%v", item)
case []byte:
value = "base64:" + base64.StdEncoding.EncodeToString(t)
case string:
// If the string looks like a number we encode
// it as a json object. This will ensure that
// the reader does not get confused between
// strings which look like a number and
// numbers.
if number_regex.MatchString(t) ||
protected_prefix.MatchString(t) {
value = " " + t
} else {
value = t
}
default:
serialized, err := MarshalIndentWithOptions(item, opts)
if err != nil {
return ""
}
if len(serialized) > 0 {
if serialized[0] == '{' || serialized[0] == '[' {
value = string(serialized)
} else if serialized[0] == '"' && serialized[len(serialized)-1] == '"' {
value, _ = strconv.Unquote(string(serialized))
}
}
}
return value
}