-
Notifications
You must be signed in to change notification settings - Fork 68
/
dongle.go
93 lines (84 loc) · 2.19 KB
/
dongle.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
// @Package dongle
// @Description a simple, semantic and developer-friendly golang package for encoding&decoding, encryption&decryption and signature&verification
// @Page github.com/dromara/dongle
// @Developer gouguoyin
// @Blog www.gouguoyin.com
// @Email 245629560@qq.com
// Package dongle is a simple, semantic and developer-friendly golang package for encoding&decoding, encryption&decryption and signature&verification.
package dongle
import (
"unsafe"
)
// Version current version
// 当前版本号
const Version = "1.0.0"
// dongle defines a dongle struct.
// 定义 dongle 结构体
type dongle struct {
src []byte
dst []byte
Error error
}
var (
// Encode returns a new Encoder instance
// 返回 encoder 实例
Encode = newEncoder()
// Decode returns a new Decoder instance
// 返回 decoder 实例
Decode = newDecoder()
// Encrypt returns a new Encrypter instance
// 返回 encrypter 实例
Encrypt = newEncrypter()
// Decrypt returns a new Decrypter instance
// 返回 decrypter 实例
Decrypt = newDecrypter()
// Sign returns a new Signer instance
// 返回 signer 实例
Sign = newSigner()
// Verify returns a new Verifier instance
// 返回 verifier 实例
Verify = newVerifier()
)
// converts string to byte slice without a memory allocation.
// 将字符串转换为字节切片
func string2bytes(s string) []byte {
if len(s) == 0 {
return []byte("")
}
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}
// converts byte slice to string without a memory allocation.
// 将字节切片转换为字符串
func bytes2string(b []byte) string {
if len(b) == 0 {
return ""
}
return *(*string)(unsafe.Pointer(&b))
}
// converts interface to byte slice.
// 将接口转换为字节切片
func interface2bytes(i interface{}) (b []byte) {
switch v := i.(type) {
case string:
b = string2bytes(v)
case []byte:
b = v
}
return
}
// split the byte slice by the specified size.
// 按照指定长度分割字节切片
func bytesSplit(buf []byte, size int) [][]byte {
var chunk []byte
chunks := make([][]byte, 0, len(buf)/size+1)
for len(buf) >= size {
chunk, buf = buf[:size], buf[size:]
chunks = append(chunks, chunk)
}
return chunks
}