Skip to main content

LabelEnum

Trait LabelEnum 

Source
pub trait LabelEnum:
    Copy
    + Debug
    + 'static {
    const CARDINALITY: usize;
    const LABEL_NAME: &'static str;

    // Required methods
    fn as_index(self) -> usize;
    fn from_index(index: usize) -> Self;
    fn variant_name(self) -> &'static str;

    // Provided method
    fn label_name(&self) -> &'static str { ... }
}
Expand description

Trait for label enums used with LabeledCounter, LabeledGauge, etc.

Implementing this trait allows an enum to be used as a dimension for metrics. Each variant maps to an array index, enabling O(1) metric lookup and update.

§Example

#[derive(Copy, Clone, Debug)]
enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
    Other,
}

impl LabelEnum for HttpMethod {
    const CARDINALITY: usize = 5;
    const LABEL_NAME: &'static str = "method";

    fn as_index(self) -> usize {
        self as usize
    }

    fn from_index(index: usize) -> Self {
        match index {
            0 => Self::Get,
            1 => Self::Post,
            2 => Self::Put,
            3 => Self::Delete,
            _ => Self::Other,
        }
    }

    fn variant_name(self) -> &'static str {
        match self {
            Self::Get => "get",
            Self::Post => "post",
            Self::Put => "put",
            Self::Delete => "delete",
            Self::Other => "other",
        }
    }
}

Required Associated Constants§

Source

const CARDINALITY: usize

Number of variants in this enum.

Source

const LABEL_NAME: &'static str

The Prometheus label name for this dimension.

E.g., “method” for HttpMethod, “command” for RedisCommand.

Required Methods§

Source

fn as_index(self) -> usize

Convert this variant to its array index.

Source

fn from_index(index: usize) -> Self

Convert an array index back to a variant.

Used for iteration during export. Should handle out-of-bounds by returning a sensible default (e.g., an “Other” variant).

Source

fn variant_name(self) -> &'static str

Get the Prometheus label value for this variant.

Should be lowercase, snake_case for Prometheus compatibility.

Provided Methods§

Source

fn label_name(&self) -> &'static str

Get the label name (convenience method for accessing LABEL_NAME).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§