Skip to main content

Casepaths

Derive Macro Casepaths 

Source
#[derive(Casepaths)]
{
    // Attributes available to this derive:
    #[Readable]
    #[Writable]
    #[All]
}
Expand description

Derives case path methods for enum variants.

Case paths (also known as prisms) provide a way to access and manipulate enum variants in a composable way. They allow you to extract values from enum variants and embed values back into variants.

§Generated Methods

For each variant VariantName with a single field of type T:

  • variant_name_r() - Returns an OptionalKeyPath<Enum, T> for reading
  • variant_name_w() - Returns a WritableOptionalKeyPath<Enum, T> for writing
  • variant_name_fr() - Alias for variant_name_r()
  • variant_name_fw() - Alias for variant_name_w()
  • variant_name_embed(value) - Returns Enum by embedding a value into the variant
  • variant_name_enum() - Returns an EnumKeyPath<Enum, T> with both extraction and embedding

For unit variants (no fields):

  • variant_name_fr() - Returns an OptionalKeyPath<Enum, ()> that checks if variant matches

For multi-field tuple variants:

  • variant_name_fr() - Returns an OptionalKeyPath<Enum, (T1, T2, ...)> for the tuple
  • variant_name_fw() - Returns a WritableOptionalKeyPath<Enum, (T1, T2, ...)> for the tuple

§Attributes

§Enum-level attributes:

  • #[All] - Generate all methods (readable and writable)
  • #[Readable] - Generate only readable methods (default)
  • #[Writable] - Generate only writable methods

§Variant-level attributes:

  • #[Readable] - Generate readable methods for this variant only
  • #[Writable] - Generate writable methods for this variant only
  • #[All] - Generate all methods for this variant

§Examples

use keypaths_proc::Casepaths;

#[derive(Casepaths)]
#[All]
enum Status {
    Active(String),
    Inactive,
    Pending(u32),
}

// Usage:
let mut status = Status::Active("online".to_string());

// Extract value from variant
let active_path = Status::active_r();
if let Some(value) = active_path.get(&status) {
    println!("Status is: {}", value);
}

// Embed value into variant
let new_status = Status::active_embed("offline".to_string());

// Use EnumKeyPath for both extraction and embedding
let active_enum = Status::active_enum();
let extracted = active_enum.extract(&status);  // Option<&String>
let embedded = active_enum.embed("new".to_string());  // Status::Active("new")