github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/internal/subtle/aliasing.go (about)

     1  package subtle
     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  		// 如果in的当前长度+n 依然在其in的容量范围内,则直接获取in的(len(in) + n)部分作为head
    33  		head = in[:total]
    34  	} else {
    35  		// in的当前长度+n已经超过其容量,则重新申请内存生成head,并将in的(len(in))部分拷贝到新的head切片
    36  		head = make([]byte, total)
    37  		copy(head, in)
    38  	}
    39  	// 获取head切片的尾部
    40  	tail = head[len(in):]
    41  	return
    42  }