github.com/searKing/golang/go@v1.2.117/unsafe/conv_go1.20.go (about)

     1  // Copyright 2023 The searKing Author. 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 unsafe
     8  
     9  import (
    10  	"unsafe"
    11  )
    12  
    13  // StringToBytes converts string to byte slice without a memory allocation.
    14  // For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.
    15  func StringToBytes(s string) []byte {
    16  	// unsafe.StringData is unspecified for the empty string, so we provide a strict interpretation
    17  	if len(s) == 0 {
    18  		return nil
    19  	}
    20  	// Copied from go 1.20.1 os.File.WriteString
    21  	// https://github.com/golang/go/blob/202a1a57064127c3f19d96df57b9f9586145e21c/src/os/file.go#L246
    22  	return unsafe.Slice(unsafe.StringData(s), len(s))
    23  }
    24  
    25  // BytesToString converts byte slice to string without a memory allocation.
    26  // For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.
    27  func BytesToString(b []byte) string {
    28  	// unsafe.SliceData relies on cap whereas we want to rely on len
    29  	if len(b) == 0 {
    30  		return ""
    31  	}
    32  	// Copied from go 1.20.1 strings.Builder.String
    33  	// https://github.com/golang/go/blob/202a1a57064127c3f19d96df57b9f9586145e21c/src/strings/builder.go#L48
    34  	return unsafe.String(unsafe.SliceData(b), len(b))
    35  }