alias_purego.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  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. //go:build purego
  5. // Package alias implements memory aliasing tests.
  6. package alias
  7. // This is the Google App Engine standard variant based on reflect
  8. // because the unsafe package and cgo are disallowed.
  9. import "reflect"
  10. // AnyOverlap reports whether x and y share memory at any (not necessarily
  11. // corresponding) index. The memory beyond the slice length is ignored.
  12. func AnyOverlap(x, y []byte) bool {
  13. return len(x) > 0 && len(y) > 0 &&
  14. reflect.ValueOf(&x[0]).Pointer() <= reflect.ValueOf(&y[len(y)-1]).Pointer() &&
  15. reflect.ValueOf(&y[0]).Pointer() <= reflect.ValueOf(&x[len(x)-1]).Pointer()
  16. }
  17. // InexactOverlap reports whether x and y share memory at any non-corresponding
  18. // index. The memory beyond the slice length is ignored. Note that x and y can
  19. // have different lengths and still not have any inexact overlap.
  20. //
  21. // InexactOverlap can be used to implement the requirements of the crypto/cipher
  22. // AEAD, Block, BlockMode and Stream interfaces.
  23. func InexactOverlap(x, y []byte) bool {
  24. if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] {
  25. return false
  26. }
  27. return AnyOverlap(x, y)
  28. }