v / vlib / crypto / internal / subtle / aliasing.v
29 lines · 27 sloc · 1.24 KB · 763f94388b1ceff59c3e68ebda2c9f57197f32a4
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4// Package subtle implements functions that are often useful in cryptographic
5// code but require careful thought to use correctly.
6module subtle
7
8// NOTE: require unsafe in future
9// any_overlap reports whether x and y share memory at any (not necessarily
10// corresponding) index. The memory beyond the slice length is ignored.
11pub fn any_overlap(x []u8, y []u8) bool {
12 // NOTE: Remember to come back to this (joe-c)
13 return x.len > 0 && y.len > 0 && // &x.data[0] <= &y.data[y.len-1] &&
14 // &y.data[0] <= &x.data[x.len-1]
15 unsafe { &x[0] <= &y[y.len - 1] && &y[0] <= &x[x.len - 1] }
16}
17
18// inexact_overlap reports whether x and y share memory at any non-corresponding
19// index. The memory beyond the slice length is ignored. Note that x and y can
20// have different lengths and still not have any inexact overlap.
21//
22// inexact_overlap can be used to implement the requirements of the crypto/cipher
23// AEAD, Block, BlockMode and Stream interfaces.
24pub fn inexact_overlap(x []u8, y []u8) bool {
25 if x.len == 0 || y.len == 0 || unsafe { &x[0] == &y[0] } {
26 return false
27 }
28 return any_overlap(x, y)
29}
30