Skip to content

Instantly share code, notes, and snippets.

@faceair
Last active July 9, 2018 07:00
Show Gist options
  • Save faceair/7826d6927467e58d669ebe4c6f23bb04 to your computer and use it in GitHub Desktop.
Save faceair/7826d6927467e58d669ebe4c6f23bb04 to your computer and use it in GitHub Desktop.
New Bytes As String Extension
package utils
import (
"unsafe"
jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2"
)
var JSON = jsoniter.ConfigCompatibleWithStandardLibrary
func init() {
JSON.RegisterExtension(&BytesAsStringExtension{})
}
var bytesType = reflect2.TypeOfPtr((*[]byte)(nil)).Elem()
type BytesAsStringExtension struct {
jsoniter.DummyExtension
}
func (extension *BytesAsStringExtension) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {
if typ == bytesType {
return &bytesAsStringCodec{}
}
return nil
}
func (extension *BytesAsStringExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
if typ == bytesType {
return &bytesAsStringCodec{}
}
return nil
}
type bytesAsStringCodec struct{}
func (codec *bytesAsStringCodec) IsEmpty(ptr unsafe.Pointer) bool {
return len(*((*[]byte)(ptr))) == 0
}
func (codec *bytesAsStringCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
stream.WriteString(string(*(*[]byte)(ptr)))
}
func (codec *bytesAsStringCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
*(*[]byte)(ptr) = []byte(iter.ReadString())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment