value_120.go raw

   1  // Copyright 2022 The Go Authors. All rights reserved.
   2  // Use of this source code is governed by a BSD-style
   3  // license that can be found in the LICENSE file.
   4  
   5  //go:build go1.20
   6  
   7  package slog
   8  
   9  import "unsafe"
  10  
  11  type (
  12  	stringptr *byte // used in Value.any when the Value is a string
  13  	groupptr  *Attr // used in Value.any when the Value is a []Attr
  14  )
  15  
  16  // StringValue returns a new Value for a string.
  17  func StringValue(value string) Value {
  18  	return Value{num: uint64(len(value)), any: stringptr(unsafe.StringData(value))}
  19  }
  20  
  21  // GroupValue returns a new Value for a list of Attrs.
  22  // The caller must not subsequently mutate the argument slice.
  23  func GroupValue(as ...Attr) Value {
  24  	return Value{num: uint64(len(as)), any: groupptr(unsafe.SliceData(as))}
  25  }
  26  
  27  // String returns Value's value as a string, formatted like fmt.Sprint. Unlike
  28  // the methods Int64, Float64, and so on, which panic if v is of the
  29  // wrong kind, String never panics.
  30  func (v Value) String() string {
  31  	if sp, ok := v.any.(stringptr); ok {
  32  		return unsafe.String(sp, v.num)
  33  	}
  34  	return string(v.append(nil))
  35  }
  36  
  37  func (v Value) str() string {
  38  	return unsafe.String(v.any.(stringptr), v.num)
  39  }
  40