rust-lang / rust-lang/rust

Transitioning to superset enum variant causes unnecessary copy

Open
#146,081 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-enum C-optimization I-slow T-compiler
Dominant language
Rust
Stars
119k
Forks
16.2k
PR merge metrics
PR metrics pending

Description

When I have an enum whose variants are superset of the previous ones, transitioning to the superset variant unnecessarily copies the entire variant instead of just changing discriminant and copying the new data over.

https://rust.godbolt.org/z/Mjeq3d4MW

Example

use std::mem::{ManuallyDrop, take};

type Param = ManuallyDrop<String>;

#[derive(Default)]
enum State {
    #[default]
    None,
    A([Param; 16]),
    B([Param; 16], Param),
    C([Param; 16], Param, Param),
}

impl State {
    #[unsafe(no_mangle)]
    fn transition(&mut self, param: Param) {
        let taken = take(self);
        *self = match taken {
            Self::None | Self::C { .. } => Self::None,
            Self::A(a) => Self::B(a, param),
            Self::B(a, b) => Self::C(a, b, param),
        };
    }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rust Compiler Explorer example at https://rust.godbolt.org/z/Mjeq3d4MW and inspect the generated code for State::transition. Compare transitions between the enum variants and identify whether the superset transition still copies the existing array; done means the unnecessary copy is eliminated while the shown behavior remains correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.