Specialized Option implementations

I watched jonhoo's stream and while I was distracted with other things I heard it mentioned that Option<Vec<T>> can be optimized so that it uses the vector's internal list pointer to indicate whether it's Some or None. Unfortunately because I was focused on other things, I didn't quite get the context under which this happens.

Are these types of quote-specializations-endquote something that is completely built into the compiler (i.e. it knows about Option<Vec<T>> specifically), or is this something one could hint the compiler about in library code? Conceptually:

struct MyThing {
  ptr: *const u32;

Or is it based on things like NonNull?

This is called a "niche" or "niche-filling" optimization. There's some information in the Unsafe Code Guidelines here:


(Incidentally you can observe this in action quite easily, e.g. by verifying that size_of::<Option<Box<u32>>>() == size_of::<Box<u32>>().)


NonNull uses unstable attributes for this:

#[stable(feature = "nonnull", since = "1.25.0")]
pub struct NonNull<T: ?Sized> {
    pointer: *const T,

And there's similar on the NonZero* types.

1 Like

So, no, it's not specialization, and yes, it's built into the compiler, but it's not hard-coded for Option.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.