summaryrefslogtreecommitdiff
path: root/utils/convert.go
diff options
context:
space:
mode:
authorValery Piashchynski <[email protected]>2021-05-13 17:15:00 +0300
committerValery Piashchynski <[email protected]>2021-05-13 17:15:00 +0300
commit2be94ad0400e2f523d87f47e09a7bf505edef689 (patch)
tree1824c8ee28d0c6ce2884b99d0a4eaa99dcaa9cbb /utils/convert.go
parent705b69631dc91323c64a19594dcfeca06ea4fa5a (diff)
- Remove unsafe casting (replace with a less unsafe)
- Make the static plugin great again (separate plugin) - Revert new behavior Signed-off-by: Valery Piashchynski <[email protected]>
Diffstat (limited to 'utils/convert.go')
-rw-r--r--utils/convert.go34
1 files changed, 34 insertions, 0 deletions
diff --git a/utils/convert.go b/utils/convert.go
new file mode 100644
index 00000000..8d153ce5
--- /dev/null
+++ b/utils/convert.go
@@ -0,0 +1,34 @@
+package utils
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+// AsBytes returns a slice that refers to the data backing the string s.
+func AsBytes(s string) []byte {
+ // get the pointer to the data of the string
+ p := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)
+
+ var b []byte
+ hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
+ hdr.Data = uintptr(p)
+ // we need to set the cap and len for the string to byte convert
+ // because string is shorter than []bytes
+ hdr.Cap = len(s)
+ hdr.Len = len(s)
+
+ return b
+}
+
+// AsString returns a string that refers to the data backing the slice s.
+func AsString(b []byte) string {
+ p := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&b)).Data)
+
+ var s string
+ hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
+ hdr.Data = uintptr(p)
+ hdr.Len = len(b)
+
+ return s
+}