Skip to content

Tracking Issue for option_as_slice #108545

Closed
@llogiq

Description

@llogiq

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

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.

Footnotes

  1. https://std-dev-guide.rust-lang.org/feature-lifecycle/stabilization.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.disposition-mergeThis issue / PR is in PFCP or FCP with a disposition to merge it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions