github.com/emmansun/gmsm@v0.29.1/internal/alias/aliasing.go (about)

     1  package alias
     2  
     3  import "unsafe"
     4  
     5  // AnyOverlap reports whether x and y share memory at any (not necessarily
     6  // corresponding) index. The memory beyond the slice length is ignored.
     7  func AnyOverlap(x, y []byte) bool {
     8  	return len(x) > 0 && len(y) > 0 &&
     9  		uintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) &&
    10  		uintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1]))
    11  }
    12  
    13  // InexactOverlap reports whether x and y share memory at any non-corresponding
    14  // index. The memory beyond the slice length is ignored. Note that x and y can
    15  // have different lengths and still not have any inexact overlap.
    16  //
    17  // InexactOverlap can be used to implement the requirements of the crypto/cipher
    18  // AEAD, Block, BlockMode and Stream interfaces.
    19  func InexactOverlap(x, y []byte) bool {
    20  	if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] {
    21  		return false
    22  	}
    23  	return AnyOverlap(x, y)
    24  }
    25  
    26  // SliceForAppend takes a slice and a requested number of bytes. It returns a
    27  // slice with the contents of the given slice followed by that many bytes and a
    28  // second slice that aliases into it and contains only the extra bytes. If the
    29  // original slice has sufficient capacity then no allocation is performed.
    30  func SliceForAppend(in []byte, n int) (head, tail []byte) {
    31  	if total := len(in) + n; cap(in) >= total {
    32  		head = in[:total]
    33  	} else {
    34  		head = make([]byte, total)
    35  		copy(head, in)
    36  	}
    37  	tail = head[len(in):]
    38  	return
    39  }