Skip to content

Commit

Permalink
add unsafe string casting
Browse files Browse the repository at this point in the history
  • Loading branch information
awalterschulze committed Jan 29, 2025
1 parent eeeccf8 commit f16fb74
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func unquote(s []byte) (string, error) {
var ok bool
var t string
s, ok = unquoteBytes(s)
t = string(s)
t = castToString(s)
if !ok {
return "", errUnquote
}
Expand Down
27 changes: 27 additions & 0 deletions json/string_unsafe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2025 Walter Schulze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package json

import (
"reflect"
"unsafe"
)

// castToString uses unsafe to cast a byte slice to a string without copying or allocating memory.
func castToString(buf []byte) string {
header := (*reflect.SliceHeader)(unsafe.Pointer(&buf))
strHeader := reflect.StringHeader{Data: header.Data, Len: header.Len}
return *(*string)(unsafe.Pointer(&strHeader))
}

0 comments on commit f16fb74

Please sign in to comment.