From 26953344c3aa8606b903a4aacf27bb7d7b8bb026 Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Wed, 29 Aug 2018 15:44:30 +0300 Subject: [PATCH] Turn some potentially dangerous templates into functions Be careful when creating templates. If the input parameters are referenced within the body multiple times, this may lead to multiple evaluations of functions with side-effects. --- json_rpc/jsonmarshal.nim | 4 ++-- json_rpc/router.nim | 2 +- tests/ethhexstrings.nim | 8 +++++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/json_rpc/jsonmarshal.nim b/json_rpc/jsonmarshal.nim index b38987a..1cf3849 100644 --- a/json_rpc/jsonmarshal.nim +++ b/json_rpc/jsonmarshal.nim @@ -1,9 +1,9 @@ import macros, json, options, typetraits -template expect*(actual, expected: JsonNodeKind, argName: string) = +proc expect*(actual, expected: JsonNodeKind, argName: string) = if actual != expected: raise newException(ValueError, "Parameter [" & argName & "] expected " & $expected & " but got " & $actual) -template expectType*(actual: JsonNodeKind, expected: typedesc, argName: string, allowNull = false) = +proc expectType*(actual: JsonNodeKind, expected: typedesc, argName: string, allowNull = false) = var expType: JsonNodeKind when expected is array: expType = JArray diff --git a/json_rpc/router.nim b/json_rpc/router.nim index 92f04be..5d325c3 100644 --- a/json_rpc/router.nim +++ b/json_rpc/router.nim @@ -59,7 +59,7 @@ proc clear*(router: var RpcRouter) = router.procs.clear proc hasMethod*(router: RpcRouter, methodName: string): bool = router.procs.hasKey(methodName) -template isEmpty(node: JsonNode): bool = node.isNil or node.kind == JNull +func isEmpty(node: JsonNode): bool = node.isNil or node.kind == JNull # Json state checking diff --git a/tests/ethhexstrings.nim b/tests/ethhexstrings.nim index e97adf1..9fa859a 100644 --- a/tests/ethhexstrings.nim +++ b/tests/ethhexstrings.nim @@ -15,12 +15,14 @@ proc encodeQuantity*(value: SomeUnsignedInt): string = var hValue = value.toHex.stripLeadingZeros result = "0x" & hValue -template hasHexHeader*(value: string | HexDataStr | HexQuantityStr): bool = - template strVal: untyped = value.string +func hasHexHeader*(value: string): bool = if strVal != "" and strVal[0] == '0' and strVal[1] in {'x', 'X'} and strVal.len > 2: true else: false -template isHexChar*(c: char): bool = +template hasHexHeader*(value: HexDataStr|HexQuantityStr): bool = + value.string.hasHexHeader + +func isHexChar*(c: char): bool = if c notin {'0'..'9'} and c notin {'a'..'f'} and c notin {'A'..'F'}: false