Skip to content

Instantly share code, notes, and snippets.

@erikdubbelboer
Created October 27, 2019 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikdubbelboer/898d219bbc997ab1e9aeee2d64aafa04 to your computer and use it in GitHub Desktop.
Save erikdubbelboer/898d219bbc997ab1e9aeee2d64aafa04 to your computer and use it in GitHub Desktop.
diff --git a/fflib/v1/jsonstring.go b/fflib/v1/jsonstring.go
index 513b45d..fd70988 100644
--- a/fflib/v1/jsonstring.go
+++ b/fflib/v1/jsonstring.go
@@ -24,10 +24,12 @@ package v1
import (
"io"
- "unicode/utf8"
+ "reflect"
"strconv"
- "unicode/utf16"
"unicode"
+ "unicode/utf16"
+ "unicode/utf8"
+ "unsafe"
)
const hex = "0123456789abcdef"
@@ -38,8 +40,19 @@ type JsonStringWriter interface {
stringWriter
}
+func s2b(s string) (b []byte) {
+ bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
+ sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
+ bh.Data = sh.Data
+ bh.Len = sh.Len
+ bh.Cap = sh.Len
+ return b
+}
+
func WriteJsonString(buf JsonStringWriter, s string) {
- WriteJson(buf, []byte(s))
+ // WriteJson will not keep any pointers to its []byte argument
+ // so using s2b here is completely safe.
+ WriteJson(buf, s2b(s))
}
/**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment