Skip to content

Commit

Permalink
address #7430: to
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Apr 3, 2018
1 parent 17d0e29 commit d887e01
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/pure/conv.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#
#
# Nim's Runtime Library
# (c) Copyright 2018 Nim contributors
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#

##[
Universal conversion template.
Usage:
.. code-block:: nim
import conv
echo "yes".to(bool)
echo "0034".to(int)
Design:
each specialized `to` overload should belong in its respective module, eg:
`parseJson` in `lib/pure/json.nim`
to avoid making this module pull in all dependencies
]##

import strutils

template to*(source: string; dest: typedesc[bool]): untyped = parseBool(source)
template to*(source: string; dest: typedesc[int]): untyped = parseInt(source)
template to*(source: string; dest: typedesc[float]): untyped = parseFloat(source)
2 changes: 2 additions & 0 deletions lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1339,6 +1339,8 @@ else:
proc parseJson*(buffer: string): JsonNode =
return parseNativeJson(buffer).convertObject()

template to*(source: string; dest: typedesc[JsonNode]): untyped = parseJson(source)

# -- Json deserialiser macro. --

proc createJsonIndexer(jsonNode: NimNode,
Expand Down
6 changes: 6 additions & 0 deletions tests/stdlib/tconv.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import conv

doAssert "true".to(bool) == true
doAssert "yes".to(bool) == true
doAssert "0034".to(int) == 34
doAssert "1.5".to(float) == 1.5
13 changes: 13 additions & 0 deletions tests/stdlib/tjsonmacro.nim
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,19 @@ when isMainModule:
except:
doAssert false

# Test parseJson vs to
block:
let str = """
{
"person": {
"name": "Nimmer",
"age": 21
},
"list": [1, 2, 3, 4]
}
"""
doAssert str.parseJson == str.to(JsonNode)

# Test the example in json module.
block:
let jsonNode = parseJson("""
Expand Down

0 comments on commit d887e01

Please sign in to comment.