Skip to content

Commit

Permalink
log/slog: use unsafe.StringData, SliceData
Browse files Browse the repository at this point in the history
Use the new functions in 1.20 (unsafe.StringData, etc.) instead
of StringHeader and StructHeader from the reflect package.

Updates golang#56345.

Change-Id: I84d0db7b203aeffe45ce8b06beb7b4ee17e19949
Reviewed-on: https://go-review.googlesource.com/c/go/+/478055
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Alan Donovan <adonovan@google.com>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
  • Loading branch information
jba authored and eric committed Sep 7, 2023
1 parent 58b5dde commit 6e1306c
Showing 1 changed file with 6 additions and 18 deletions.
24 changes: 6 additions & 18 deletions src/log/slog/value_unsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package slog

import (
"reflect"
"unsafe"
)

Expand All @@ -29,8 +28,8 @@ type Value struct {
}

type (
stringptr unsafe.Pointer // used in Value.any when the Value is a string
groupptr unsafe.Pointer // used in Value.any when the Value is a []Attr
stringptr *byte // used in Value.any when the Value is a string
groupptr *Attr // used in Value.any when the Value is a []Attr
)

// Kind returns v's Kind.
Expand All @@ -55,37 +54,26 @@ func (v Value) Kind() Kind {

// StringValue returns a new Value for a string.
func StringValue(value string) Value {
hdr := (*reflect.StringHeader)(unsafe.Pointer(&value))
return Value{num: uint64(hdr.Len), any: stringptr(hdr.Data)}
return Value{num: uint64(len(value)), any: stringptr(unsafe.StringData(value))}
}

func (v Value) str() string {
var s string
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(v.any.(stringptr))
hdr.Len = int(v.num)
return s
return unsafe.String(v.any.(stringptr), v.num)
}

// String returns Value's value as a string, formatted like fmt.Sprint. Unlike
// the methods Int64, Float64, and so on, which panic if v is of the
// wrong kind, String never panics.
func (v Value) String() string {
if sp, ok := v.any.(stringptr); ok {
// Inlining this code makes a huge difference.
var s string
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(sp)
hdr.Len = int(v.num)
return s
return unsafe.String(sp, v.num)
}
var buf []byte
return string(v.append(buf))
}

func groupValue(as []Attr) Value {
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&as))
return Value{num: uint64(hdr.Len), any: groupptr(hdr.Data)}
return Value{num: uint64(len(as)), any: groupptr(unsafe.SliceData(as))}
}

// group returns the Value's value as a []Attr.
Expand Down

0 comments on commit 6e1306c

Please sign in to comment.