/
str_conv.go
55 lines (48 loc) · 1.18 KB
/
str_conv.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
package inspector
import (
"errors"
"strconv"
"strings"
)
// StrConv describes string to X conversion object.
type StrConv struct {
// Code snippet.
Snippet string
// Imports list.
Import []string
}
var (
// Conversion snippets registry.
convSnippetRegistry = map[string]StrConv{}
// Counter for variables suffixes to avoid variable names duplicates.
tmpCntr int
ErrNoConvFunc = errors.New("convert function doesn't exists")
)
// RegisterStrToXFn registers new snippet.
func RegisterStrToXFn(typ, snippet string, imports []string) {
convSnippetRegistry[typ] = StrConv{snippet, imports}
}
// StrConvSnippet builds a conversion snippet according arguments.
func StrConvSnippet(s, typn, typu, _var string) (string, []string, error) {
var (
sc StrConv
ok bool
)
sc, ok = convSnippetRegistry[typn]
if !ok {
sc, ok = convSnippetRegistry[typu]
}
if ok {
i := tmpIdx()
snippet := strings.Replace(sc.Snippet, "!{arg}", s, -1)
snippet = strings.Replace(snippet, "!{var}", _var, -1)
snippet = strings.Replace(snippet, "!{tmp}", i, -1)
return snippet, sc.Import, nil
}
return "", nil, ErrNoConvFunc
}
func tmpIdx() string {
i := strconv.Itoa(tmpCntr)
tmpCntr++
return i
}