Skip to main content

Crate numbered

Crate numbered 

Source
Expand description

Compile-time integer numbers for enum variants.

This crate gives each variant a stable integer: a u8 (or another chosen repr) assigned at compile time. Runtime conversion is a match on a literal. Number::number and FromNumber::from_number are not const (trait methods cannot be). In const context, use Variants::NUMBERS.

Downstream crates use this to drop handwritten from_u8 / as_u8 matches on status codes, wire tags, and similar closed integer sets.

Numbers are trait items in this crate, not inherent methods on E. Import Number / FromNumber to call them, or use UFCS (<E as Number>::number(&e)). A user fn number() still compiles.

§Quick start

use numbered::{FromNumber, Number, Numbered, Variants};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Numbered)]
#[numbered(u8)]
enum Kind {
    Process,                 // 0
    File,                    // 1
    #[numbered(n = 10)]
    Network,                 // 10
    Socket,                  // 11  (continues after last explicit)
}

assert_eq!(Kind::Process.number(), 0u8);
assert_eq!(Kind::File.as_u8(), 1);
assert_eq!(Kind::from_number(10).unwrap(), Kind::Network);
assert_eq!(Kind::try_from(11u8), Ok(Kind::Socket));
assert!(Kind::Process == 0u8);
assert_eq!(Kind::VARIANTS.len(), 4);
assert_eq!(Kind::NUMBERS, &[0, 1, 10, 11]);

Native Rust discriminants (Process = 1) are treated as #[numbered(n = 1)]. If both are present they must agree. A variant named Error is fine: generated TryFrom names FromNumberError instead of Self::Error.

§Attributes

Container (required): #[numbered(<repr>, ...)]

  • A repr type: u8, u16, u32, u64, usize, i8, i16, i32, i64, or isize. First positional, or repr = u8.
  • start = 1: first auto-assigned number when no discriminant / n is set (default 0).
  • crate = ::other::numbered: path used in generated code when this crate is re-exported under another name.

Variant (optional): #[numbered(n = 5)]

Pins that variant to an explicit integer. A native = 5 discriminant does the same. Gaps are allowed. After an explicit number, the next auto variant is last + 1.

use numbered::{FromNumber, Number, Numbered};

#[derive(Debug, PartialEq, Numbered)]
#[numbered(u8, start = 1)]
enum Wire {
    Open,                    // 1
    #[numbered(n = 10)]
    IoFailed,                // 10
    Closed = 20,             // 20
    Draining,                // 21
}

assert_eq!(Wire::Open.number(), 1);
assert_eq!(Wire::IoFailed.as_u8(), 10);
assert_eq!(Wire::from_number(21).unwrap(), Wire::Draining);

Fielded variants keep Number and the Variants tables. Pair with cognomen reason = "... {field}" on the same enum; a number cannot rebuild the payload, so FromNumber is omitted.

use numbered::{Number, Numbered, Variants};

#[derive(Debug, Clone, PartialEq, Numbered)]
#[numbered(u8, start = 1)]
enum HostError {
    Unsupported { capability: &'static str },
    OpenFailed { cause: &'static str },
}

let e = HostError::OpenFailed { cause: "busy" };
assert_eq!(e.number(), 2);
assert_eq!(HostError::NUMBERS, &[1, 2]);
assert_eq!(HostError::VARIANTS.len(), 2);
assert_eq!(HostError::COUNT, 2);

Violations (non-enum, empty enum, missing repr, duplicate keys, unknown keys, collisions, overflow, disagreeing discriminant) are compile errors.

§Generated API

For #[numbered(u8)] on E. Nothing is inherent on E.

  • Number: number() / as_u8() (as_* follows the repr). Takes &self so fielded variants do not need Copy. Not const
  • FromNumber: from_number / from_u8 -> Result<Self, FromNumberError<u8>> (fieldless enums; a number cannot rebuild a payload). Not const
  • Variants (non-generic enums): E::VARIANTS, E::NUMBERS, and E::COUNT after use numbered::Variants. Trait items, so they cannot clash with cognomen or a user const VARIANTS. Fielded enums keep NUMBERS / COUNT; VARIANTS is &[()] of that length. Const use goes through NUMBERS
  • No Display impl. Print the number with e.number().
  • From<E> for u8, TryFrom<u8> for E (TryFrom is fieldless only)
  • PartialEq<u8> / PartialEq<E> both ways
  • Serialize / Deserialize (feature serde): the number, not a string. Deserialize is fieldless only. Do not enable serde on both Numbered and Cognomen for the same type (two Serialize impls)

§Features

FeatureDefaultUnlocks
stdyesalloc + std::error::Error for FromNumberError
allocvia stdkept for feature parity; the unmatched number is always stored
serdenoSerialize / Deserialize

§no_std

numbered = { version = "0.2", default-features = false }

Number, FromNumber, From / TryFrom, and Variants use only core. Add features = ["serde"] for wire formats.

§MSRV

Rust 1.71.1.

Structs§

FromNumberError
Error returned when a number matches no declared variant.

Traits§

FromNumber
Parse a number into Self.
Number
Stable integer number for a numbered enum.
Variants
Declaration-order tables for a non-generic numbered enum.

Derive Macros§

Numbered
Derive stable integer numbers for an enum.