github.com/google/capslock@v0.2.3-0.20240517042941-dac19fc347c0/testpkgs/useunsafe/useunsafe.go (about)

     1  // Copyright 2023 Google LLC
     2  //
     3  // Use of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file or at
     5  // https://developers.google.com/open-source/licenses/bsd
     6  
     7  // Package useunsafe is used for testing.
     8  package useunsafe
     9  
    10  import (
    11  	"unsafe"
    12  )
    13  
    14  // Foo converts a pointer using unsafe.Pointer.
    15  func Foo() int {
    16  	x := uint(3)
    17  	u := unsafe.Pointer(&x)
    18  	y := *(*int)(u)
    19  	return y
    20  }
    21  
    22  type up = unsafe.Pointer
    23  
    24  // Bar converts a pointer using a type equivalent to unsafe.Pointer.
    25  func Bar() int {
    26  	x := uint(3)
    27  	u := up(&x)
    28  	y := *(*int)(u)
    29  	return y
    30  }
    31  
    32  // Some exported variables.
    33  var (
    34  	I  int
    35  	U  up = up(&I)
    36  	IP *int
    37  	Y  = *(*int)(U)
    38  	Z  = func() int {
    39  		return *(*int)(U)
    40  	}
    41  )
    42  
    43  // Baz converts an unsafe pointer in a global variable.
    44  func Baz() int {
    45  	IP = (*int)(U)
    46  	return *IP
    47  }
    48  
    49  // ReturnFunction returns a function that converts an unsafe.Pointer.
    50  func ReturnFunction() func() int {
    51  	return func() int {
    52  		return *(*int)(U)
    53  	}
    54  }
    55  
    56  // Indirect calls a function that converts an unsafe.Pointer.
    57  func Indirect() int {
    58  	return ReturnFunction()()
    59  }
    60  
    61  // Indirect2 calls a function that converts an unsafe.Pointer.
    62  func Indirect2() int {
    63  	return Z()
    64  }
    65  
    66  // NestedFunctions contains a nested function that converts an unsafe.Pointer.
    67  func NestedFunctions() func() func() func() float32 {
    68  	return func() func() func() float32 {
    69  		return func() func() float32 {
    70  			return func() float32 {
    71  				return *(*float32)(U)
    72  			}
    73  		}
    74  	}
    75  }
    76  
    77  // CallNestedFunctions calls a nested function that converts an unsafe.Pointer.
    78  func CallNestedFunctions() float32 {
    79  	return NestedFunctions()()()()
    80  }
    81  
    82  // Ok converts an unsafe.Pointer to a uintptr.
    83  func Ok() uintptr {
    84  	var p unsafe.Pointer
    85  	return (uintptr)(p)
    86  }
    87  
    88  // T is a type with a method that uses an unsafe.Pointer.
    89  type T struct{}
    90  
    91  // M uses an unsafe pointer.
    92  func (t T) M() int {
    93  	return *(*int)(U)
    94  }