Description
Feature gate: #![feature(option_as_slice)]
This is a tracking issue for the Option::as_slice
and Option::as_mut_slice
methods.
The functions return an immutable or mutable slice to the value contained in the Option, if any. Otherwise an empty slice is returned.
Public API
// core::option
impl Option {
pub fn as_slice(&self) -> &[T] { .. }
pub fn as_mut_slice(&mut self) -> &mut [T] { .. }
}
Steps / History
- Implementation:
- Final comment period (FCP)1
- Stabilization PR stabilize
Option::as_
(mut_
)slice
#116220
Unresolved Questions
The current implementation contains an optimization which relies on the fact that layout randomization as currently implemented only applies to individual variants, never to the discriminant, and thus the offset of the value
within Some(value)
is always either 0 (because of niche optimization) or would be the same if the type was Option<MaybeUninit<T>>
instead of Option<T>
.
Before stabilization, the implementation should be changed to either use an intrinsic to get the offset or extend the offset_of!
macro (recently merged RFC#3308) to cover enum variants and use that. There might also be a smaller solution (that we'd still need to check re the rules of Rust layout), which would simply be mem::size_of::<Option<T>>() - mem::size_of::<T>()
. I can see that this works for all types I've tested it with, and indeed I'm quite sure that it will work perfectly with the current layout implementation, but I'd like someone from the types team have a look at it before actually using it in a stable API.
The implementation now uses an approach that's always sound (just less efficient than optimal if the hack guesses wrong). A stabilization conversation would probably still want to discuss whether we're comfortable with shipping that approach as stable (since the implementation could be improved non-breakingly later) or we'd prefer to wait for a more principled approach (such as an extension of offset_of!
from rust-lang/rfcs#3308 that allows enum variants) first.