This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
util.go
112 lines (102 loc) · 2.04 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright (c) 2020-2021 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package micheline
import (
"strconv"
"strings"
"unicode"
)
const (
PATH_SEPARATOR = "."
DEFAULT = "default"
PRIM = "prim"
INT = "int"
BYTES = "bytes"
STRING = "string"
ROOT = "root"
ANNOTS = "annots"
ARGS = "args"
DO = "do"
SET_DELEGATE = "set_delegate"
REMOVE_DELEGATE = "remove_delegate"
DEPOSIT = "deposit"
)
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < 32 || s[i] > unicode.MaxASCII {
return false
}
}
return true
}
func isASCIIBytes(b []byte) bool {
return isASCII(string(b))
}
func isPackedBytes(b []byte) bool {
return len(b) > 1 && b[0] == 0x5 && b[1] <= 0x0A // first primitive is valid
}
func limit(s string, l int) string {
return s[:min(len(s), l)]
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func getPath(val interface{}, path string) (interface{}, bool) {
if val == nil {
return nil, false
}
if path == "" {
return val, true
}
frag := strings.Split(path, PATH_SEPARATOR)
next := val
for i, v := range frag {
switch t := next.(type) {
case map[string]interface{}:
var ok bool
next, ok = t[v]
if !ok {
return nil, false
}
case []interface{}:
idx, err := strconv.Atoi(v)
if err != nil || idx < 0 || len(t) < idx {
return nil, false
}
next = t[idx]
default:
return next, i == len(frag)-1
}
}
return next, true
}
func walkValueMap(name string, val interface{}, fn ValueWalkerFunc) error {
switch t := val.(type) {
case map[string]interface{}:
if len(name) > 0 {
name += "."
}
for n, v := range t {
child := name + n
if err := walkValueMap(child, v, fn); err != nil {
return err
}
}
case []interface{}:
if len(name) > 0 {
name += "."
}
for i, v := range t {
child := name + strconv.Itoa(i)
if err := walkValueMap(child, v, fn); err != nil {
return err
}
}
default:
return fn(name, val)
}
return nil
}