std/enumutils

  Source   Edit

Procs

func symbolName[T: enum](a: T): string

Returns the symbol name of an enum.

This uses symbolRank.

Example:

type B = enum
  b0 = (10, "kb0")
  b1 = "kb1"
  b2
let b = B.low
assert b.symbolName == "b0"
assert $b == "kb0"
static: assert B.high.symbolName == "b2"
type C = enum # HoleyEnum
  c0 = -3
  c1 = 4
  c2 = 20
assert c1.symbolName == "c1"
  Source   Edit

Iterators

iterator items[T: HoleyEnum](E: typedesc[T]): T
Iterates over an enum with holes.

Example:

type
  A = enum
    a0 = 2
    a1 = 4
    a2
  B[T] = enum
    b0 = 2
    b1 = 4
from std/sequtils import toSeq
assert A.toSeq == [a0, a1, a2]
assert B[float].toSeq == [B[float].b0, B[float].b1]
  Source   Edit

Templates

template genEnumCaseStmt(typ: typedesc[enum]; arg: typed; default: typed;
                         userMin, userMax: static[int]; normalizer: typed): untyped
Generates a case statement yielding the enum value corresponding the normalized value of arg. String normalization is done using passed normalizer. Only enum values in the provide range are considered.   Source   Edit
template symbolRank[T: enum](a: T): int

Returns the index in which a is listed in T.

The cost for a HoleyEnum is implementation defined, currently optimized for small enums, otherwise is O(T.enumLen).

Example:

type
  A = enum # HoleyEnum
    a0 = -3
    a1 = 10
    a2
    a3 = (20, "f3Alt")
  B = enum # OrdinalEnum
    b0
    b1
    b2
  C = enum # OrdinalEnum
    c0 = 10
    c1
    c2
assert a2.symbolRank == 2
assert b2.symbolRank == 2
assert c2.symbolRank == 2
assert c2.ord == 12
assert a2.ord == 11
  Source   Edit