Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/js/libs/structs/structs.go
2070 views
1
package structs
2
3
import (
4
_ "embed"
5
6
"github.com/projectdiscovery/gostruct"
7
)
8
9
// StructsUnpack the byte slice (presumably packed by Pack(format, msg)) according to the given format.
10
// The result is a []interface{} slice even if it contains exactly one item.
11
// The byte slice must contain not less the amount of data required by the format
12
// (len(msg) must more or equal CalcSize(format)).
13
// Ex: structs.Unpack(">I", buff[:nb])
14
// @example
15
// ```javascript
16
// const structs = require('nuclei/structs');
17
// const result = structs.Unpack('H', [0]);
18
// ```
19
func Unpack(format string, msg []byte) ([]interface{}, error) {
20
return gostruct.UnPack(buildFormatSliceFromStringFormat(format), msg)
21
}
22
23
// StructsPack returns a byte slice containing the values of msg slice packed according to the given format.
24
// The items of msg slice must match the values required by the format exactly.
25
// Ex: structs.pack("H", 0)
26
// @example
27
// ```javascript
28
// const structs = require('nuclei/structs');
29
// const packed = structs.Pack('H', [0]);
30
// ```
31
func Pack(formatStr string, msg interface{}) ([]byte, error) {
32
var args []interface{}
33
switch v := msg.(type) {
34
case []interface{}:
35
args = v
36
default:
37
args = []interface{}{v}
38
}
39
format := buildFormatSliceFromStringFormat(formatStr)
40
41
var idxMsg int
42
for _, f := range format {
43
switch f {
44
case "<", ">", "!":
45
case "h", "H", "i", "I", "l", "L", "q", "Q", "b", "B":
46
switch v := args[idxMsg].(type) {
47
case int64:
48
args[idxMsg] = int(v)
49
}
50
idxMsg++
51
}
52
}
53
return gostruct.Pack(format, args)
54
}
55
56
// StructsCalcSize returns the number of bytes needed to pack the values according to the given format.
57
// Ex: structs.CalcSize("H")
58
// @example
59
// ```javascript
60
// const structs = require('nuclei/structs');
61
// const size = structs.CalcSize('H');
62
// ```
63
func StructsCalcSize(format string) (int, error) {
64
return gostruct.CalcSize(buildFormatSliceFromStringFormat(format))
65
}
66
67
func buildFormatSliceFromStringFormat(format string) []string {
68
var formats []string
69
temp := ""
70
71
for _, c := range format {
72
if c >= '0' && c <= '9' {
73
temp += string(c)
74
} else {
75
if temp != "" {
76
formats = append(formats, temp+string(c))
77
temp = ""
78
} else {
79
formats = append(formats, string(c))
80
}
81
}
82
}
83
if temp != "" {
84
formats = append(formats, temp)
85
}
86
return formats
87
}
88
89