-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathbytes.go
37 lines (32 loc) · 961 Bytes
/
bytes.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
package core
import (
"encoding/json"
"fmt"
)
// BytesToSlice converts a 32 bit array to a slice slice.
func BytesToSlice(bytes [32]byte) []byte {
rawBytes := make([]byte, len(bytes))
copy(rawBytes, bytes[:])
return rawBytes
}
// BytesToJSONString converts a 32 bit array to a JSON string without escapes, newlines, etc.
func BytesToJSONString(bz []byte) (string, error) {
var jsonData map[string]interface{}
if err := json.Unmarshal(bz, &jsonData); err != nil {
return "", fmt.Errorf("failed to unmarshal JSON: %w", err)
}
formattedJSON, err := json.Marshal(jsonData)
if err != nil {
return "", fmt.Errorf("failed to marshal JSON: %w", err)
}
return string(formattedJSON), nil
}
// BytesToArray converts a slice to a 32 length byte array.
func BytesToArray(bz []byte) ([32]byte, error) {
var bytes [32]byte
if len(bz) != 32 {
return bytes, fmt.Errorf("invalid length of bytes: %d", len(bz))
}
copy(bytes[:], bz)
return bytes, nil
}