mirror of
https://github.com/nim-lang/Nim.git
synced 2026-06-05 19:34:12 +00:00
added strutils.parseEnum; fixes #95
This commit is contained in:
@@ -378,6 +378,22 @@ proc parseBool*(s: string): bool =
|
||||
of "y", "yes", "true", "1", "on": result = true
|
||||
of "n", "no", "false", "0", "off": result = false
|
||||
else: raise newException(EInvalidValue, "cannot interpret as a bool: " & s)
|
||||
|
||||
proc parseEnum*[T: enum](s: string): T =
|
||||
## parses an enum ``T``. Raises ``EInvalidValue`` for an invalid value in
|
||||
## `s`. The comparison is done in a style insensitive way.
|
||||
for e in low(T)..high(T):
|
||||
if cmpIgnoreStyle(s, $e) == 0:
|
||||
return e
|
||||
raise newException(EInvalidValue, "invalid enum value: " & s)
|
||||
|
||||
proc parseEnum*[T: enum](s: string, default: T): T =
|
||||
## parses an enum ``T``. Uses `default` for an invalid value in
|
||||
## `s`. The comparison is done in a style insensitive way.
|
||||
for e in low(T)..high(T):
|
||||
if cmpIgnoreStyle(s, $e) == 0:
|
||||
return e
|
||||
result = default
|
||||
|
||||
proc repeatChar*(count: int, c: Char = ' '): string {.noSideEffect,
|
||||
rtl, extern: "nsuRepeatChar".} =
|
||||
@@ -1105,5 +1121,8 @@ when isMainModule:
|
||||
|
||||
doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz "
|
||||
doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz abc"
|
||||
|
||||
|
||||
|
||||
type TMyEnum = enum enA, enB, enC, enuD, enE
|
||||
doAssert parseEnum[TMyEnum]("enu_D") == enuD
|
||||
|
||||
doAssert parseEnum("invalid enum value", enC) == enC
|
||||
|
||||
@@ -2232,4 +2232,3 @@ template eval*(blk: stmt): stmt =
|
||||
|
||||
when defined(initDebugger):
|
||||
initDebugger()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user