Marker trait for value types

I'm currently implementing library code that deals with secrets and thus must adhere to the principles of constant-time programming. One of them is that memory access patterns must not depend on secrets. One way to violate this is to conditionally select between two addresses (and subsequently dereference). Such a violation may not be obvious, especially if the address is deeply nested within a type, or if it's a private implementation detail. For this reason, I want to implement constant-time selection only over value types (i.e., types free from references and pointers).

Existing libraries address this issue by explicitly implementing marker traits on allowed types they wish to perform constant-time selection over. To generalize this, an auto trait to mark value types could be introduced. Basically, it should be something like this:

pub unsafe auto trait ValueType {}

impl<T> !ValueType for &T {}
impl<T> !ValueType for &mut T {}
impl<T> !ValueType for *const T {}
impl<T> !ValueType for *mut T {}

Of course, unsafe Rust code can still circumvent this by casting to and from addresses, but I think this is an acceptable limitation.

Are there any other use-cases for such a trait? Any pitfalls to watch out for? Thanks in advance!

The requirement you're looking for seems to be "no memory access will be made via values of this type", which is equivalent to saying "the values of this type do not have provenance". That makes me think that this requirement might potentially be useful in other contexts, e.g. it may also describe types that can be correctly serialized to disk using a bitwise copy.

3 Likes

@ais523 Nice way to think about it, thanks! For serialization, there of course are additional concerns like platform-independent type properties (most notably, no isize or usize). I hope someone working with serialization can add a cent or two. :slight_smile: