/
bytes32.go
79 lines (64 loc) · 1.42 KB
/
bytes32.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 test
import (
"bytes"
"encoding/hex"
"errors"
"reflect"
"strings"
)
type Bytes8 = [8]byte
type Bytes32 = [32]byte
type Bytes16 = [16]byte
var ErrStringTooLong = errors.New("string to long")
func B8(s string) (r Bytes8) {
copy(r[:], s)
return
}
func ToString8(b Bytes8) string {
return string(bytes.Trim(b[:], "\000"))
}
func B16(s string) (r Bytes16) {
copy(r[:], s)
return
}
func ToBytes32(s string) (r Bytes32, err error) {
if len(s) > 32 {
err = ErrStringTooLong
} else {
copy(r[:], s)
}
return
}
func B32(s string) (r Bytes32) {
copy(r[:], s)
return
}
func ToString(b Bytes32) string {
return string(bytes.Trim(b[:], "\000"))
}
func ToHex(b Bytes32) string {
return "0x" + hex.EncodeToString(b[:])
}
var ErrHexTooShort = errors.New("hex string is shorter than bytes32")
func FromHex(s string) (Bytes32, error) {
var b Bytes32
n, err := hex.Decode(b[:], []byte(strings.TrimPrefix(s, "0x")))
if err == nil && n != 32 {
return b, ErrHexTooShort
}
return b, err
}
func FromOGRN(ogrn string) Bytes32 {
return B32("OGRN:" + ogrn)
}
func ToOGRN(orgId Bytes32) string {
return strings.TrimRight(strings.TrimPrefix(string(orgId[:]), "OGRN:"), "\000")
}
func Bytes32Enum(in interface{}) interface{} {
out := reflect.ValueOf(in).Elem()
for i := out.NumField() - 1; i >= 0; i-- {
fieldValue := B32(out.Type().Field(i).Name)
out.Field(i).Set(reflect.ValueOf(fieldValue))
}
return out.Interface()
}