github.com/noisysockets/netstack@v0.6.0/pkg/gohacks/string_go120_unsafe.go (about)

     1  // Copyright 2023 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build go1.20
    16  
    17  package gohacks
    18  
    19  import (
    20  	"unsafe"
    21  )
    22  
    23  // ImmutableBytesFromString is equivalent to []byte(s), except that it uses the
    24  // same memory backing s instead of making a heap-allocated copy. This is only
    25  // valid if the returned slice is never mutated.
    26  func ImmutableBytesFromString(s string) []byte {
    27  	b := unsafe.StringData(s)
    28  	return unsafe.Slice(b, len(s))
    29  }
    30  
    31  // StringFromImmutableBytes is equivalent to string(bs), except that it uses
    32  // the same memory backing bs instead of making a heap-allocated copy. This is
    33  // only valid if bs is never mutated after StringFromImmutableBytes returns.
    34  func StringFromImmutableBytes(bs []byte) string {
    35  	if len(bs) == 0 {
    36  		return ""
    37  	}
    38  	return unsafe.String(&bs[0], len(bs))
    39  }