I was trying to imagine a way to introduce niche optimization in a sRGBA color type.
The idea is that when the alpha channel is zero, then the RGB values don't matter and can be zero.
The Repr
enum represents internally the color value. The Transparent
variant represents the color (0, 0, 0, 0)
.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Color(Repr);
- First attempt,
Transparent
is a unit variant.
#[derive(Clone, Copy)]
enum Repr {
Transparent,
Color([u8; 3], NonZero<u8>),
}
- Explicitly set the
Transparent
's fields to match theColor
variant's fields but with unit type.
#[derive(Clone, Copy)]
enum Repr {
Transparent([(); 3], ()),
Color([u8; 3], NonZero<u8>),
}
- Explicitly set the
Transparent
's fields to match theColor
variant's fields but with a type that can only be0
.
#[derive(Clone, Copy)]
enum Repr {
Transparent([Zero; 3], Zero),
Color([u8; 3], NonZero<u8>),
}
#[derive(Clone, Copy)]
#[repr(u8)]
enum Zero {
Zero = 0,
}
It turns out that in the cases 1. and 2., there is no niche optimization, but in the last case, there is.
In case 1., since there is no field in Repr::Transparent
, I was expecting the compiler to introduce niche optimization. So why isn't it the case?