anon_enum

Crates.ioanon_enum
lib.rsanon_enum
version1.1.0
sourcesrc
created_at2023-03-17 06:27:35.34054
updated_at2023-03-25 20:12:09.20608
descriptionEnum types with fully-generic variants
homepage
repositoryhttps://gitlab.com/Ssolar5/anon_enum
max_upload_size
id812461
size43,115
(Ssolar5)

documentation

README

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>>
Commit count: 6

cargo fmt