Realized how I could simplify the operations I was doing, and remove that pesky
premature conversion, though... still uncertain if it resolved the
afformentioned issues, just for posterity felt like posting :P
import std/macros
type
X = enum
Z
type
HoleyEnum = enum
AVal = -5
BVal = 5
macro enumAsSet(enm: typed): untyped =
newNimNode(nnkCurly).add(enm.getType[1][1..^1])
proc toEnum*(val: SomeInteger, E: typedesc[enum]): E =
const enmRange = E.low.ord .. E.high.ord
let enmSet = cast[set[E.low.ord .. E.high.ord]](enumAsSet(E)) # Vm cannot
do the casting
if val in enmRange and val in enmSet:
E(val)
else:
raise (ref ValueError)(msg: $val & " cannot be converted to the enum: "
& $E)
let b = 0.toEnum(X)
let c = (-5).toEnum(HoleyEnum)
Run
- Safe `enum` conversion ElegantBeef
- Safe `enum` conversion mildred
- Safe `enum` conversion ElegantBeef
- Safe `enum` conversion planetis
- Safe `enum` conversion Zoom
- Safe `enum` conversion ynfle
- Safe `enum` conversion arnetheduck
- Safe `enum` conversion cumulonimbus
- Safe `enum` conversion ElegantBeef
- Safe `enum` conversion lscrd
- Safe `enum` conversion ElegantBeef
- Safe `enum` conversion arnetheduck
- Safe `enum` conversion arnetheduck
- Safe `enum` conversion ElegantBeef
- Safe `enum` conversion arnetheduck
- Safe `enum` conversion lscrd
- Safe `enum` conversion PMunch
- Safe `enum` conversion leorize
- Safe `enum` conversion planetis
- Safe `enum` conversion arnetheduck
- Safe `enum` conversion boatvid
