strmantle.nim 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2018 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Compilerprocs for strings that do not depend on the string implementation.
  10. proc cmpStrings(a, b: string): int {.inline, compilerproc.} =
  11. let alen = a.len
  12. let blen = b.len
  13. let minlen = min(alen, blen)
  14. if minlen > 0:
  15. result = c_memcmp(unsafeAddr a[0], unsafeAddr b[0], cast[csize_t](minlen))
  16. if result == 0:
  17. result = alen - blen
  18. else:
  19. result = alen - blen
  20. proc eqStrings(a, b: string): bool {.inline, compilerproc.} =
  21. let alen = a.len
  22. let blen = b.len
  23. if alen == blen:
  24. if alen == 0: return true
  25. return equalMem(unsafeAddr(a[0]), unsafeAddr(b[0]), alen)
  26. proc hashString(s: string): int {.compilerproc.} =
  27. # the compiler needs exactly the same hash function!
  28. # this used to be used for efficient generation of string case statements
  29. var h : uint = 0
  30. for i in 0..len(s)-1:
  31. h = h + uint(s[i])
  32. h = h + h shl 10
  33. h = h xor (h shr 6)
  34. h = h + h shl 3
  35. h = h xor (h shr 11)
  36. h = h + h shl 15
  37. result = cast[int](h)
  38. proc addInt*(result: var string; x: int64) =
  39. ## Converts integer to its string representation and appends it to `result`.
  40. ##
  41. ## .. code-block:: Nim
  42. ## var
  43. ## a = "123"
  44. ## b = 45
  45. ## a.addInt(b) # a <- "12345"
  46. let base = result.len
  47. setLen(result, base + sizeof(x)*4)
  48. var i = 0
  49. var y = x
  50. while true:
  51. var d = y div 10
  52. result[base+i] = chr(abs(int(y - d*10)) + ord('0'))
  53. inc(i)
  54. y = d
  55. if y == 0: break
  56. if x < 0:
  57. result[base+i] = '-'
  58. inc(i)
  59. setLen(result, base+i)
  60. # mirror the string:
  61. for j in 0..i div 2 - 1:
  62. swap(result[base+j], result[base+i-j-1])
  63. proc nimIntToStr(x: int): string {.compilerRtl.} =
  64. result = newStringOfCap(sizeof(x)*4)
  65. result.addInt x
  66. proc addCstringN(result: var string, buf: cstring; buflen: int) =
  67. # no nimvm support needed, so it doesn't need to be fast here either
  68. let oldLen = result.len
  69. let newLen = oldLen + buflen
  70. result.setLen newLen
  71. copyMem(result[oldLen].addr, buf, buflen)
  72. import formatfloat
  73. proc addFloat*(result: var string; x: float) =
  74. ## Converts float to its string representation and appends it to `result`.
  75. ##
  76. ## .. code-block:: Nim
  77. ## var
  78. ## a = "123"
  79. ## b = 45.67
  80. ## a.addFloat(b) # a <- "12345.67"
  81. when nimvm:
  82. result.add $x
  83. else:
  84. var buffer {.noinit.}: array[65, char]
  85. let n = writeFloatToBuffer(buffer, x)
  86. result.addCstringN(cstring(buffer[0].addr), n)
  87. proc nimFloatToStr(f: float): string {.compilerproc.} =
  88. result = newStringOfCap(8)
  89. result.addFloat f
  90. proc c_strtod(buf: cstring, endptr: ptr cstring): float64 {.
  91. importc: "strtod", header: "<stdlib.h>", noSideEffect.}
  92. const
  93. IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
  94. powtens = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  95. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  96. 1e20, 1e21, 1e22]
  97. when defined(nimHasInvariant):
  98. {.push staticBoundChecks: off.}
  99. proc nimParseBiggestFloat(s: string, number: var BiggestFloat,
  100. start = 0): int {.compilerproc.} =
  101. # This routine attempt to parse float that can parsed quickly.
  102. # i.e. whose integer part can fit inside a 53bits integer.
  103. # their real exponent must also be <= 22. If the float doesn't follow
  104. # these restrictions, transform the float into this form:
  105. # INTEGER * 10 ^ exponent and leave the work to standard `strtod()`.
  106. # This avoid the problems of decimal character portability.
  107. # see: http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
  108. var
  109. i = start
  110. sign = 1.0
  111. kdigits, fdigits = 0
  112. exponent = 0
  113. integer = uint64(0)
  114. fracExponent = 0
  115. expSign = 1
  116. firstDigit = -1
  117. hasSign = false
  118. # Sign?
  119. if i < s.len and (s[i] == '+' or s[i] == '-'):
  120. hasSign = true
  121. if s[i] == '-':
  122. sign = -1.0
  123. inc(i)
  124. # NaN?
  125. if i+2 < s.len and (s[i] == 'N' or s[i] == 'n'):
  126. if s[i+1] == 'A' or s[i+1] == 'a':
  127. if s[i+2] == 'N' or s[i+2] == 'n':
  128. if i+3 >= s.len or s[i+3] notin IdentChars:
  129. number = NaN
  130. return i+3 - start
  131. return 0
  132. # Inf?
  133. if i+2 < s.len and (s[i] == 'I' or s[i] == 'i'):
  134. if s[i+1] == 'N' or s[i+1] == 'n':
  135. if s[i+2] == 'F' or s[i+2] == 'f':
  136. if i+3 >= s.len or s[i+3] notin IdentChars:
  137. number = Inf*sign
  138. return i+3 - start
  139. return 0
  140. if i < s.len and s[i] in {'0'..'9'}:
  141. firstDigit = (s[i].ord - '0'.ord)
  142. # Integer part?
  143. while i < s.len and s[i] in {'0'..'9'}:
  144. inc(kdigits)
  145. integer = integer * 10'u64 + (s[i].ord - '0'.ord).uint64
  146. inc(i)
  147. while i < s.len and s[i] == '_': inc(i)
  148. # Fractional part?
  149. if i < s.len and s[i] == '.':
  150. inc(i)
  151. # if no integer part, Skip leading zeros
  152. if kdigits <= 0:
  153. while i < s.len and s[i] == '0':
  154. inc(fracExponent)
  155. inc(i)
  156. while i < s.len and s[i] == '_': inc(i)
  157. if firstDigit == -1 and i < s.len and s[i] in {'0'..'9'}:
  158. firstDigit = (s[i].ord - '0'.ord)
  159. # get fractional part
  160. while i < s.len and s[i] in {'0'..'9'}:
  161. inc(fdigits)
  162. inc(fracExponent)
  163. integer = integer * 10'u64 + (s[i].ord - '0'.ord).uint64
  164. inc(i)
  165. while i < s.len and s[i] == '_': inc(i)
  166. # if has no digits: return error
  167. if kdigits + fdigits <= 0 and
  168. (i == start or # no char consumed (empty string).
  169. (i == start + 1 and hasSign)): # or only '+' or '-
  170. return 0
  171. if i+1 < s.len and s[i] in {'e', 'E'}:
  172. inc(i)
  173. if s[i] == '+' or s[i] == '-':
  174. if s[i] == '-':
  175. expSign = -1
  176. inc(i)
  177. if s[i] notin {'0'..'9'}:
  178. return 0
  179. while i < s.len and s[i] in {'0'..'9'}:
  180. exponent = exponent * 10 + (ord(s[i]) - ord('0'))
  181. inc(i)
  182. while i < s.len and s[i] == '_': inc(i) # underscores are allowed and ignored
  183. var realExponent = expSign*exponent - fracExponent
  184. let expNegative = realExponent < 0
  185. var absExponent = abs(realExponent)
  186. # if exponent greater than can be represented: +/- zero or infinity
  187. if absExponent > 999:
  188. if expNegative:
  189. number = 0.0*sign
  190. else:
  191. number = Inf*sign
  192. return i - start
  193. # if integer is representable in 53 bits: fast path
  194. # max fast path integer is 1<<53 - 1 or 8999999999999999 (16 digits)
  195. let digits = kdigits + fdigits
  196. if digits <= 15 or (digits <= 16 and firstDigit <= 8):
  197. # max float power of ten with set bits above the 53th bit is 10^22
  198. if absExponent <= 22:
  199. if expNegative:
  200. number = sign * integer.float / powtens[absExponent]
  201. else:
  202. number = sign * integer.float * powtens[absExponent]
  203. return i - start
  204. # if exponent is greater try to fit extra exponent above 22 by multiplying
  205. # integer part is there is space left.
  206. let slop = 15 - kdigits - fdigits
  207. if absExponent <= 22 + slop and not expNegative:
  208. number = sign * integer.float * powtens[slop] * powtens[absExponent-slop]
  209. return i - start
  210. # if failed: slow path with strtod.
  211. var t: array[500, char] # flaviu says: 325 is the longest reasonable literal
  212. var ti = 0
  213. let maxlen = t.high - "e+000".len # reserve enough space for exponent
  214. result = i - start
  215. i = start
  216. # re-parse without error checking, any error should be handled by the code above.
  217. if i < s.len and s[i] == '.': i.inc
  218. while i < s.len and s[i] in {'0'..'9','+','-'}:
  219. if ti < maxlen:
  220. t[ti] = s[i]; inc(ti)
  221. inc(i)
  222. while i < s.len and s[i] in {'.', '_'}: # skip underscore and decimal point
  223. inc(i)
  224. # insert exponent
  225. t[ti] = 'E'
  226. inc(ti)
  227. t[ti] = if expNegative: '-' else: '+'
  228. inc(ti, 4)
  229. # insert adjusted exponent
  230. t[ti-1] = ('0'.ord + absExponent mod 10).char
  231. absExponent = absExponent div 10
  232. t[ti-2] = ('0'.ord + absExponent mod 10).char
  233. absExponent = absExponent div 10
  234. t[ti-3] = ('0'.ord + absExponent mod 10).char
  235. when defined(nimNoArrayToCstringConversion):
  236. number = c_strtod(addr t, nil)
  237. else:
  238. number = c_strtod(t, nil)
  239. when defined(nimHasInvariant):
  240. {.pop.} # staticBoundChecks
  241. proc nimInt64ToStr(x: int64): string {.compilerRtl.} =
  242. result = newStringOfCap(sizeof(x)*4)
  243. result.addInt x
  244. proc nimBoolToStr(x: bool): string {.compilerRtl.} =
  245. return if x: "true" else: "false"
  246. proc nimCharToStr(x: char): string {.compilerRtl.} =
  247. result = newString(1)
  248. result[0] = x
  249. when defined(gcDestructors):
  250. proc GC_getStatistics*(): string =
  251. result = "[GC] total memory: "
  252. result.addInt getTotalMem()
  253. result.add "\n[GC] occupied memory: "
  254. result.addInt getOccupiedMem()
  255. result.add '\n'
  256. #"[GC] cycle collections: " & $gch.stat.cycleCollections & "\n" &