parseutils.nim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains helpers for parsing tokens, numbers, integers, floats,
  10. ## identifiers, etc.
  11. ##
  12. ## To unpack raw bytes look at the `streams <streams.html>`_ module.
  13. ##
  14. ## .. code-block:: nim
  15. ## :test:
  16. ##
  17. ## let logs = @["2019-01-10: OK_", "2019-01-11: FAIL_", "2019-01: aaaa"]
  18. ## var outp: seq[string]
  19. ##
  20. ## for log in logs:
  21. ## var res: string
  22. ## if parseUntil(log, res, ':') == 10: # YYYY-MM-DD == 10
  23. ## outp.add(res & " - " & captureBetween(log, ' ', '_'))
  24. ## doAssert outp == @["2019-01-10 - OK", "2019-01-11 - FAIL"]
  25. ##
  26. ## .. code-block:: nim
  27. ## :test:
  28. ## from strutils import Digits, parseInt
  29. ##
  30. ## let
  31. ## input1 = "2019 school start"
  32. ## input2 = "3 years back"
  33. ## startYear = input1[0 .. skipWhile(input1, Digits)-1] # 2019
  34. ## yearsBack = input2[0 .. skipWhile(input2, Digits)-1] # 3
  35. ## examYear = parseInt(startYear) + parseInt(yearsBack)
  36. ## doAssert "Examination is in " & $examYear == "Examination is in 2022"
  37. ##
  38. ## **See also:**
  39. ## * `strutils module<strutils.html>`_ for combined and identical parsing proc's
  40. ## * `json module<json.html>`_ for a JSON parser
  41. ## * `parsecfg module<parsecfg.html>`_ for a configuration file parser
  42. ## * `parsecsv module<parsecsv.html>`_ for a simple CSV (comma separated value) parser
  43. ## * `parseopt module<parseopt.html>`_ for a command line parser
  44. ## * `parsexml module<parsexml.html>`_ for a XML / HTML parser
  45. ## * `other parsers<lib.html#pure-libraries-parsers>`_ for other parsers
  46. {.push debugger: off.} # the user does not want to trace a part
  47. # of the standard library!
  48. include "system/inclrtl"
  49. const
  50. Whitespace = {' ', '\t', '\v', '\r', '\l', '\f'}
  51. IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
  52. IdentStartChars = {'a'..'z', 'A'..'Z', '_'}
  53. ## copied from strutils
  54. proc toLower(c: char): char {.inline.} =
  55. result = if c in {'A'..'Z'}: chr(ord(c)-ord('A')+ord('a')) else: c
  56. proc parseBin*[T: SomeInteger](s: string, number: var T, start = 0,
  57. maxLen = 0): int {.noSideEffect.} =
  58. ## Parses a binary number and stores its value in ``number``.
  59. ##
  60. ## Returns the number of the parsed characters or 0 in case of an error.
  61. ## If error, the value of ``number`` is not changed.
  62. ##
  63. ## If ``maxLen == 0``, the parsing continues until the first non-bin character
  64. ## or to the end of the string. Otherwise, no more than ``maxLen`` characters
  65. ## are parsed starting from the ``start`` position.
  66. ##
  67. ## It does not check for overflow. If the value represented by the string is
  68. ## too big to fit into ``number``, only the value of last fitting characters
  69. ## will be stored in ``number`` without producing an error.
  70. runnableExamples:
  71. var num: int
  72. doAssert parseBin("0100_1110_0110_1001_1110_1101", num) == 29
  73. doAssert num == 5138925
  74. doAssert parseBin("3", num) == 0
  75. var num8: int8
  76. doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8) == 32
  77. doAssert num8 == 0b1110_1101'i8
  78. doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8, 3, 9) == 9
  79. doAssert num8 == 0b0100_1110'i8
  80. var num8u: uint8
  81. doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8u) == 32
  82. doAssert num8u == 237
  83. var num64: int64
  84. doAssert parseBin("0100111001101001111011010100111001101001", num64) == 40
  85. doAssert num64 == 336784608873
  86. var i = start
  87. var output = T(0)
  88. var foundDigit = false
  89. let last = min(s.len, if maxLen == 0: s.len else: i + maxLen)
  90. if i + 1 < last and s[i] == '0' and (s[i+1] in {'b', 'B'}): inc(i, 2)
  91. while i < last:
  92. case s[i]
  93. of '_': discard
  94. of '0'..'1':
  95. output = output shl 1 or T(ord(s[i]) - ord('0'))
  96. foundDigit = true
  97. else: break
  98. inc(i)
  99. if foundDigit:
  100. number = output
  101. result = i - start
  102. proc parseOct*[T: SomeInteger](s: string, number: var T, start = 0,
  103. maxLen = 0): int {.noSideEffect.} =
  104. ## Parses an octal number and stores its value in ``number``.
  105. ##
  106. ## Returns the number of the parsed characters or 0 in case of an error.
  107. ## If error, the value of ``number`` is not changed.
  108. ##
  109. ## If ``maxLen == 0``, the parsing continues until the first non-oct character
  110. ## or to the end of the string. Otherwise, no more than ``maxLen`` characters
  111. ## are parsed starting from the ``start`` position.
  112. ##
  113. ## It does not check for overflow. If the value represented by the string is
  114. ## too big to fit into ``number``, only the value of last fitting characters
  115. ## will be stored in ``number`` without producing an error.
  116. runnableExamples:
  117. var num: int
  118. doAssert parseOct("0o23464755", num) == 10
  119. doAssert num == 5138925
  120. doAssert parseOct("8", num) == 0
  121. var num8: int8
  122. doAssert parseOct("0o_1464_755", num8) == 11
  123. doAssert num8 == -19
  124. doAssert parseOct("0o_1464_755", num8, 3, 3) == 3
  125. doAssert num8 == 102
  126. var num8u: uint8
  127. doAssert parseOct("1464755", num8u) == 7
  128. doAssert num8u == 237
  129. var num64: int64
  130. doAssert parseOct("2346475523464755", num64) == 16
  131. doAssert num64 == 86216859871725
  132. var i = start
  133. var output = T(0)
  134. var foundDigit = false
  135. let last = min(s.len, if maxLen == 0: s.len else: i + maxLen)
  136. if i + 1 < last and s[i] == '0' and (s[i+1] in {'o', 'O'}): inc(i, 2)
  137. while i < last:
  138. case s[i]
  139. of '_': discard
  140. of '0'..'7':
  141. output = output shl 3 or T(ord(s[i]) - ord('0'))
  142. foundDigit = true
  143. else: break
  144. inc(i)
  145. if foundDigit:
  146. number = output
  147. result = i - start
  148. proc parseHex*[T: SomeInteger](s: string, number: var T, start = 0,
  149. maxLen = 0): int {.noSideEffect.} =
  150. ## Parses a hexadecimal number and stores its value in ``number``.
  151. ##
  152. ## Returns the number of the parsed characters or 0 in case of an error.
  153. ## If error, the value of ``number`` is not changed.
  154. ##
  155. ## If ``maxLen == 0``, the parsing continues until the first non-hex character
  156. ## or to the end of the string. Otherwise, no more than ``maxLen`` characters
  157. ## are parsed starting from the ``start`` position.
  158. ##
  159. ## It does not check for overflow. If the value represented by the string is
  160. ## too big to fit into ``number``, only the value of last fitting characters
  161. ## will be stored in ``number`` without producing an error.
  162. runnableExamples:
  163. var num: int
  164. doAssert parseHex("4E_69_ED", num) == 8
  165. doAssert num == 5138925
  166. doAssert parseHex("X", num) == 0
  167. doAssert parseHex("#ABC", num) == 4
  168. var num8: int8
  169. doAssert parseHex("0x_4E_69_ED", num8) == 11
  170. doAssert num8 == 0xED'i8
  171. doAssert parseHex("0x_4E_69_ED", num8, 3, 2) == 2
  172. doAssert num8 == 0x4E'i8
  173. var num8u: uint8
  174. doAssert parseHex("0x_4E_69_ED", num8u) == 11
  175. doAssert num8u == 237
  176. var num64: int64
  177. doAssert parseHex("4E69ED4E69ED", num64) == 12
  178. doAssert num64 == 86216859871725
  179. var i = start
  180. var output = T(0)
  181. var foundDigit = false
  182. let last = min(s.len, if maxLen == 0: s.len else: i + maxLen)
  183. if i + 1 < last and s[i] == '0' and (s[i+1] in {'x', 'X'}): inc(i, 2)
  184. elif i < last and s[i] == '#': inc(i)
  185. while i < last:
  186. case s[i]
  187. of '_': discard
  188. of '0'..'9':
  189. output = output shl 4 or T(ord(s[i]) - ord('0'))
  190. foundDigit = true
  191. of 'a'..'f':
  192. output = output shl 4 or T(ord(s[i]) - ord('a') + 10)
  193. foundDigit = true
  194. of 'A'..'F':
  195. output = output shl 4 or T(ord(s[i]) - ord('A') + 10)
  196. foundDigit = true
  197. else: break
  198. inc(i)
  199. if foundDigit:
  200. number = output
  201. result = i - start
  202. proc parseIdent*(s: string, ident: var string, start = 0): int =
  203. ## Parses an identifier and stores it in ``ident``. Returns
  204. ## the number of the parsed characters or 0 in case of an error.
  205. runnableExamples:
  206. var res: string
  207. doAssert parseIdent("Hello World", res, 0) == 5
  208. doAssert res == "Hello"
  209. doAssert parseIdent("Hello World", res, 1) == 4
  210. doAssert res == "ello"
  211. doAssert parseIdent("Hello World", res, 6) == 5
  212. doAssert res == "World"
  213. var i = start
  214. if i < s.len and s[i] in IdentStartChars:
  215. inc(i)
  216. while i < s.len and s[i] in IdentChars: inc(i)
  217. ident = substr(s, start, i-1)
  218. result = i-start
  219. proc parseIdent*(s: string, start = 0): string =
  220. ## Parses an identifier and returns it or an empty string in
  221. ## case of an error.
  222. runnableExamples:
  223. doAssert parseIdent("Hello World", 0) == "Hello"
  224. doAssert parseIdent("Hello World", 1) == "ello"
  225. doAssert parseIdent("Hello World", 5) == ""
  226. doAssert parseIdent("Hello World", 6) == "World"
  227. result = ""
  228. var i = start
  229. if i < s.len and s[i] in IdentStartChars:
  230. inc(i)
  231. while i < s.len and s[i] in IdentChars: inc(i)
  232. result = substr(s, start, i-1)
  233. proc skipWhitespace*(s: string, start = 0): int {.inline.} =
  234. ## Skips the whitespace starting at ``s[start]``. Returns the number of
  235. ## skipped characters.
  236. runnableExamples:
  237. doAssert skipWhitespace("Hello World", 0) == 0
  238. doAssert skipWhitespace(" Hello World", 0) == 1
  239. doAssert skipWhitespace("Hello World", 5) == 1
  240. doAssert skipWhitespace("Hello World", 5) == 2
  241. while start+result < s.len and s[start+result] in Whitespace: inc(result)
  242. proc skip*(s, token: string, start = 0): int {.inline.} =
  243. ## Skips the `token` starting at ``s[start]``. Returns the length of `token`
  244. ## or 0 if there was no `token` at ``s[start]``.
  245. runnableExamples:
  246. doAssert skip("2019-01-22", "2019", 0) == 4
  247. doAssert skip("2019-01-22", "19", 0) == 0
  248. doAssert skip("2019-01-22", "19", 2) == 2
  249. doAssert skip("CAPlow", "CAP", 0) == 3
  250. doAssert skip("CAPlow", "cap", 0) == 0
  251. while start+result < s.len and result < token.len and
  252. s[result+start] == token[result]:
  253. inc(result)
  254. if result != token.len: result = 0
  255. proc skipIgnoreCase*(s, token: string, start = 0): int =
  256. ## Same as `skip` but case is ignored for token matching.
  257. runnableExamples:
  258. doAssert skipIgnoreCase("CAPlow", "CAP", 0) == 3
  259. doAssert skipIgnoreCase("CAPlow", "cap", 0) == 3
  260. while start+result < s.len and result < token.len and
  261. toLower(s[result+start]) == toLower(token[result]): inc(result)
  262. if result != token.len: result = 0
  263. proc skipUntil*(s: string, until: set[char], start = 0): int {.inline.} =
  264. ## Skips all characters until one char from the set `until` is found
  265. ## or the end is reached.
  266. ## Returns number of characters skipped.
  267. runnableExamples:
  268. doAssert skipUntil("Hello World", {'W', 'e'}, 0) == 1
  269. doAssert skipUntil("Hello World", {'W'}, 0) == 6
  270. doAssert skipUntil("Hello World", {'W', 'd'}, 0) == 6
  271. while start+result < s.len and s[result+start] notin until: inc(result)
  272. proc skipUntil*(s: string, until: char, start = 0): int {.inline.} =
  273. ## Skips all characters until the char `until` is found
  274. ## or the end is reached.
  275. ## Returns number of characters skipped.
  276. runnableExamples:
  277. doAssert skipUntil("Hello World", 'o', 0) == 4
  278. doAssert skipUntil("Hello World", 'o', 4) == 0
  279. doAssert skipUntil("Hello World", 'W', 0) == 6
  280. doAssert skipUntil("Hello World", 'w', 0) == 11
  281. while start+result < s.len and s[result+start] != until: inc(result)
  282. proc skipWhile*(s: string, toSkip: set[char], start = 0): int {.inline.} =
  283. ## Skips all characters while one char from the set `token` is found.
  284. ## Returns number of characters skipped.
  285. runnableExamples:
  286. doAssert skipWhile("Hello World", {'H', 'e'}) == 2
  287. doAssert skipWhile("Hello World", {'e'}) == 0
  288. doAssert skipWhile("Hello World", {'W', 'o', 'r'}, 6) == 3
  289. while start+result < s.len and s[result+start] in toSkip: inc(result)
  290. proc parseUntil*(s: string, token: var string, until: set[char],
  291. start = 0): int {.inline.} =
  292. ## Parses a token and stores it in ``token``. Returns
  293. ## the number of the parsed characters or 0 in case of an error. A token
  294. ## consists of the characters notin `until`.
  295. runnableExamples:
  296. var myToken: string
  297. doAssert parseUntil("Hello World", myToken, {'W', 'o', 'r'}) == 4
  298. doAssert myToken == "Hell"
  299. doAssert parseUntil("Hello World", myToken, {'W', 'r'}) == 6
  300. doAssert myToken == "Hello "
  301. doAssert parseUntil("Hello World", myToken, {'W', 'r'}, 3) == 3
  302. doAssert myToken == "lo "
  303. var i = start
  304. while i < s.len and s[i] notin until: inc(i)
  305. result = i-start
  306. token = substr(s, start, i-1)
  307. proc parseUntil*(s: string, token: var string, until: char,
  308. start = 0): int {.inline.} =
  309. ## Parses a token and stores it in ``token``. Returns
  310. ## the number of the parsed characters or 0 in case of an error. A token
  311. ## consists of any character that is not the `until` character.
  312. runnableExamples:
  313. var myToken: string
  314. doAssert parseUntil("Hello World", myToken, 'W') == 6
  315. doAssert myToken == "Hello "
  316. doAssert parseUntil("Hello World", myToken, 'o') == 4
  317. doAssert myToken == "Hell"
  318. doAssert parseUntil("Hello World", myToken, 'o', 2) == 2
  319. doAssert myToken == "ll"
  320. var i = start
  321. while i < s.len and s[i] != until: inc(i)
  322. result = i-start
  323. token = substr(s, start, i-1)
  324. proc parseUntil*(s: string, token: var string, until: string,
  325. start = 0): int {.inline.} =
  326. ## Parses a token and stores it in ``token``. Returns
  327. ## the number of the parsed characters or 0 in case of an error. A token
  328. ## consists of any character that comes before the `until` token.
  329. runnableExamples:
  330. var myToken: string
  331. doAssert parseUntil("Hello World", myToken, "Wor") == 6
  332. doAssert myToken == "Hello "
  333. doAssert parseUntil("Hello World", myToken, "Wor", 2) == 4
  334. doAssert myToken == "llo "
  335. when (NimMajor, NimMinor) <= (1, 0):
  336. if until.len == 0:
  337. token.setLen(0)
  338. return 0
  339. var i = start
  340. while i < s.len:
  341. if until.len > 0 and s[i] == until[0]:
  342. var u = 1
  343. while i+u < s.len and u < until.len and s[i+u] == until[u]:
  344. inc u
  345. if u >= until.len: break
  346. inc(i)
  347. result = i-start
  348. token = substr(s, start, i-1)
  349. proc parseWhile*(s: string, token: var string, validChars: set[char],
  350. start = 0): int {.inline.} =
  351. ## Parses a token and stores it in ``token``. Returns
  352. ## the number of the parsed characters or 0 in case of an error. A token
  353. ## consists of the characters in `validChars`.
  354. runnableExamples:
  355. var myToken: string
  356. doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 0) == 0
  357. doAssert myToken.len() == 0
  358. doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 6) == 3
  359. doAssert myToken == "Wor"
  360. var i = start
  361. while i < s.len and s[i] in validChars: inc(i)
  362. result = i-start
  363. token = substr(s, start, i-1)
  364. proc captureBetween*(s: string, first: char, second = '\0', start = 0): string =
  365. ## Finds the first occurrence of ``first``, then returns everything from there
  366. ## up to ``second`` (if ``second`` is '\0', then ``first`` is used).
  367. runnableExamples:
  368. doAssert captureBetween("Hello World", 'e') == "llo World"
  369. doAssert captureBetween("Hello World", 'e', 'r') == "llo Wo"
  370. doAssert captureBetween("Hello World", 'l', start = 6) == "d"
  371. var i = skipUntil(s, first, start)+1+start
  372. result = ""
  373. discard s.parseUntil(result, if second == '\0': first else: second, i)
  374. proc integerOutOfRangeError() {.noinline.} =
  375. raise newException(ValueError, "Parsed integer outside of valid range")
  376. # See #6752
  377. when defined(js):
  378. {.push overflowChecks: off.}
  379. proc rawParseInt(s: string, b: var BiggestInt, start = 0): int =
  380. var
  381. sign: BiggestInt = -1
  382. i = start
  383. if i < s.len:
  384. if s[i] == '+': inc(i)
  385. elif s[i] == '-':
  386. inc(i)
  387. sign = 1
  388. if i < s.len and s[i] in {'0'..'9'}:
  389. b = 0
  390. while i < s.len and s[i] in {'0'..'9'}:
  391. let c = ord(s[i]) - ord('0')
  392. if b >= (low(BiggestInt) + c) div 10:
  393. b = b * 10 - c
  394. else:
  395. integerOutOfRangeError()
  396. inc(i)
  397. while i < s.len and s[i] == '_': inc(i) # underscores are allowed and ignored
  398. if sign == -1 and b == low(BiggestInt):
  399. integerOutOfRangeError()
  400. else:
  401. b = b * sign
  402. result = i - start
  403. when defined(js):
  404. {.pop.} # overflowChecks: off
  405. proc parseBiggestInt*(s: string, number: var BiggestInt, start = 0): int {.
  406. rtl, extern: "npuParseBiggestInt", noSideEffect, raises: [ValueError].} =
  407. ## Parses an integer starting at `start` and stores the value into `number`.
  408. ## Result is the number of processed chars or 0 if there is no integer.
  409. ## `ValueError` is raised if the parsed integer is out of the valid range.
  410. runnableExamples:
  411. var res: BiggestInt
  412. doAssert parseBiggestInt("9223372036854775807", res, 0) == 19
  413. doAssert res == 9223372036854775807
  414. var res: BiggestInt
  415. # use 'res' for exception safety (don't write to 'number' in case of an
  416. # overflow exception):
  417. result = rawParseInt(s, res, start)
  418. if result != 0:
  419. number = res
  420. proc parseInt*(s: string, number: var int, start = 0): int {.
  421. rtl, extern: "npuParseInt", noSideEffect, raises: [ValueError].} =
  422. ## Parses an integer starting at `start` and stores the value into `number`.
  423. ## Result is the number of processed chars or 0 if there is no integer.
  424. ## `ValueError` is raised if the parsed integer is out of the valid range.
  425. runnableExamples:
  426. var res: int
  427. doAssert parseInt("2019", res, 0) == 4
  428. doAssert res == 2019
  429. doAssert parseInt("2019", res, 2) == 2
  430. doAssert res == 19
  431. var res: BiggestInt
  432. result = parseBiggestInt(s, res, start)
  433. when sizeof(int) <= 4:
  434. if res < low(int) or res > high(int):
  435. integerOutOfRangeError()
  436. if result != 0:
  437. number = int(res)
  438. proc parseSaturatedNatural*(s: string, b: var int, start = 0): int {.
  439. raises: [].} =
  440. ## Parses a natural number into ``b``. This cannot raise an overflow
  441. ## error. ``high(int)`` is returned for an overflow.
  442. ## The number of processed character is returned.
  443. ## This is usually what you really want to use instead of `parseInt`:idx:.
  444. runnableExamples:
  445. var res = 0
  446. discard parseSaturatedNatural("848", res)
  447. doAssert res == 848
  448. var i = start
  449. if i < s.len and s[i] == '+': inc(i)
  450. if i < s.len and s[i] in {'0'..'9'}:
  451. b = 0
  452. while i < s.len and s[i] in {'0'..'9'}:
  453. let c = ord(s[i]) - ord('0')
  454. if b <= (high(int) - c) div 10:
  455. b = b * 10 + c
  456. else:
  457. b = high(int)
  458. inc(i)
  459. while i < s.len and s[i] == '_': inc(i) # underscores are allowed and ignored
  460. result = i - start
  461. proc rawParseUInt(s: string, b: var BiggestUInt, start = 0): int =
  462. var
  463. res = 0.BiggestUInt
  464. prev = 0.BiggestUInt
  465. i = start
  466. if i < s.len - 1 and s[i] == '-' and s[i + 1] in {'0'..'9'}:
  467. integerOutOfRangeError()
  468. if i < s.len and s[i] == '+': inc(i) # Allow
  469. if i < s.len and s[i] in {'0'..'9'}:
  470. b = 0
  471. while i < s.len and s[i] in {'0'..'9'}:
  472. prev = res
  473. res = res * 10 + (ord(s[i]) - ord('0')).BiggestUInt
  474. if prev > res:
  475. integerOutOfRangeError()
  476. inc(i)
  477. while i < s.len and s[i] == '_': inc(i) # underscores are allowed and ignored
  478. b = res
  479. result = i - start
  480. proc parseBiggestUInt*(s: string, number: var BiggestUInt, start = 0): int {.
  481. rtl, extern: "npuParseBiggestUInt", noSideEffect, raises: [ValueError].} =
  482. ## Parses an unsigned integer starting at `start` and stores the value
  483. ## into `number`.
  484. ## `ValueError` is raised if the parsed integer is out of the valid range.
  485. runnableExamples:
  486. var res: BiggestUInt
  487. doAssert parseBiggestUInt("12", res, 0) == 2
  488. doAssert res == 12
  489. doAssert parseBiggestUInt("1111111111111111111", res, 0) == 19
  490. doAssert res == 1111111111111111111'u64
  491. var res: BiggestUInt
  492. # use 'res' for exception safety (don't write to 'number' in case of an
  493. # overflow exception):
  494. result = rawParseUInt(s, res, start)
  495. if result != 0:
  496. number = res
  497. proc parseUInt*(s: string, number: var uint, start = 0): int {.
  498. rtl, extern: "npuParseUInt", noSideEffect, raises: [ValueError].} =
  499. ## Parses an unsigned integer starting at `start` and stores the value
  500. ## into `number`.
  501. ## `ValueError` is raised if the parsed integer is out of the valid range.
  502. runnableExamples:
  503. var res: uint
  504. doAssert parseUInt("3450", res) == 4
  505. doAssert res == 3450
  506. doAssert parseUInt("3450", res, 2) == 2
  507. doAssert res == 50
  508. var res: BiggestUInt
  509. result = parseBiggestUInt(s, res, start)
  510. when sizeof(BiggestUInt) > sizeof(uint) and sizeof(uint) <= 4:
  511. if res > 0xFFFF_FFFF'u64:
  512. integerOutOfRangeError()
  513. if result != 0:
  514. number = uint(res)
  515. proc parseBiggestFloat*(s: string, number: var BiggestFloat, start = 0): int {.
  516. magic: "ParseBiggestFloat", importc: "nimParseBiggestFloat", noSideEffect.}
  517. ## Parses a float starting at `start` and stores the value into `number`.
  518. ## Result is the number of processed chars or 0 if a parsing error
  519. ## occurred.
  520. proc parseFloat*(s: string, number: var float, start = 0): int {.
  521. rtl, extern: "npuParseFloat", noSideEffect.} =
  522. ## Parses a float starting at `start` and stores the value into `number`.
  523. ## Result is the number of processed chars or 0 if there occurred a parsing
  524. ## error.
  525. runnableExamples:
  526. var res: float
  527. doAssert parseFloat("32", res, 0) == 2
  528. doAssert res == 32.0
  529. doAssert parseFloat("32.57", res, 0) == 5
  530. doAssert res == 32.57
  531. doAssert parseFloat("32.57", res, 3) == 2
  532. doAssert res == 57.00
  533. var bf: BiggestFloat
  534. result = parseBiggestFloat(s, bf, start)
  535. if result != 0:
  536. number = bf
  537. type
  538. InterpolatedKind* = enum ## Describes for `interpolatedFragments`
  539. ## which part of the interpolated string is
  540. ## yielded; for example in "str$$$var${expr}"
  541. ikStr, ## ``str`` part of the interpolated string
  542. ikDollar, ## escaped ``$`` part of the interpolated string
  543. ikVar, ## ``var`` part of the interpolated string
  544. ikExpr ## ``expr`` part of the interpolated string
  545. iterator interpolatedFragments*(s: string): tuple[kind: InterpolatedKind,
  546. value: string] =
  547. ## Tokenizes the string `s` into substrings for interpolation purposes.
  548. ##
  549. runnableExamples:
  550. var outp: seq[tuple[kind: InterpolatedKind, value: string]]
  551. for k, v in interpolatedFragments(" $this is ${an example} $$"):
  552. outp.add (k, v)
  553. doAssert outp == @[(ikStr, " "),
  554. (ikVar, "this"),
  555. (ikStr, " is "),
  556. (ikExpr, "an example"),
  557. (ikStr, " "),
  558. (ikDollar, "$")]
  559. var i = 0
  560. var kind: InterpolatedKind
  561. while true:
  562. var j = i
  563. if j < s.len and s[j] == '$':
  564. if j+1 < s.len and s[j+1] == '{':
  565. inc j, 2
  566. var nesting = 0
  567. block curlies:
  568. while j < s.len:
  569. case s[j]
  570. of '{': inc nesting
  571. of '}':
  572. if nesting == 0:
  573. inc j
  574. break curlies
  575. dec nesting
  576. else: discard
  577. inc j
  578. raise newException(ValueError,
  579. "Expected closing '}': " & substr(s, i, s.high))
  580. inc i, 2 # skip ${
  581. kind = ikExpr
  582. elif j+1 < s.len and s[j+1] in IdentStartChars:
  583. inc j, 2
  584. while j < s.len and s[j] in IdentChars: inc(j)
  585. inc i # skip $
  586. kind = ikVar
  587. elif j+1 < s.len and s[j+1] == '$':
  588. inc j, 2
  589. inc i # skip $
  590. kind = ikDollar
  591. else:
  592. raise newException(ValueError,
  593. "Unable to parse a variable name at " & substr(s, i, s.high))
  594. else:
  595. while j < s.len and s[j] != '$': inc j
  596. kind = ikStr
  597. if j > i:
  598. # do not copy the trailing } for ikExpr:
  599. yield (kind, substr(s, i, j-1-ord(kind == ikExpr)))
  600. else:
  601. break
  602. i = j
  603. when isMainModule:
  604. import sequtils
  605. let input = "$test{} $this is ${an{ example}} "
  606. let expected = @[(ikVar, "test"), (ikStr, "{} "), (ikVar, "this"),
  607. (ikStr, " is "), (ikExpr, "an{ example}"), (ikStr, " ")]
  608. doAssert toSeq(interpolatedFragments(input)) == expected
  609. var value = 0
  610. discard parseHex("0x38", value)
  611. doAssert value == 56
  612. value = -1
  613. doAssert(parseSaturatedNatural("848", value) == 3)
  614. doAssert value == 848
  615. value = -1
  616. discard parseSaturatedNatural("84899999999999999999324234243143142342135435342532453", value)
  617. doAssert value == high(int)
  618. value = -1
  619. discard parseSaturatedNatural("9223372036854775808", value)
  620. doAssert value == high(int)
  621. value = -1
  622. discard parseSaturatedNatural("9223372036854775807", value)
  623. doAssert value == high(int)
  624. value = -1
  625. discard parseSaturatedNatural("18446744073709551616", value)
  626. doAssert value == high(int)
  627. value = -1
  628. discard parseSaturatedNatural("18446744073709551615", value)
  629. doAssert value == high(int)
  630. value = -1
  631. doAssert(parseSaturatedNatural("1_000_000", value) == 9)
  632. doAssert value == 1_000_000
  633. var i64Value: int64
  634. discard parseBiggestInt("9223372036854775807", i64Value)
  635. doAssert i64Value == 9223372036854775807
  636. {.pop.}