split_enum_storage/
lib.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Library to allow storing enum discriminants out-of-line from payloads without maintaining
6//! `unsafe` code. Makes structs smaller when they have enum fields whose discriminants are stored
7//! with padding in the enum layout due to payload alignment requirements.
8//!
9//! An enum's internal padding can result in a lot of memory used even when the use case does not
10//! require the ability to return a concrete reference to the enum type. This macro allows relaxing
11//! the requirement at the expense of ergonomics, storing enum discriminants in bytes of a struct
12//! that would otherwise be used by the compiler for padding. Callers then interact with the enum
13//! "field" through generated accessors.
14
15pub use split_enum_storage_macro::{container, SplitStorage};
16
17/// A trait for enums which can be decomposed into a separate discriminant and data payload.
18///
19/// # Safety
20///
21/// Do not implement this manually. Use the derive macro provided by this crate.
22pub unsafe trait SplitStorage {
23    /// The data-less discriminant enum for this enum's split storage.
24    type Discriminant;
25
26    /// The payload union for this enum's split storage.
27    type Payload;
28
29    /// Split the enum's discriminant and payload for separate storage.
30    fn decompose(self) -> (Self::Discriminant, std::mem::ManuallyDrop<Self::Payload>);
31}