111 lines
1.7 KiB
Go
111 lines
1.7 KiB
Go
|
package jsonpack
|
||
|
|
||
|
import (
|
||
|
"math"
|
||
|
"regexp"
|
||
|
"strings"
|
||
|
|
||
|
"github.com/samber/lo"
|
||
|
)
|
||
|
|
||
|
type AstToken struct {
|
||
|
category string // array null,
|
||
|
index int
|
||
|
child []AstToken
|
||
|
}
|
||
|
|
||
|
var baseCharacters = []rune("0123456789abcdefghijklmnopqrstuvwxyz")
|
||
|
|
||
|
var baseCharactersMap = lo.Reduce[rune, map[rune]int](baseCharacters, func(carry map[rune]int, v rune, i int) map[rune]int {
|
||
|
carry[v] = i
|
||
|
return carry
|
||
|
}, make(map[rune]int))
|
||
|
|
||
|
var astEncodeReplace = map[string]string{
|
||
|
" ": "+",
|
||
|
"+": "%2B",
|
||
|
"|": "%7C",
|
||
|
"^": "%5E",
|
||
|
"%": "%25",
|
||
|
}
|
||
|
|
||
|
var astDecodeReplace = map[string]string{
|
||
|
"+": " ",
|
||
|
"%2B": "+",
|
||
|
"%7C": "|",
|
||
|
"%5E": "^",
|
||
|
"%25": "%",
|
||
|
}
|
||
|
|
||
|
// 字符串编码
|
||
|
func astEncode(str string) string {
|
||
|
reg := regexp.MustCompile(`[\+ \|\^\%]`)
|
||
|
|
||
|
return reg.ReplaceAllStringFunc(str, func(s string) string {
|
||
|
return astEncodeReplace[s]
|
||
|
})
|
||
|
}
|
||
|
|
||
|
// 字符串界面
|
||
|
func astDecode(str string) string {
|
||
|
reg := regexp.MustCompile(`\+|%2B|%7C|%5E|%25`)
|
||
|
|
||
|
return reg.ReplaceAllStringFunc(str, func(s string) string {
|
||
|
return astDecodeReplace[s]
|
||
|
})
|
||
|
}
|
||
|
|
||
|
// 10进制转36进制
|
||
|
func astBase10to36(num int) string {
|
||
|
if num == 0 {
|
||
|
return "0"
|
||
|
}
|
||
|
|
||
|
isSubFlag := num < 0
|
||
|
|
||
|
if isSubFlag {
|
||
|
num = num * -1
|
||
|
}
|
||
|
|
||
|
str := ""
|
||
|
|
||
|
for num != 0 {
|
||
|
p := num % 36
|
||
|
str = string(baseCharacters[p]) + str
|
||
|
num = num / 36
|
||
|
}
|
||
|
|
||
|
if isSubFlag {
|
||
|
return "-" + str
|
||
|
}
|
||
|
|
||
|
return str
|
||
|
}
|
||
|
|
||
|
// 36进制转10进制
|
||
|
func astBase36to10(str string) int {
|
||
|
str = strings.ToLower(str)
|
||
|
|
||
|
isSubFlag := str[0:1] == "-"
|
||
|
|
||
|
if isSubFlag {
|
||
|
str = str[1:]
|
||
|
}
|
||
|
|
||
|
v := 0.0
|
||
|
|
||
|
length := len(str)
|
||
|
|
||
|
for i := 0; i < length; i++ {
|
||
|
s := rune(str[i])
|
||
|
index := baseCharactersMap[s]
|
||
|
v += float64(index) * math.Pow(float64(36), float64(length-1-i)) // 倒序
|
||
|
}
|
||
|
|
||
|
if isSubFlag {
|
||
|
return -int(v)
|
||
|
}
|
||
|
|
||
|
return int(v)
|
||
|
}
|