This repository has been archived by the owner on Nov 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
converts.go
78 lines (64 loc) · 1.68 KB
/
converts.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
package tools
import (
"reflect"
"strconv"
"unsafe"
)
/*
Creation Time: 2019 - Oct - 03
Created by: (ehsan)
Maintainers:
1. Ehsan N. Moosa (E2)
Auditor: Ehsan N. Moosa (E2)
Copyright Ronak Software Group 2020
*/
func StrToInt64(s string) int64 {
v, _ := strconv.ParseInt(s, 10, 64)
return v
}
func StrToInt32(s string) int32 {
v, _ := strconv.ParseInt(s, 10, 32)
return int32(v)
}
func StrToUInt64(s string) uint64 {
v, _ := strconv.ParseInt(s, 10, 64)
return uint64(v)
}
func StrToUInt32(s string) uint32 {
v, _ := strconv.ParseInt(s, 10, 32)
return uint32(v)
}
func Int64ToStr(x int64) string {
return strconv.FormatInt(x, 10)
}
func Int32ToStr(x int32) string {
return strconv.FormatInt(int64(x), 10)
}
func UInt64ToStr(x uint64) string {
return strconv.FormatUint(x, 10)
}
func UInt32ToStr(x uint32) string {
return strconv.FormatUint(uint64(x), 10)
}
// ByteToStr converts byte slice to a string without memory allocation.
// Note it may break if string and/or slice header will change
// in the future go versions.
func ByteToStr(bts []byte) string {
b := *(*reflect.SliceHeader)(unsafe.Pointer(&bts))
s := &reflect.StringHeader{Data: b.Data, Len: b.Len}
return *(*string)(unsafe.Pointer(s))
}
func B2S(bts []byte) string {
return ByteToStr(bts)
}
// StrToByte converts string to a byte slice without memory allocation.
// Note it may break if string and/or slice header will change
// in the future go versions.
func StrToByte(str string) []byte {
s := *(*reflect.StringHeader)(unsafe.Pointer(&str))
b := &reflect.SliceHeader{Data: s.Data, Len: s.Len, Cap: s.Len}
return *(*[]byte)(unsafe.Pointer(b))
}
func S2B(str string) []byte {
return StrToByte(str)
}