-
Notifications
You must be signed in to change notification settings - Fork 58
/
function.go
1554 lines (1347 loc) · 35.3 KB
/
function.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kgo
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"math"
"net/url"
"reflect"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"unsafe"
)
// dumpPrint 打印调试变量,变量可多个.
func dumpPrint(vs ...interface{}) {
for _, v := range vs {
fmt.Printf("%+v\n", v)
}
}
// lenArrayOrSlice 获取数组/切片的长度.
// chkType为检查类型,枚举值有(1仅数组,2仅切片,3数组或切片);结果为-1表示变量不是数组或切片,>=0表示合法长度.
func lenArrayOrSlice(val interface{}, chkType uint8) int {
if chkType != 1 && chkType != 2 && chkType != 3 {
chkType = 3
}
var res = -1
refVal := reflect.ValueOf(val)
switch refVal.Kind() {
case reflect.Array:
if chkType == 1 || chkType == 3 {
res = refVal.Len()
}
case reflect.Slice:
if chkType == 2 || chkType == 3 {
res = refVal.Len()
}
}
return res
}
// isBool 是否布尔值.
func isBool(val interface{}) bool {
return val == true || val == false
}
// isMap 检查变量是否字典.
func isMap(val interface{}) bool {
return reflect.ValueOf(val).Kind() == reflect.Map
}
// isStruct 检查变量是否结构体.
func isStruct(val interface{}) bool {
r, _ := reflectFinalValue(reflect.ValueOf(val))
return r.Kind() == reflect.Struct
}
// isInterface 变量是否接口.
func isInterface(val interface{}) bool {
r, _ := reflectFinalValue(reflect.ValueOf(val))
return r.Kind() == reflect.Invalid
}
// isString 变量是否字符串.
func isString(val interface{}) bool {
return GetVariateType(val) == "string"
}
// isByte 变量是否字节切片.
func isByte(val interface{}) bool {
return GetVariateType(val) == "[]uint8"
}
// isBinary 字符串是否二进制.
func isBinary(s string) bool {
for _, b := range s {
if 0 == b {
return true
}
}
return false
}
// isHex 是否十六进制字符串.
func isHex(str string) (res bool) {
if len(str) > 0 {
_, err := hex2Byte(str)
res = (err == nil)
}
return
}
// isInt 变量是否整型数值.
func isInt(val interface{}) bool {
switch val.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return true
case string:
str := val.(string)
if str == "" {
return false
}
_, err := strconv.Atoi(str)
return err == nil
}
return false
}
// isFloat 变量是否浮点数值.
func isFloat(val interface{}) bool {
switch val.(type) {
case float32, float64:
return true
case string:
str := val.(string)
if str == "" {
return false
}
if ok := RegFloat.MatchString(str); ok {
return true
}
}
return false
}
// isNumeric 变量是否数值(不包含复数).
func isNumeric(val interface{}) bool {
switch val.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return true
case float32, float64:
return true
case string:
str := val.(string)
if str == "" {
return false
}
_, err := strconv.ParseFloat(str, 64)
return err == nil
}
return false
}
// isNil 检查变量是否nil.
func isNil(val interface{}) bool {
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.Invalid:
return true
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Interface:
return rv.IsNil()
}
return val == nil
}
// isEmpty 检查变量是否为空.
func isEmpty(val interface{}) bool {
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.Invalid:
return true
case reflect.String, reflect.Array:
return v.Len() == 0
case reflect.Map, reflect.Slice:
return v.Len() == 0 || v.IsNil()
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
return reflect.DeepEqual(val, reflect.Zero(v.Type()).Interface())
}
// isLittleEndian 系统字节序类型是否小端存储.
func isLittleEndian() bool {
var i int32 = 0x01020304
// 将int32类型的指针转换为byte类型的指针
u := unsafe.Pointer(&i)
pb := (*byte)(u)
// 取得pb位置对应的值
b := *pb
// 由于b是byte类型的,最多保存8位,那么只能取得开始的8位
// 小端: 04 (03 02 01)
// 大端: 01 (02 03 04)
return (b == 0x04)
}
// isUrl 字符串是否URL.
func isUrl(str string) bool {
if str == "" || len(str) <= 3 || utf8.RuneCountInString(str) >= 2083 || strings.HasPrefix(str, ".") {
return false
}
u, err := url.Parse(str)
//Couldn't even parse the url
if err != nil {
return false
}
//Invalid host
if u.Host == "" || strings.HasPrefix(u.Host, ".") || strings.HasSuffix(u.Host, ":") {
return false
}
//No Scheme found
if u.Scheme == "" {
return false
}
var inScheme bool
var schemes = []string{"ftp", "tcp", "udp", "irc", "rtmp", "ws", "wss", "http", "https"}
for _, s := range schemes {
if u.Scheme == s {
inScheme = true
break
}
}
if !inScheme {
return false
}
return true
}
// getEndian 获取系统字节序类型,小端返回binary.LittleEndian,大端返回binary.BigEndian .
func getEndian() binary.ByteOrder {
var nativeEndian binary.ByteOrder = binary.BigEndian
buf := [2]byte{}
*(*uint16)(unsafe.Pointer(&buf[0])) = uint16(0xABCD)
switch buf {
case [2]byte{0xCD, 0xAB}:
nativeEndian = binary.LittleEndian
//case [2]byte{0xAB, 0xCD}:
// nativeEndian = binary.BigEndian
}
return nativeEndian
}
// numeric2Float 将数值转换为float64.
func numeric2Float(val interface{}) (res float64, err error) {
switch val.(type) {
case int:
res = float64(val.(int))
case int8:
res = float64(val.(int8))
case int16:
res = float64(val.(int16))
case int32:
res = float64(val.(int32))
case int64:
res = float64(val.(int64))
case uint:
res = float64(val.(uint))
case uint8:
res = float64(val.(uint8))
case uint16:
res = float64(val.(uint16))
case uint32:
res = float64(val.(uint32))
case uint64:
res = float64(val.(uint64))
case float32:
res = float64(val.(float32))
case float64:
res = val.(float64)
case string:
str := val.(string)
res, err = strconv.ParseFloat(str, 64)
}
return
}
// md5Byte 计算字节切片的 MD5 散列值.
func md5Byte(str []byte, length uint8) []byte {
var res []byte
h := md5.New()
_, err := h.Write(str)
if err == nil {
hashInBytes := h.Sum(nil)
dst := make([]byte, hex.EncodedLen(len(hashInBytes)))
hex.Encode(dst, hashInBytes)
if length > 0 && length < 32 {
res = dst[:length]
} else {
res = dst
}
}
return res
}
// md5Reader 计算Reader的 MD5 散列值.
func md5Reader(reader io.Reader, length uint8) (res []byte, err error) {
h := md5.New()
if _, err = io.Copy(h, reader); err == nil {
hashInBytes := h.Sum(nil)
dst := make([]byte, hex.EncodedLen(len(hashInBytes)))
hex.Encode(dst, hashInBytes)
if length > 0 && length < 32 {
res = dst[:length]
} else {
res = dst
}
}
return
}
// shaXByte 计算字节切片的 shaX 散列值,x为1/256/512.
func shaXByte(str []byte, x uint16) []byte {
var h hash.Hash
switch x {
case 1:
h = sha1.New()
case 256:
h = sha256.New()
case 512:
h = sha512.New()
default:
panic(fmt.Sprintf("[shaXByte]`x must be in [1, 256, 512]; but: %d", x))
}
_, _ = h.Write(str)
hashInBytes := h.Sum(nil)
res := make([]byte, hex.EncodedLen(len(hashInBytes)))
hex.Encode(res, hashInBytes)
return res
}
// shaXReader 计算Reader的 shaX 散列值,x为1/256/512.
func shaXReader(reader io.Reader, x uint16) (res []byte, err error) {
var h hash.Hash
switch x {
case 1:
h = sha1.New()
case 256:
h = sha256.New()
case 512:
h = sha512.New()
default:
panic(fmt.Sprintf("[shaXReader]`x must be in [1, 256, 512]; but: %d", x))
}
if _, err = io.Copy(h, reader); err == nil {
hashInBytes := h.Sum(nil)
res = make([]byte, hex.EncodedLen(len(hashInBytes)))
hex.Encode(res, hashInBytes)
}
return
}
// arrayValues 返回arr(数组/切片/字典/结构体)中所有的值.
// filterZero 是否过滤零值元素(nil,false,0,”,[]),true时排除零值元素,false时保留零值元素.
func arrayValues(arr interface{}, filterZero bool) []interface{} {
var res []interface{}
var fieldVal reflect.Value
val := reflect.ValueOf(arr)
switch val.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < val.Len(); i++ {
fieldVal = val.Index(i)
if !filterZero || (filterZero && !fieldVal.IsZero()) {
res = append(res, fieldVal.Interface())
}
}
case reflect.Map:
for _, k := range val.MapKeys() {
fieldVal = val.MapIndex(k)
if !filterZero || (filterZero && !fieldVal.IsZero()) {
res = append(res, fieldVal.Interface())
}
}
case reflect.Struct:
for i := 0; i < val.NumField(); i++ {
fieldVal = val.Field(i)
if fieldVal.CanInterface() {
if !filterZero || (filterZero && !fieldVal.IsZero()) {
res = append(res, fieldVal.Interface())
}
}
}
default:
panic("[arrayValues]`arr type must be array|slice|map|struct; but : " + val.Kind().String())
}
return res
}
// reflectFinalValue 获取反射的最终值.
func reflectFinalValue(r reflect.Value) (reflect.Value, bool) {
var isPtr bool
// 如果是指针,则获取其所指向的元素
if r.Kind() == reflect.Ptr {
r = r.Elem()
isPtr = true
}
return r, isPtr
}
// reflectFinalType 获取反射的最终类型.
func reflectFinalType(r reflect.Type) (reflect.Type, bool) {
var isPtr bool
// 如果是指针,则获取其所指向的元素
if r.Kind() == reflect.Ptr {
r = r.Elem()
isPtr = true
}
return r, isPtr
}
// reflectTypesMap 递归获取反射字段类型Map.
func reflectTypesMap(r reflect.Type, res map[string]reflect.Type) {
for i := 0; i < r.NumField(); i++ {
field := r.Field(i)
if field.Anonymous { //匿名字段
subTyp := r.Field(i).Type
reflectTypesMap(subTyp, res)
} else if field.PkgPath == "" { //公开字段
res[field.Name] = field.Type
}
}
}
// reflect2Itf 将反射值转为接口(原值)
func reflect2Itf(r reflect.Value) (res interface{}) {
switch r.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
res = r.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
res = r.Uint()
case reflect.Float32, reflect.Float64:
res = r.Float()
case reflect.String:
res = r.String()
case reflect.Bool:
res = r.Bool()
default:
if r.CanInterface() {
res = r.Interface()
} else {
res = r
}
}
return
}
// structVal 获取结构体的反射值.
func structVal(obj interface{}) (reflect.Value, error) {
v := reflect.ValueOf(obj)
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return v, errors.New("[structVal]`obj type must be struct; but : " + v.Kind().String())
}
return v, nil
}
// structFields 获取结构体的字段切片;all是否包含所有字段(包括未导出的).
func structFields(obj interface{}, all bool) ([]reflect.StructField, error) {
v, e := structVal(obj)
if e != nil {
return nil, e
}
var fs []reflect.StructField
var t = v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
// 不能访问未导出的字段
if !all && field.PkgPath != "" {
continue
}
fs = append(fs, field)
}
return fs, nil
}
// struct2Map 结构体转为字典;tagName为要导出的标签名,可以为空,为空时将导出所有字段.
func struct2Map(obj interface{}, tagName string) (map[string]interface{}, error) {
v, e := structVal(obj)
if e != nil {
return nil, e
}
t := v.Type()
var res = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if tagName != "" {
if tagValue := field.Tag.Get(tagName); tagValue != "" {
res[tagValue] = reflect2Itf(v.Field(i))
}
} else {
res[field.Name] = reflect2Itf(v.Field(i))
}
}
return res, nil
}
// creditChecksum 计算身份证校验码,其中id为身份证号码.
func creditChecksum(id string) byte {
//∑(ai×Wi)(mod 11)
// 加权因子
factor := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
// 校验位对应值
code := []byte{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}
leng := len(id)
sum := 0
for i, char := range id[:leng-1] {
num, _ := strconv.Atoi(string(char))
sum += num * factor[i]
}
return code[sum%11]
}
// compareConditionMap 比对数组是否匹配条件.condition为条件字典,arr为要比对的数据(字典/结构体).
func compareConditionMap(condition map[string]interface{}, arr interface{}) (res interface{}) {
val := reflect.ValueOf(arr)
conNum := len(condition)
if conNum > 0 {
chkNum := 0
switch val.Kind() {
case reflect.Map:
if conNum > 0 {
for _, k := range val.MapKeys() {
if condVal, ok := condition[k.String()]; ok && reflect.DeepEqual(val.MapIndex(k).Interface(), condVal) {
chkNum++
}
}
}
case reflect.Struct:
var field reflect.Value
for k, v := range condition {
field = val.FieldByName(k)
if field.IsValid() && field.CanInterface() && reflect.DeepEqual(field.Interface(), v) {
chkNum++
}
}
default:
panic("[compareConditionMap]`arr type must be map|struct; but : " + val.Kind().String())
}
if chkNum == conNum {
res = arr
}
}
return
}
// getTrimMask 获取要修剪的字符串集合,masks为要屏蔽的字符切片.
func getTrimMask(masks []string) string {
var str string
if len(masks) == 0 {
str = blankChars
} else {
str = strings.Join(masks, "")
}
return str
}
// methodExists 检查val结构体中是否存在methodName方法.
func methodExists(val interface{}, methodName string) (bool, error) {
if methodName == "" {
return false, errors.New("[methodExists]`methodName can not be empty.")
}
r := reflect.ValueOf(val)
if r.Type().Kind() != reflect.Ptr {
r = reflect.New(reflect.TypeOf(val))
}
method := r.MethodByName(methodName)
if !method.IsValid() {
return false, fmt.Errorf("[methodExists] Method `%s` not exists in interface `%s`", methodName, r.Type())
}
return true, nil
}
// getMethod 获取val结构体的methodName方法.
// 注意:返回的方法中的第一个参数是接收者.
// 所以,调用返回的方法时,必须将接收者作为第一个参数传递.
func getMethod(val interface{}, methodName string) interface{} {
if val == nil || methodName == "" {
return nil
}
r := reflect.ValueOf(val)
if r.Type().Kind() != reflect.Ptr {
r = reflect.New(reflect.TypeOf(val))
}
method := r.MethodByName(methodName)
if !method.IsValid() {
return nil
}
return method.Interface()
}
// getFuncNames 获取变量的所有函数名.
func getFuncNames(val interface{}) (res []string) {
if val == nil {
return
}
r := reflect.ValueOf(val)
if r.Type().Kind() != reflect.Ptr {
r = reflect.New(reflect.TypeOf(val))
}
typ := r.Type()
for i := 0; i < r.NumMethod(); i++ {
res = append(res, typ.Method(i).Name)
}
return
}
// camelCaseToLowerCase 驼峰转为小写.
func camelCaseToLowerCase(str string, connector rune) string {
if len(str) == 0 {
return ""
}
buf := &bytes.Buffer{}
var prev, r0, r1 rune
var size int
r0 = connector
for len(str) > 0 {
prev = r0
r0, size = utf8.DecodeRuneInString(str)
str = str[size:]
switch {
case r0 == utf8.RuneError:
continue
case unicode.IsUpper(r0):
if prev != connector && !unicode.IsNumber(prev) {
buf.WriteRune(connector)
}
buf.WriteRune(unicode.ToLower(r0))
if len(str) == 0 {
break
}
r0, size = utf8.DecodeRuneInString(str)
str = str[size:]
if !unicode.IsUpper(r0) {
buf.WriteRune(r0)
break
}
// find next non-upper-case character and insert connector properly.
// it's designed to convert `HTTPServer` to `http_server`.
// if there are more than 2 adjacent upper case characters in a word,
// treat them as an abbreviation plus a normal word.
for len(str) > 0 {
r1 = r0
r0, size = utf8.DecodeRuneInString(str)
str = str[size:]
if r0 == utf8.RuneError {
buf.WriteRune(unicode.ToLower(r1))
break
}
if !unicode.IsUpper(r0) {
if isCaseConnector(r0) {
r0 = connector
buf.WriteRune(unicode.ToLower(r1))
} else if unicode.IsNumber(r0) {
// treat a number as an upper case rune
// so that both `http2xx` and `HTTP2XX` can be converted to `http_2xx`.
buf.WriteRune(unicode.ToLower(r1))
buf.WriteRune(connector)
buf.WriteRune(r0)
} else {
buf.WriteRune(connector)
buf.WriteRune(unicode.ToLower(r1))
buf.WriteRune(r0)
}
break
}
buf.WriteRune(unicode.ToLower(r1))
}
if len(str) == 0 || r0 == connector {
buf.WriteRune(unicode.ToLower(r0))
}
case unicode.IsNumber(r0):
if prev != connector && !unicode.IsNumber(prev) {
buf.WriteRune(connector)
}
buf.WriteRune(r0)
default:
if isCaseConnector(r0) {
r0 = connector
}
buf.WriteRune(r0)
}
}
return buf.String()
}
// isCaseConnector 是否字符转换连接符.
func isCaseConnector(r rune) bool {
return r == '-' || r == '_' || unicode.IsSpace(r)
}
// pkcs7Padding PKCS7填充.
// cipherText为密文;blockSize为分组长度;isZero是否零填充.
func pkcs7Padding(cipherText []byte, blockSize int, isZero bool) []byte {
clen := len(cipherText)
if cipherText == nil || clen == 0 || blockSize <= 0 {
return nil
}
var padtext []byte
padding := blockSize - clen%blockSize
if isZero {
padtext = bytes.Repeat([]byte{0}, padding)
} else {
padtext = bytes.Repeat([]byte{byte(padding)}, padding)
}
return append(cipherText, padtext...)
}
// pkcs7UnPadding PKCS7拆解.
// origData为源数据;blockSize为分组长度.
func pkcs7UnPadding(origData []byte, blockSize int) (res []byte) {
//origData = zeroUnPadding(origData)
olen := len(origData)
if origData == nil || olen == 0 || blockSize <= 0 || olen%blockSize != 0 {
return
}
unPadding := int(origData[olen-1])
if unPadding <= olen {
res = origData[:(olen - unPadding)]
}
return
}
// zeroPadding PKCS7使用0填充.
func zeroPadding(cipherText []byte, blockSize int) []byte {
return pkcs7Padding(cipherText, blockSize, true)
}
// zeroUnPadding PKCS7-0拆解.
func zeroUnPadding(origData []byte) []byte {
return bytes.TrimRightFunc(origData, func(r rune) bool {
return r == rune(0)
})
}
// GetFieldValue 获取(字典/结构体的)字段值;fieldName为字段名,大小写敏感.
func GetFieldValue(arr interface{}, fieldName string) (res interface{}, err error) {
val := reflect.ValueOf(arr)
switch val.Kind() {
case reflect.Map:
for _, subKey := range val.MapKeys() {
if fmt.Sprintf("%s", subKey) == fieldName {
res = val.MapIndex(subKey).Interface()
break
}
}
case reflect.Struct:
field := val.FieldByName(fieldName)
if !field.IsValid() || !field.CanInterface() {
break
}
res = field.Interface()
default:
err = errors.New("[GetFieldValue]`arr type must be map|struct; but : " + val.Kind().String())
}
return
}
// str2Int 将字符串转换为int.其中"true", "TRUE", "True"为1;若为浮点字符串,则取整数部分.
func str2Int(val string) (res int) {
if val == "true" || val == "TRUE" || val == "True" {
res = 1
return
} else if ok := RegFloat.MatchString(val); ok {
fl, _ := strconv.ParseFloat(val, 1)
res = int(fl)
return
}
res, _ = strconv.Atoi(val)
return
}
// str2Int 将字符串转换为uint.其中"true", "TRUE", "True"为1;若为浮点字符串,则取整数部分;若为负值则为0.
func str2Uint(val string) (res uint) {
if val == "true" || val == "TRUE" || val == "True" {
res = 1
return
} else if ok := RegFloat.MatchString(val); ok {
fl, _ := strconv.ParseFloat(val, 1)
if fl > 0 {
res = uint(fl)
}
return
}
n, e := strconv.Atoi(val)
if e == nil && n > 0 {
res = uint(n)
}
return
}
// str2Float32 将字符串转换为float32;其中"true", "TRUE", "True"为1.0 .
func str2Float32(val string) (res float32) {
if val == "true" || val == "TRUE" || val == "True" {
res = 1.0
} else {
r, _ := strconv.ParseFloat(val, 32)
res = float32(r)
}
return
}
// str2Float64 将字符串转换为float64;其中"true", "TRUE", "True"为1.0 .
func str2Float64(val string) (res float64) {
if val == "true" || val == "TRUE" || val == "True" {
res = 1.0
} else {
res, _ = strconv.ParseFloat(val, 64)
}
return
}
// str2Bool 将字符串转换为布尔值.
// 1, t, T, TRUE, true, True 等字符串为真;
// 0, f, F, FALSE, false, False 等字符串为假.
func str2Bool(val string) (res bool) {
if val != "" {
res, _ = strconv.ParseBool(val)
}
return
}
// bool2Int 将布尔值转换为整型.
func bool2Int(val bool) int {
if val {
return 1
}
return 0
}
// str2Bytes 将字符串转换为字节切片.
func str2Bytes(val string) []byte {
return []byte(val)
}
// str2Runes 将字符串转为字符切片.
func str2Runes(val string) []rune {
return []rune(val)
}
// bytes2Str 将字节切片转换为字符串.
func bytes2Str(val []byte) string {
return string(val)
}
// str2BytesUnsafe (非安全的)将字符串转换为字节切片.
// 该方法零拷贝,但不安全.它直接转换底层指针,两者指向的相同的内存,改一个另外一个也会变.
// 仅当临时需将长字符串转换且不长时间保存时可以使用.
// 转换之后若没做其他操作直接改变里面的字符,则程序会崩溃.
// 如 b:=str2BytesUnsafe("xxx"); b[1]='d'; 程序将panic.
func str2BytesUnsafe(val string) []byte {
psHeader := &reflect.SliceHeader{}
strHeader := (*reflect.StringHeader)(unsafe.Pointer(&val))
psHeader.Data = strHeader.Data
psHeader.Len = strHeader.Len
psHeader.Cap = strHeader.Len
return *(*[]byte)(unsafe.Pointer(psHeader))
}
// bytes2StrUnsafe (非安全的)将字节切片转换为字符串.
// 零拷贝,不安全.效率是string([]byte{})的百倍以上,且转换量越大效率优势越明显.
func bytes2StrUnsafe(val []byte) string {
return *(*string)(unsafe.Pointer(&val))
}
// runes2Bytes 将[]rune转为[]byte.
func runes2Bytes(rs []rune) []byte {
size := 0
for _, r := range rs {
size += utf8.RuneLen(r)
}
bs := make([]byte, size)
count := 0
for _, r := range rs {
count += utf8.EncodeRune(bs[count:], r)
}
return bs
}
// toStr 强制将变量转换为字符串.
func toStr(val interface{}) string {
//先处理其他类型
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.Invalid:
return ""
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.String:
return v.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(v.Uint(), 10)
case reflect.Float32:
return strconv.FormatFloat(v.Float(), 'f', -1, 32)
case reflect.Float64:
return strconv.FormatFloat(v.Float(), 'f', -1, 64)
case reflect.Ptr, reflect.Struct, reflect.Map: //指针、结构体和字典
b, err := json.Marshal(v.Interface())
if err != nil {
return ""
}
return string(b)