github.com/searKing/golang/go@v1.2.117/pragma/pragma.go (about)

     1  // Copyright 2018 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  // Package pragma provides types that can be embedded into a struct to
     6  // statically enforce or prevent certain language properties.
     7  // The key observation and some code (shr) is borrowed from https://github.com/protocolbuffers/protobuf-go/blob/v1.25.0/internal/pragma/pragma.go
     8  package pragma
     9  
    10  import (
    11  	"sync"
    12  	"sync/atomic"
    13  	"unsafe"
    14  )
    15  
    16  // NoUnkeyedLiterals can be embedded in a struct to prevent unkeyed literals.
    17  type NoUnkeyedLiterals struct{}
    18  
    19  // DoNotImplement can be embedded in an interface to prevent trivial
    20  // implementations of the interface.
    21  //
    22  // This is useful to prevent unauthorized implementations of an interface
    23  // so that it can be extended in the future for any protobuf language changes.
    24  type doNotImplement struct{}
    25  type DoNotImplement interface{ ProtoInternal(doNotImplement) }
    26  
    27  // DoNotCompare can be embedded in a struct to prevent comparability.
    28  type DoNotCompare [0]func()
    29  
    30  // DoNotCopy can be embedded in a struct to help prevent shallow copies.
    31  // This does not rely on a Go language feature, but rather a special case
    32  // within the vet checker.
    33  //
    34  // See https://golang.org/issues/8005.
    35  type DoNotCopy [0]sync.Mutex
    36  
    37  // CopyChecker holds back pointer to itself to detect object copying.
    38  // Deprecated. use DoNotCopy instead, check by go vet.
    39  // methods Copied or Check return not copied if none of methods Copied or Check have bee called before
    40  type CopyChecker uintptr
    41  
    42  // Copied returns true if this object is copied
    43  func (c *CopyChecker) Copied() bool {
    44  	return uintptr(*c) != uintptr(unsafe.Pointer(c)) &&
    45  		!atomic.CompareAndSwapUintptr((*uintptr)(c), 0, uintptr(unsafe.Pointer(c))) &&
    46  		uintptr(*c) != uintptr(unsafe.Pointer(c))
    47  }
    48  
    49  // Check panic is c is copied
    50  func (c *CopyChecker) Check() {
    51  	if c.Copied() {
    52  		panic("object is copied")
    53  	}
    54  }