forked from projectdiscovery/alterx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
61 lines (54 loc) · 1.62 KB
/
util.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
package alterx
import (
"fmt"
"reflect"
"regexp"
"strings"
"unsafe"
)
var varRegex = regexp.MustCompile(`\{\{([a-zA-Z0-9]+)\}\}`)
// returns no of variables present in statement
func getVarCount(data string) int {
return len(varRegex.FindAllStringSubmatch(data, -1))
}
// returns names of all variables
func getAllVars(data string) []string {
values := []string{}
for _, v := range varRegex.FindAllStringSubmatch(data, -1) {
if len(v) >= 2 {
values = append(values, v[1])
}
}
return values
}
// getSampleMap returns a sample map containing input variables and payload variable
func getSampleMap(inputVars map[string]interface{}, payloadVars map[string][]string) map[string]interface{} {
sMap := map[string]interface{}{}
for k, v := range inputVars {
sMap[k] = v
}
for k, v := range payloadVars {
if k != "" && len(v) > 0 {
sMap[k] = "temp"
}
}
return sMap
}
// checkMissing checks if all variables/placeholders are successfully replaced
// if not error is thrown with description
func checkMissing(template string, data map[string]interface{}) error {
got := Replace(template, data)
if res := varRegex.FindAllString(got, -1); len(res) > 0 {
return fmt.Errorf("values of `%v` variables not found", strings.Join(res, ","))
}
return nil
}
// unsafeToBytes converts a string to byte slice and does it with
// zero allocations.
//
// Reference - https://stackoverflow.com/questions/59209493/how-to-use-unsafe-get-a-byte-slice-from-a-string-without-memory-copy
func unsafeToBytes(data string) []byte {
var buf = *(*[]byte)(unsafe.Pointer(&data))
(*reflect.SliceHeader)(unsafe.Pointer(&buf)).Cap = len(data)
return buf
}