#sum #error-handling #anon #no-alloc #anonymous-enum

no-std anon_enum

Enum types with fully-generic variants

2 stable releases

1.1.0 Mar 25, 2023
1.0.0 Mar 17, 2023

#2520 in Rust patterns

28 downloads per month

CC0 license

37KB
976 lines

Anonymous Enums

Enum types with fully-generic variants.

This library defines enum types which are generic over from 2 (Enum2) to 16 (Enum16) type parameters. Each type parameter of a given enum type is the type of the single field of its respective variant of the same name (all variants are tuple structs with a single field).

use std::collections::HashMap;

use anon_enum::Enum2;

/// Error type stating that a map does not contain a given key.
struct ErrKeyNotFound;

/// Error type stating that an integer overflow occured during
/// an arithmetic operation.
struct ErrIntegerOverflow;

/// Maps a `str` to an integer of type `i32` and returns the integer plus one.
fn get_and_add_one(
    map: &HashMap<&str, i32>,
    key: &str,
) -> Result<i32, Enum2<ErrKeyNotFound, ErrIntegerOverflow>> {
    Ok(map
        .get(key)
        .ok_or(Enum2::T0(ErrKeyNotFound))?
        .checked_add(1)
        .ok_or(Enum2::T1(ErrIntegerOverflow))?)
}

fn main() {
    let mut fruit_count = HashMap::new();

    fruit_count.insert("Lime", 5);
    fruit_count.insert("Orange", i32::MAX);

    matches!(get_and_add_one(&fruit_count, "Lime"), Ok(6));
    matches!(
        get_and_add_one(&fruit_count, "Tangerine"),
        Err(Enum2::T0(ErrKeyNotFound))
    );
    matches!(
        get_and_add_one(&fruit_count, "Orange"),
        Err(Enum2::T1(ErrIntegerOverflow))
    );
}

An enum of more than 16 variants may be expressed by setting the generic type T15 of Enum16 to an enum type:

// Enum of 18 variants.
Enum16<T0, T1, ..., T14, Enum3<T15, T16, T17>>

No runtime deps