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 c0 = -3, c1 = 4, c2 = 20 # HoleyEnum
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
type 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

Macros

macro genEnumCaseStmt(typ: typedesc; argSym: typed; default: typed;
                      userMin, userMax: static[int];
                      normalizer: static[proc (s: string): string]): untyped
  Source   Edit

Templates

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 a0 = -3, a1 = 10, a2, a3 = (20, "f3Alt") # HoleyEnum
  B = enum b0, b1, b2 # OrdinalEnum
  C = enum c0 = 10, c1, c2 # OrdinalEnum
assert a2.symbolRank == 2
assert b2.symbolRank == 2
assert c2.symbolRank == 2
assert c2.ord == 12
assert a2.ord == 11
var invalid = 7.A
doAssertRaises(IndexDefect): discard invalid.symbolRank
  Source   Edit