This repository has been archived by the owner on May 13, 2022. It is now read-only.
/
helpers.go
86 lines (79 loc) · 1.98 KB
/
helpers.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
package bc
import (
"fmt"
"github.com/hyperledger/burrow/execution/evm/asm"
)
type ByteSlicable interface {
Bytes() []byte
}
// Concatenate multiple byte slices without unnecessary copying
func Concat(bss ...[]byte) []byte {
offset := 0
for _, bs := range bss {
offset += len(bs)
}
bytes := make([]byte, offset)
offset = 0
for _, bs := range bss {
for i, b := range bs {
bytes[offset+i] = b
}
offset += len(bs)
}
return bytes
}
// Splice or panic
func MustSplice(bytelikes ...interface{}) []byte {
spliced, err := Splice(bytelikes...)
if err != nil {
panic(err)
}
return spliced
}
// Convenience function to allow us to mix bytes, ints, and OpCodes that
// represent bytes in an EVM assembly code to make assembly more readable.
// Also allows us to splice together assembly
// fragments because any []byte arguments are flattened in the result.
func Splice(bytelikes ...interface{}) ([]byte, error) {
bytes := make([]byte, 0, len(bytelikes))
for _, bytelike := range bytelikes {
bs, err := byteSlicify(bytelike)
if err != nil {
return nil, err
}
bytes = append(bytes, bs...)
}
return bytes, nil
}
// Convert anything byte or byte slice like to a byte slice
func byteSlicify(bytelike interface{}) ([]byte, error) {
switch b := bytelike.(type) {
case byte:
return []byte{b}, nil
case asm.OpCode:
return []byte{byte(b)}, nil
case int:
if int(byte(b)) != b {
return nil, fmt.Errorf("the int %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case int64:
if int64(byte(b)) != b {
return nil, fmt.Errorf("the int64 %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case uint64:
if uint64(byte(b)) != b {
return nil, fmt.Errorf("the uint64 %v does not fit inside a byte", b)
}
return []byte{byte(b)}, nil
case string:
return []byte(b), nil
case ByteSlicable:
return b.Bytes(), nil
case []byte:
return b, nil
default:
return nil, fmt.Errorf("could not convert %s to a byte or sequence of bytes", bytelike)
}
}