Skip to content

Commit

Permalink
add unsafeext package
Browse files Browse the repository at this point in the history
  • Loading branch information
Dean Karn committed Jun 29, 2020
1 parent 4569437 commit eecc242
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 2 deletions.
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
module github.com/go-playground/pkg/v4

require (
github.com/go-playground/assert v1.2.1 // indirect
github.com/go-playground/assert/v2 v2.0.1
github.com/go-playground/form/v4 v4.0.0
github.com/go-playground/form/v4 v4.1.1
)

go 1.13
go 1.14
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBY
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/form/v4 v4.0.0 h1:vUKi2K1Hqlc4rpBc0tCclgs9zSfbY5yMKsL106db/eY=
github.com/go-playground/form/v4 v4.0.0/go.mod h1:bodWfd97U9PVMZFcDsbVzSbQQTtaWrebnTwQtWjSW1M=
github.com/go-playground/form/v4 v4.1.1 h1:1T9lGt3WRHuDwT5uwx7RYQZfxVwWZhF0DC1ovKyNnWY=
github.com/go-playground/form/v4 v4.1.1/go.mod h1:q1a2BY+AQUUzhl6xA/6hBetay6dEIhMHjgvJiGo6K7U=
23 changes: 23 additions & 0 deletions unsafe/conversions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package unsafeext

import (
"reflect"
"unsafe"
)

// BytesToString converts an array of bytes into a string without allocating.
// The byte slice passed to this function is not to be used after this call as it's unsafe; you have been warned.
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

// StringToBytes converts an existing string into an []byte without allocating.
// The string passed to this functions is not to be used again after this call as it's unsafe; you have been warned.
func StringToBytes(s string) (b []byte) {
strHdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
sliceHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sliceHdr.Data = strHdr.Data
sliceHdr.Cap = strHdr.Len
sliceHdr.Len = strHdr.Len
return
}
21 changes: 21 additions & 0 deletions unsafe/conversions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package unsafeext

import "testing"

func TestBytesToString(t *testing.T) {
b := []byte{'g', 'o', '-', 'p', 'l', 'a', 'y', 'g', 'r', 'o', 'u', 'n', 'd'}
s := BytesToString(b)
expected := string(b)
if s != expected {
t.Fatalf("expected '%s' got '%s'", expected, s)
}
}

func TestStringToBytes(t *testing.T) {
s := "go-playground"
b := StringToBytes(s)

if string(b) != s {
t.Fatalf("expected '%s' got '%s'", s, string(b))
}
}

0 comments on commit eecc242

Please sign in to comment.