strformat.nim 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ##[
  10. String `interpolation`:idx: / `format`:idx: inspired by
  11. Python's ``f``-strings.
  12. ``fmt`` vs. ``&``
  13. =================
  14. You can use either ``fmt`` or the unary ``&`` operator for formatting. The
  15. difference between them is subtle but important.
  16. The ``fmt"{expr}"`` syntax is more aesthetically pleasing, but it hides a small
  17. gotcha. The string is a
  18. `generalized raw string literal <manual.html#lexical-analysis-generalized-raw-string-literals>`_.
  19. This has some surprising effects:
  20. .. code-block:: nim
  21. import strformat
  22. let msg = "hello"
  23. doAssert fmt"{msg}\n" == "hello\\n"
  24. Because the literal is a raw string literal, the ``\n`` is not interpreted as
  25. an escape sequence.
  26. There are multiple ways to get around this, including the use of the ``&``
  27. operator:
  28. .. code-block:: nim
  29. import strformat
  30. let msg = "hello"
  31. doAssert &"{msg}\n" == "hello\n"
  32. doAssert fmt"{msg}{'\n'}" == "hello\n"
  33. doAssert fmt("{msg}\n") == "hello\n"
  34. doAssert "{msg}\n".fmt == "hello\n"
  35. The choice of style is up to you.
  36. Formatting strings
  37. ==================
  38. .. code-block:: nim
  39. import strformat
  40. doAssert &"""{"abc":>4}""" == " abc"
  41. doAssert &"""{"abc":<4}""" == "abc "
  42. Formatting floats
  43. =================
  44. .. code-block:: nim
  45. import strformat
  46. doAssert fmt"{-12345:08}" == "-0012345"
  47. doAssert fmt"{-1:3}" == " -1"
  48. doAssert fmt"{-1:03}" == "-01"
  49. doAssert fmt"{16:#X}" == "0x10"
  50. doAssert fmt"{123.456}" == "123.456"
  51. doAssert fmt"{123.456:>9.3f}" == " 123.456"
  52. doAssert fmt"{123.456:9.3f}" == " 123.456"
  53. doAssert fmt"{123.456:9.4f}" == " 123.4560"
  54. doAssert fmt"{123.456:>9.0f}" == " 123."
  55. doAssert fmt"{123.456:<9.4f}" == "123.4560 "
  56. doAssert fmt"{123.456:e}" == "1.234560e+02"
  57. doAssert fmt"{123.456:>13e}" == " 1.234560e+02"
  58. doAssert fmt"{123.456:13e}" == " 1.234560e+02"
  59. Implementation details
  60. ======================
  61. An expression like ``&"{key} is {value:arg} {{z}}"`` is transformed into:
  62. .. code-block:: nim
  63. var temp = newStringOfCap(educatedCapGuess)
  64. format(key, temp)
  65. format(" is ", temp)
  66. format(value, arg, temp)
  67. format(" {z}", temp)
  68. temp
  69. Parts of the string that are enclosed in the curly braces are interpreted
  70. as Nim code, to escape an ``{`` or ``}`` double it.
  71. ``&`` delegates most of the work to an open overloaded set
  72. of ``format`` procs. The required signature for a type ``T`` that supports
  73. formatting is usually ``proc format(x: T; result: var string)`` for efficiency
  74. but can also be ``proc format(x: T): string``. ``add`` and ``$`` procs are
  75. used as the fallback implementation.
  76. This is the concrete lookup algorithm that ``&`` uses:
  77. .. code-block:: nim
  78. when compiles(format(arg, res)):
  79. format(arg, res)
  80. elif compiles(format(arg)):
  81. res.add format(arg)
  82. elif compiles(add(res, arg)):
  83. res.add(arg)
  84. else:
  85. res.add($arg)
  86. The subexpression after the colon
  87. (``arg`` in ``&"{key} is {value:arg} {{z}}"``) is an optional argument
  88. passed to ``format``.
  89. If an optional argument is present the following lookup algorithm is used:
  90. .. code-block:: nim
  91. when compiles(format(arg, option, res)):
  92. format(arg, option, res)
  93. else:
  94. res.add format(arg, option)
  95. For strings and numeric types the optional argument is a so-called
  96. "standard format specifier".
  97. Standard format specifier for strings, integers and floats
  98. ==========================================================
  99. The general form of a standard format specifier is::
  100. [[fill]align][sign][#][0][minimumwidth][.precision][type]
  101. The square brackets ``[]`` indicate an optional element.
  102. The optional align flag can be one of the following:
  103. '<'
  104. Forces the field to be left-aligned within the available
  105. space. (This is the default for strings.)
  106. '>'
  107. Forces the field to be right-aligned within the available space.
  108. (This is the default for numbers.)
  109. '^'
  110. Forces the field to be centered within the available space.
  111. Note that unless a minimum field width is defined, the field width
  112. will always be the same size as the data to fill it, so that the alignment
  113. option has no meaning in this case.
  114. The optional 'fill' character defines the character to be used to pad
  115. the field to the minimum width. The fill character, if present, must be
  116. followed by an alignment flag.
  117. The 'sign' option is only valid for numeric types, and can be one of the following:
  118. ================= ====================================================
  119. Sign Meaning
  120. ================= ====================================================
  121. ``+`` Indicates that a sign should be used for both
  122. positive as well as negative numbers.
  123. ``-`` Indicates that a sign should be used only for
  124. negative numbers (this is the default behavior).
  125. (space) Indicates that a leading space should be used on
  126. positive numbers.
  127. ================= ====================================================
  128. If the '#' character is present, integers use the 'alternate form' for formatting.
  129. This means that binary, octal, and hexadecimal output will be prefixed
  130. with '0b', '0o', and '0x', respectively.
  131. 'width' is a decimal integer defining the minimum field width. If not specified,
  132. then the field width will be determined by the content.
  133. If the width field is preceded by a zero ('0') character, this enables
  134. zero-padding.
  135. The 'precision' is a decimal number indicating how many digits should be displayed
  136. after the decimal point in a floating point conversion. For non-numeric types the
  137. field indicates the maximum field size - in other words, how many characters will
  138. be used from the field content. The precision is ignored for integer conversions.
  139. Finally, the 'type' determines how the data should be presented.
  140. The available integer presentation types are:
  141. ================= ====================================================
  142. Type Result
  143. ================= ====================================================
  144. ``b`` Binary. Outputs the number in base 2.
  145. ``d`` Decimal Integer. Outputs the number in base 10.
  146. ``o`` Octal format. Outputs the number in base 8.
  147. ``x`` Hex format. Outputs the number in base 16, using
  148. lower-case letters for the digits above 9.
  149. ``X`` Hex format. Outputs the number in base 16, using
  150. uppercase letters for the digits above 9.
  151. (None) the same as 'd'
  152. ================= ====================================================
  153. The available floating point presentation types are:
  154. ================= ====================================================
  155. Type Result
  156. ================= ====================================================
  157. ``e`` Exponent notation. Prints the number in scientific
  158. notation using the letter 'e' to indicate the
  159. exponent.
  160. ``E`` Exponent notation. Same as 'e' except it converts
  161. the number to uppercase.
  162. ``f`` Fixed point. Displays the number as a fixed-point
  163. number.
  164. ``F`` Fixed point. Same as 'f' except it converts the
  165. number to uppercase.
  166. ``g`` General format. This prints the number as a
  167. fixed-point number, unless the number is too
  168. large, in which case it switches to 'e'
  169. exponent notation.
  170. ``G`` General format. Same as 'g' except switches to 'E'
  171. if the number gets to large.
  172. (None) similar to 'g', except that it prints at least one
  173. digit after the decimal point.
  174. ================= ====================================================
  175. Future directions
  176. =================
  177. A curly expression with commas in it like ``{x, argA, argB}`` could be
  178. transformed to ``format(x, argA, argB, res)`` in order to support
  179. formatters that do not need to parse a custom language within a custom
  180. language but instead prefer to use Nim's existing syntax. This also
  181. helps in readability since there is only so much you can cram into
  182. single letter DSLs.
  183. ]##
  184. import macros, parseutils, unicode
  185. import strutils
  186. template callFormat(res, arg) {.dirty.} =
  187. when arg is string:
  188. # workaround in order to circumvent 'strutils.format' which matches
  189. # too but doesn't adhere to our protocol.
  190. res.add arg
  191. elif compiles(format(arg, res)) and
  192. # Check if format returns void
  193. not (compiles do: discard format(arg, res)):
  194. format(arg, res)
  195. elif compiles(format(arg)):
  196. res.add format(arg)
  197. elif compiles(add(res, arg)):
  198. res.add(arg)
  199. else:
  200. res.add($arg)
  201. template callFormatOption(res, arg, option) {.dirty.} =
  202. when compiles(format(arg, option, res)):
  203. format(arg, option, res)
  204. elif compiles(format(arg, option)):
  205. res.add format(arg, option)
  206. else:
  207. format($arg, option, res)
  208. macro `&`*(pattern: string): untyped =
  209. ## For a specification of the ``&`` macro, see the module level documentation.
  210. if pattern.kind notin {nnkStrLit..nnkTripleStrLit}:
  211. error "string formatting (fmt(), &) only works with string literals", pattern
  212. let f = pattern.strVal
  213. var i = 0
  214. let res = genSym(nskVar, "fmtRes")
  215. result = newNimNode(nnkStmtListExpr, lineInfoFrom=pattern)
  216. result.add newVarStmt(res, newCall(bindSym"newStringOfCap", newLit(f.len + count(f, '{')*10)))
  217. var strlit = ""
  218. while i < f.len:
  219. if f[i] == '{':
  220. inc i
  221. if f[i] == '{':
  222. inc i
  223. strlit.add '{'
  224. else:
  225. if strlit.len > 0:
  226. result.add newCall(bindSym"add", res, newLit(strlit))
  227. strlit = ""
  228. var subexpr = ""
  229. while i < f.len and f[i] != '}' and f[i] != ':':
  230. subexpr.add f[i]
  231. inc i
  232. let x = parseExpr(subexpr)
  233. if f[i] == ':':
  234. inc i
  235. var options = ""
  236. while i < f.len and f[i] != '}':
  237. options.add f[i]
  238. inc i
  239. result.add getAst(callFormatOption(res, x, newLit(options)))
  240. else:
  241. result.add getAst(callFormat(res, x))
  242. if f[i] == '}':
  243. inc i
  244. else:
  245. doAssert false, "invalid format string: missing '}'"
  246. elif f[i] == '}':
  247. if f[i+1] == '}':
  248. strlit.add '}'
  249. inc i, 2
  250. else:
  251. doAssert false, "invalid format string: '}' instead of '}}'"
  252. inc i
  253. else:
  254. strlit.add f[i]
  255. inc i
  256. if strlit.len > 0:
  257. result.add newCall(bindSym"add", res, newLit(strlit))
  258. result.add res
  259. when defined(debugFmtDsl):
  260. echo repr result
  261. template fmt*(pattern: string): untyped =
  262. ## An alias for ``&``.
  263. bind `&`
  264. &pattern
  265. proc mkDigit(v: int, typ: char): string {.inline.} =
  266. assert(v < 26)
  267. if v < 10:
  268. result = $chr(ord('0') + v)
  269. else:
  270. result = $chr(ord(if typ == 'x': 'a' else: 'A') + v - 10)
  271. proc alignString*(s: string, minimumWidth: int; align = '\0'; fill = ' '): string =
  272. ## Aligns ``s`` using ``fill`` char.
  273. ## This is only of interest if you want to write a custom ``format`` proc that
  274. ## should support the standard format specifiers.
  275. if minimumWidth == 0:
  276. result = s
  277. else:
  278. let sRuneLen = if s.validateUtf8 == -1: s.runeLen else: s.len
  279. let toFill = minimumWidth - sRuneLen
  280. if toFill <= 0:
  281. result = s
  282. elif align == '<' or align == '\0':
  283. result = s & repeat(fill, toFill)
  284. elif align == '^':
  285. let half = toFill div 2
  286. result = repeat(fill, half) & s & repeat(fill, toFill - half)
  287. else:
  288. result = repeat(fill, toFill) & s
  289. type
  290. StandardFormatSpecifier* = object ## Type that describes "standard format specifiers".
  291. fill*, align*: char ## Desired fill and alignment.
  292. sign*: char ## Desired sign.
  293. alternateForm*: bool ## Whether to prefix binary, octal and hex numbers
  294. ## with ``0b``, ``0o``, ``0x``.
  295. padWithZero*: bool ## Whether to pad with zeros rather than spaces.
  296. minimumWidth*, precision*: int ## Desired minium width and precision.
  297. typ*: char ## Type like 'f', 'g' or 'd'.
  298. endPosition*: int ## End position in the format specifier after
  299. ## ``parseStandardFormatSpecifier`` returned.
  300. proc formatInt(n: SomeNumber; radix: int; spec: StandardFormatSpecifier): string =
  301. ## Converts ``n`` to string. If ``n`` is `SomeFloat`, it casts to `int64`.
  302. ## Conversion is done using ``radix``. If result's length is lesser than
  303. ## ``minimumWidth``, it aligns result to the right or left (depending on ``a``)
  304. ## with ``fill`` char.
  305. when n is SomeUnsignedInt:
  306. var v = n.uint64
  307. let negative = false
  308. else:
  309. var v = n.int64
  310. let negative = v.int64 < 0
  311. if negative:
  312. # FIXME: overflow error for low(int64)
  313. v = v * -1
  314. var xx = ""
  315. if spec.alternateForm:
  316. case spec.typ
  317. of 'X': xx = "0x"
  318. of 'x': xx = "0x"
  319. of 'b': xx = "0b"
  320. of 'o': xx = "0o"
  321. else: discard
  322. if v == 0:
  323. result = "0"
  324. else:
  325. result = ""
  326. while v > type(v)(0):
  327. let d = v mod type(v)(radix)
  328. v = v div type(v)(radix)
  329. result.add(mkDigit(d.int, spec.typ))
  330. for idx in 0..<(result.len div 2):
  331. swap result[idx], result[result.len - idx - 1]
  332. if spec.padWithZero:
  333. let sign = negative or spec.sign != '-'
  334. let toFill = spec.minimumWidth - result.len - xx.len - ord(sign)
  335. if toFill > 0:
  336. result = repeat('0', toFill) & result
  337. if negative:
  338. result = "-" & xx & result
  339. elif spec.sign != '-':
  340. result = spec.sign & xx & result
  341. else:
  342. result = xx & result
  343. if spec.align == '<':
  344. for i in result.len..<spec.minimumWidth:
  345. result.add(spec.fill)
  346. else:
  347. let toFill = spec.minimumWidth - result.len
  348. if spec.align == '^':
  349. let half = toFill div 2
  350. result = repeat(spec.fill, half) & result & repeat(spec.fill, toFill - half)
  351. else:
  352. if toFill > 0:
  353. result = repeat(spec.fill, toFill) & result
  354. proc parseStandardFormatSpecifier*(s: string; start = 0;
  355. ignoreUnknownSuffix = false): StandardFormatSpecifier =
  356. ## An exported helper proc that parses the "standard format specifiers",
  357. ## as specified by the grammar::
  358. ##
  359. ## [[fill]align][sign][#][0][minimumwidth][.precision][type]
  360. ##
  361. ## This is only of interest if you want to write a custom ``format`` proc that
  362. ## should support the standard format specifiers. If ``ignoreUnknownSuffix`` is true,
  363. ## an unknown suffix after the ``type`` field is not an error.
  364. const alignChars = {'<', '>', '^'}
  365. result.fill = ' '
  366. result.align = '\0'
  367. result.sign = '-'
  368. var i = start
  369. if i + 1 < s.len and s[i+1] in alignChars:
  370. result.fill = s[i]
  371. result.align = s[i+1]
  372. inc i, 2
  373. elif i < s.len and s[i] in alignChars:
  374. result.align = s[i]
  375. inc i
  376. if i < s.len and s[i] in {'-', '+', ' '}:
  377. result.sign = s[i]
  378. inc i
  379. if i < s.len and s[i] == '#':
  380. result.alternateForm = true
  381. inc i
  382. if i+1 < s.len and s[i] == '0' and s[i+1] in {'0'..'9'}:
  383. result.padWithZero = true
  384. inc i
  385. let parsedLength = parseSaturatedNatural(s, result.minimumWidth, i)
  386. inc i, parsedLength
  387. if i < s.len and s[i] == '.':
  388. inc i
  389. let parsedLengthB = parseSaturatedNatural(s, result.precision, i)
  390. inc i, parsedLengthB
  391. else:
  392. result.precision = -1
  393. if i < s.len and s[i] in {'A'..'Z', 'a'..'z'}:
  394. result.typ = s[i]
  395. inc i
  396. result.endPosition = i
  397. if i != s.len and not ignoreUnknownSuffix:
  398. raise newException(ValueError,
  399. "invalid format string, cannot parse: " & s[i..^1])
  400. proc format*(value: SomeInteger; specifier: string; res: var string) =
  401. ## Standard format implementation for ``SomeInteger``. It makes little
  402. ## sense to call this directly, but it is required to exist
  403. ## by the ``&`` macro.
  404. let spec = parseStandardFormatSpecifier(specifier)
  405. var radix = 10
  406. case spec.typ
  407. of 'x', 'X': radix = 16
  408. of 'd', '\0': discard
  409. of 'b': radix = 2
  410. of 'o': radix = 8
  411. else:
  412. raise newException(ValueError,
  413. "invalid type in format string for number, expected one " &
  414. " of 'x', 'X', 'b', 'd', 'o' but got: " & spec.typ)
  415. res.add formatInt(value, radix, spec)
  416. proc format*(value: SomeFloat; specifier: string; res: var string) =
  417. ## Standard format implementation for ``SomeFloat``. It makes little
  418. ## sense to call this directly, but it is required to exist
  419. ## by the ``&`` macro.
  420. let spec = parseStandardFormatSpecifier(specifier)
  421. var fmode = ffDefault
  422. case spec.typ
  423. of 'e', 'E':
  424. fmode = ffScientific
  425. of 'f', 'F':
  426. fmode = ffDecimal
  427. of 'g', 'G':
  428. fmode = ffDefault
  429. of '\0': discard
  430. else:
  431. raise newException(ValueError,
  432. "invalid type in format string for number, expected one " &
  433. " of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)
  434. var f = formatBiggestFloat(value, fmode, spec.precision)
  435. var sign = false
  436. if value >= 0.0:
  437. if spec.sign != '-':
  438. sign = true
  439. if value == 0.0:
  440. if 1.0 / value == Inf:
  441. # only insert the sign if value != negZero
  442. f.insert($spec.sign, 0)
  443. else:
  444. f.insert($spec.sign, 0)
  445. else:
  446. sign = true
  447. if spec.padWithZero:
  448. var sign_str = ""
  449. if sign:
  450. sign_str = $f[0]
  451. f = f[1..^1]
  452. let toFill = spec.minimumWidth - f.len - ord(sign)
  453. if toFill > 0:
  454. f = repeat('0', toFill) & f
  455. if sign:
  456. f = sign_str & f
  457. # the default for numbers is right-alignment:
  458. let align = if spec.align == '\0': '>' else: spec.align
  459. let result = alignString(f, spec.minimumWidth,
  460. align, spec.fill)
  461. if spec.typ in {'A'..'Z'}:
  462. res.add toUpperAscii(result)
  463. else:
  464. res.add result
  465. proc format*(value: string; specifier: string; res: var string) =
  466. ## Standard format implementation for ``string``. It makes little
  467. ## sense to call this directly, but it is required to exist
  468. ## by the ``&`` macro.
  469. let spec = parseStandardFormatSpecifier(specifier)
  470. var value = value
  471. case spec.typ
  472. of 's', '\0': discard
  473. else:
  474. raise newException(ValueError,
  475. "invalid type in format string for string, expected 's', but got " &
  476. spec.typ)
  477. if spec.precision != -1:
  478. if spec.precision < runelen(value):
  479. setLen(value, runeOffset(value, spec.precision))
  480. res.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
  481. when isMainModule:
  482. template check(actual, expected: string) =
  483. doAssert actual == expected
  484. from strutils import toUpperAscii, repeat
  485. # Basic tests
  486. let s = "string"
  487. check &"{0} {s}", "0 string"
  488. check &"{s[0..2].toUpperAscii}", "STR"
  489. check &"{-10:04}", "-010"
  490. check &"{-10:<04}", "-010"
  491. check &"{-10:>04}", "-010"
  492. check &"0x{10:02X}", "0x0A"
  493. check &"{10:#04X}", "0x0A"
  494. check &"""{"test":#>5}""", "#test"
  495. check &"""{"test":>5}""", " test"
  496. check &"""{"test":#^7}""", "#test##"
  497. check &"""{"test": <5}""", "test "
  498. check &"""{"test":<5}""", "test "
  499. check &"{1f:.3f}", "1.000"
  500. check &"Hello, {s}!", "Hello, string!"
  501. # Tests for identifers without parenthesis
  502. check &"{s} works{s}", "string worksstring"
  503. check &"{s:>7}", " string"
  504. doAssert(not compiles(&"{s_works}")) # parsed as identifier `s_works`
  505. # Misc general tests
  506. check &"{{}}", "{}"
  507. check &"{0}%", "0%"
  508. check &"{0}%asdf", "0%asdf"
  509. check &("\n{\"\\n\"}\n"), "\n\n\n"
  510. check &"""{"abc"}s""", "abcs"
  511. # String tests
  512. check &"""{"abc"}""", "abc"
  513. check &"""{"abc":>4}""", " abc"
  514. check &"""{"abc":<4}""", "abc "
  515. check &"""{"":>4}""", " "
  516. check &"""{"":<4}""", " "
  517. # Int tests
  518. check &"{12345}", "12345"
  519. check &"{ - 12345}", "-12345"
  520. check &"{12345:6}", " 12345"
  521. check &"{12345:>6}", " 12345"
  522. check &"{12345:4}", "12345"
  523. check &"{12345:08}", "00012345"
  524. check &"{-12345:08}", "-0012345"
  525. check &"{0:0}", "0"
  526. check &"{0:02}", "00"
  527. check &"{-1:3}", " -1"
  528. check &"{-1:03}", "-01"
  529. check &"{10}", "10"
  530. check &"{16:#X}", "0x10"
  531. check &"{16:^#7X}", " 0x10 "
  532. check &"{16:^+#7X}", " +0x10 "
  533. # Hex tests
  534. check &"{0:x}", "0"
  535. check &"{-0:x}", "0"
  536. check &"{255:x}", "ff"
  537. check &"{255:X}", "FF"
  538. check &"{-255:x}", "-ff"
  539. check &"{-255:X}", "-FF"
  540. check &"{255:x} uNaffeCteD CaSe", "ff uNaffeCteD CaSe"
  541. check &"{255:X} uNaffeCteD CaSe", "FF uNaffeCteD CaSe"
  542. check &"{255:4x}", " ff"
  543. check &"{255:04x}", "00ff"
  544. check &"{-255:4x}", " -ff"
  545. check &"{-255:04x}", "-0ff"
  546. # Float tests
  547. check &"{123.456}", "123.456"
  548. check &"{-123.456}", "-123.456"
  549. check &"{123.456:.3f}", "123.456"
  550. check &"{123.456:+.3f}", "+123.456"
  551. check &"{-123.456:+.3f}", "-123.456"
  552. check &"{-123.456:.3f}", "-123.456"
  553. check &"{123.456:1g}", "123.456"
  554. check &"{123.456:.1f}", "123.5"
  555. check &"{123.456:.0f}", "123."
  556. #check &"{123.456:.0f}", "123."
  557. check &"{123.456:>9.3f}", " 123.456"
  558. check &"{123.456:9.3f}", " 123.456"
  559. check &"{123.456:>9.4f}", " 123.4560"
  560. check &"{123.456:>9.0f}", " 123."
  561. check &"{123.456:<9.4f}", "123.4560 "
  562. # Float (scientific) tests
  563. check &"{123.456:e}", "1.234560e+02"
  564. check &"{123.456:>13e}", " 1.234560e+02"
  565. check &"{123.456:<13e}", "1.234560e+02 "
  566. check &"{123.456:.1e}", "1.2e+02"
  567. check &"{123.456:.2e}", "1.23e+02"
  568. check &"{123.456:.3e}", "1.235e+02"
  569. # Note: times.format adheres to the format protocol. Test that this
  570. # works:
  571. import times
  572. var dt = initDateTime(01, mJan, 2000, 00, 00, 00)
  573. check &"{dt:yyyy-MM-dd}", "2000-01-01"
  574. var tm = fromUnix(0)
  575. discard &"{tm}"
  576. # Unicode string tests
  577. check &"""{"αβγ"}""", "αβγ"
  578. check &"""{"αβγ":>5}""", " αβγ"
  579. check &"""{"αβγ":<5}""", "αβγ "
  580. check &"""a{"a"}α{"α"}€{"€"}𐍈{"𐍈"}""", "aaαα€€𐍈𐍈"
  581. check &"""a{"a":2}α{"α":2}€{"€":2}𐍈{"𐍈":2}""", "aa αα €€ 𐍈𐍈 "
  582. # Invalid unicode sequences should be handled as plain strings.
  583. # Invalid examples taken from: https://stackoverflow.com/a/3886015/1804173
  584. let invalidUtf8 = [
  585. "\xc3\x28", "\xa0\xa1",
  586. "\xe2\x28\xa1", "\xe2\x82\x28",
  587. "\xf0\x28\x8c\xbc", "\xf0\x90\x28\xbc", "\xf0\x28\x8c\x28"
  588. ]
  589. for s in invalidUtf8:
  590. check &"{s:>5}", repeat(" ", 5-s.len) & s
  591. import json
  592. doAssert fmt"{'a'} {'b'}" == "a b"
  593. echo("All tests ok")