strutils.nim 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957
  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. ## The system module defines several common functions for working with strings,
  10. ## such as:
  11. ## * `$` for converting other data-types to strings
  12. ## * `&` for string concatenation
  13. ## * `add` for adding a new character or a string to the existing one
  14. ## * `in` (alias for `contains`) and `notin` for checking if a character
  15. ## is in a string
  16. ##
  17. ## This module builds upon that, providing additional functionality in form of
  18. ## procedures, iterators and templates for strings.
  19. runnableExamples:
  20. let
  21. numbers = @[867, 5309]
  22. multiLineString = "first line\nsecond line\nthird line"
  23. let jenny = numbers.join("-")
  24. assert jenny == "867-5309"
  25. assert splitLines(multiLineString) ==
  26. @["first line", "second line", "third line"]
  27. assert split(multiLineString) == @["first", "line", "second",
  28. "line", "third", "line"]
  29. assert indent(multiLineString, 4) ==
  30. " first line\n second line\n third line"
  31. assert 'z'.repeat(5) == "zzzzz"
  32. ## The chaining of functions is possible thanks to the
  33. ## `method call syntax<manual.html#procedures-method-call-syntax>`_:
  34. runnableExamples:
  35. from std/sequtils import map
  36. let jenny = "867-5309"
  37. assert jenny.split('-').map(parseInt) == @[867, 5309]
  38. assert "Beetlejuice".indent(1).repeat(3).strip ==
  39. "Beetlejuice Beetlejuice Beetlejuice"
  40. ## This module is available for the `JavaScript target
  41. ## <backends.html#backends-the-javascript-target>`_.
  42. ##
  43. ## ----
  44. ##
  45. ## **See also:**
  46. ## * `strformat module<strformat.html>`_ for string interpolation and formatting
  47. ## * `unicode module<unicode.html>`_ for Unicode UTF-8 handling
  48. ## * `sequtils module<sequtils.html>`_ for operations on container
  49. ## types (including strings)
  50. ## * `parsecsv module<parsecsv.html>`_ for a high-performance CSV parser
  51. ## * `parseutils module<parseutils.html>`_ for lower-level parsing of tokens,
  52. ## numbers, identifiers, etc.
  53. ## * `parseopt module<parseopt.html>`_ for command-line parsing
  54. ## * `pegs module<pegs.html>`_ for PEG (Parsing Expression Grammar) support
  55. ## * `strtabs module<strtabs.html>`_ for efficient hash tables
  56. ## (dictionaries, in some programming languages) mapping from strings to strings
  57. ## * `ropes module<ropes.html>`_ for rope data type, which can represent very
  58. ## long strings efficiently
  59. ## * `re module<re.html>`_ for regular expression (regex) support
  60. ## * `strscans<strscans.html>`_ for `scanf` and `scanp` macros, which offer
  61. ## easier substring extraction than regular expressions
  62. import parseutils
  63. from math import pow, floor, log10
  64. from algorithm import fill, reverse
  65. import std/enumutils
  66. from unicode import toLower, toUpper
  67. export toLower, toUpper
  68. include "system/inclrtl"
  69. import std/private/[since, jsutils]
  70. from std/private/strimpl import cmpIgnoreStyleImpl, cmpIgnoreCaseImpl,
  71. startsWithImpl, endsWithImpl
  72. when defined(nimPreviewSlimSystem):
  73. import std/assertions
  74. const
  75. Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'}
  76. ## All the characters that count as whitespace (space, tab, vertical tab,
  77. ## carriage return, new line, form feed).
  78. Letters* = {'A'..'Z', 'a'..'z'}
  79. ## The set of letters.
  80. UppercaseLetters* = {'A'..'Z'}
  81. ## The set of uppercase ASCII letters.
  82. LowercaseLetters* = {'a'..'z'}
  83. ## The set of lowercase ASCII letters.
  84. PunctuationChars* = {'!'..'/', ':'..'@', '['..'`', '{'..'~'}
  85. ## The set of all ASCII punctuation characters.
  86. Digits* = {'0'..'9'}
  87. ## The set of digits.
  88. HexDigits* = {'0'..'9', 'A'..'F', 'a'..'f'}
  89. ## The set of hexadecimal digits.
  90. IdentChars* = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
  91. ## The set of characters an identifier can consist of.
  92. IdentStartChars* = {'a'..'z', 'A'..'Z', '_'}
  93. ## The set of characters an identifier can start with.
  94. Newlines* = {'\13', '\10'}
  95. ## The set of characters a newline terminator can start with (carriage
  96. ## return, line feed).
  97. PrintableChars* = Letters + Digits + PunctuationChars + Whitespace
  98. ## The set of all printable ASCII characters (letters, digits, whitespace, and punctuation characters).
  99. AllChars* = {'\x00'..'\xFF'}
  100. ## A set with all the possible characters.
  101. ##
  102. ## Not very useful by its own, you can use it to create *inverted* sets to
  103. ## make the `find func<#find,string,set[char],Natural,int>`_
  104. ## find **invalid** characters in strings. Example:
  105. ##
  106. ## .. code-block:: nim
  107. ## let invalid = AllChars - Digits
  108. ## doAssert "01234".find(invalid) == -1
  109. ## doAssert "01A34".find(invalid) == 2
  110. func isAlphaAscii*(c: char): bool {.rtl, extern: "nsuIsAlphaAsciiChar".} =
  111. ## Checks whether or not character `c` is alphabetical.
  112. ##
  113. ## This checks a-z, A-Z ASCII characters only.
  114. ## Use `Unicode module<unicode.html>`_ for UTF-8 support.
  115. runnableExamples:
  116. doAssert isAlphaAscii('e') == true
  117. doAssert isAlphaAscii('E') == true
  118. doAssert isAlphaAscii('8') == false
  119. return c in Letters
  120. func isAlphaNumeric*(c: char): bool {.rtl, extern: "nsuIsAlphaNumericChar".} =
  121. ## Checks whether or not `c` is alphanumeric.
  122. ##
  123. ## This checks a-z, A-Z, 0-9 ASCII characters only.
  124. runnableExamples:
  125. doAssert isAlphaNumeric('n') == true
  126. doAssert isAlphaNumeric('8') == true
  127. doAssert isAlphaNumeric(' ') == false
  128. return c in Letters+Digits
  129. func isDigit*(c: char): bool {.rtl, extern: "nsuIsDigitChar".} =
  130. ## Checks whether or not `c` is a number.
  131. ##
  132. ## This checks 0-9 ASCII characters only.
  133. runnableExamples:
  134. doAssert isDigit('n') == false
  135. doAssert isDigit('8') == true
  136. return c in Digits
  137. func isSpaceAscii*(c: char): bool {.rtl, extern: "nsuIsSpaceAsciiChar".} =
  138. ## Checks whether or not `c` is a whitespace character.
  139. runnableExamples:
  140. doAssert isSpaceAscii('n') == false
  141. doAssert isSpaceAscii(' ') == true
  142. doAssert isSpaceAscii('\t') == true
  143. return c in Whitespace
  144. func isLowerAscii*(c: char): bool {.rtl, extern: "nsuIsLowerAsciiChar".} =
  145. ## Checks whether or not `c` is a lower case character.
  146. ##
  147. ## This checks ASCII characters only.
  148. ## Use `Unicode module<unicode.html>`_ for UTF-8 support.
  149. ##
  150. ## See also:
  151. ## * `toLowerAscii func<#toLowerAscii,char>`_
  152. runnableExamples:
  153. doAssert isLowerAscii('e') == true
  154. doAssert isLowerAscii('E') == false
  155. doAssert isLowerAscii('7') == false
  156. return c in LowercaseLetters
  157. func isUpperAscii*(c: char): bool {.rtl, extern: "nsuIsUpperAsciiChar".} =
  158. ## Checks whether or not `c` is an upper case character.
  159. ##
  160. ## This checks ASCII characters only.
  161. ## Use `Unicode module<unicode.html>`_ for UTF-8 support.
  162. ##
  163. ## See also:
  164. ## * `toUpperAscii func<#toUpperAscii,char>`_
  165. runnableExamples:
  166. doAssert isUpperAscii('e') == false
  167. doAssert isUpperAscii('E') == true
  168. doAssert isUpperAscii('7') == false
  169. return c in UppercaseLetters
  170. func toLowerAscii*(c: char): char {.rtl, extern: "nsuToLowerAsciiChar".} =
  171. ## Returns the lower case version of character `c`.
  172. ##
  173. ## This works only for the letters `A-Z`. See `unicode.toLower
  174. ## <unicode.html#toLower,Rune>`_ for a version that works for any Unicode
  175. ## character.
  176. ##
  177. ## See also:
  178. ## * `isLowerAscii func<#isLowerAscii,char>`_
  179. ## * `toLowerAscii func<#toLowerAscii,string>`_ for converting a string
  180. runnableExamples:
  181. doAssert toLowerAscii('A') == 'a'
  182. doAssert toLowerAscii('e') == 'e'
  183. if c in UppercaseLetters:
  184. result = char(uint8(c) xor 0b0010_0000'u8)
  185. else:
  186. result = c
  187. template toImpl(call) =
  188. result = newString(len(s))
  189. for i in 0..len(s) - 1:
  190. result[i] = call(s[i])
  191. func toLowerAscii*(s: string): string {.rtl, extern: "nsuToLowerAsciiStr".} =
  192. ## Converts string `s` into lower case.
  193. ##
  194. ## This works only for the letters `A-Z`. See `unicode.toLower
  195. ## <unicode.html#toLower,string>`_ for a version that works for any Unicode
  196. ## character.
  197. ##
  198. ## See also:
  199. ## * `normalize func<#normalize,string>`_
  200. runnableExamples:
  201. doAssert toLowerAscii("FooBar!") == "foobar!"
  202. toImpl toLowerAscii
  203. func toUpperAscii*(c: char): char {.rtl, extern: "nsuToUpperAsciiChar".} =
  204. ## Converts character `c` into upper case.
  205. ##
  206. ## This works only for the letters `A-Z`. See `unicode.toUpper
  207. ## <unicode.html#toUpper,Rune>`_ for a version that works for any Unicode
  208. ## character.
  209. ##
  210. ## See also:
  211. ## * `isUpperAscii func<#isUpperAscii,char>`_
  212. ## * `toUpperAscii func<#toUpperAscii,string>`_ for converting a string
  213. ## * `capitalizeAscii func<#capitalizeAscii,string>`_
  214. runnableExamples:
  215. doAssert toUpperAscii('a') == 'A'
  216. doAssert toUpperAscii('E') == 'E'
  217. if c in LowercaseLetters:
  218. result = char(uint8(c) xor 0b0010_0000'u8)
  219. else:
  220. result = c
  221. func toUpperAscii*(s: string): string {.rtl, extern: "nsuToUpperAsciiStr".} =
  222. ## Converts string `s` into upper case.
  223. ##
  224. ## This works only for the letters `A-Z`. See `unicode.toUpper
  225. ## <unicode.html#toUpper,string>`_ for a version that works for any Unicode
  226. ## character.
  227. ##
  228. ## See also:
  229. ## * `capitalizeAscii func<#capitalizeAscii,string>`_
  230. runnableExamples:
  231. doAssert toUpperAscii("FooBar!") == "FOOBAR!"
  232. toImpl toUpperAscii
  233. func capitalizeAscii*(s: string): string {.rtl, extern: "nsuCapitalizeAscii".} =
  234. ## Converts the first character of string `s` into upper case.
  235. ##
  236. ## This works only for the letters `A-Z`.
  237. ## Use `Unicode module<unicode.html>`_ for UTF-8 support.
  238. ##
  239. ## See also:
  240. ## * `toUpperAscii func<#toUpperAscii,char>`_
  241. runnableExamples:
  242. doAssert capitalizeAscii("foo") == "Foo"
  243. doAssert capitalizeAscii("-bar") == "-bar"
  244. if s.len == 0: result = ""
  245. else: result = toUpperAscii(s[0]) & substr(s, 1)
  246. func nimIdentNormalize*(s: string): string =
  247. ## Normalizes the string `s` as a Nim identifier.
  248. ##
  249. ## That means to convert to lower case and remove any '_' on all characters
  250. ## except first one.
  251. ##
  252. ## .. Warning:: Backticks (`) are not handled: they remain *as is* and
  253. ## spaces are preserved. See `nimIdentBackticksNormalize
  254. ## <dochelpers.html#nimIdentBackticksNormalize,string>`_ for
  255. ## an alternative approach.
  256. runnableExamples:
  257. doAssert nimIdentNormalize("Foo_bar") == "Foobar"
  258. result = newString(s.len)
  259. if s.len == 0:
  260. return
  261. result[0] = s[0]
  262. var j = 1
  263. for i in 1..len(s) - 1:
  264. if s[i] in UppercaseLetters:
  265. result[j] = chr(ord(s[i]) + (ord('a') - ord('A')))
  266. inc j
  267. elif s[i] != '_':
  268. result[j] = s[i]
  269. inc j
  270. if j != s.len: setLen(result, j)
  271. func normalize*(s: string): string {.rtl, extern: "nsuNormalize".} =
  272. ## Normalizes the string `s`.
  273. ##
  274. ## That means to convert it to lower case and remove any '_'. This
  275. ## should NOT be used to normalize Nim identifier names.
  276. ##
  277. ## See also:
  278. ## * `toLowerAscii func<#toLowerAscii,string>`_
  279. runnableExamples:
  280. doAssert normalize("Foo_bar") == "foobar"
  281. doAssert normalize("Foo Bar") == "foo bar"
  282. result = newString(s.len)
  283. var j = 0
  284. for i in 0..len(s) - 1:
  285. if s[i] in UppercaseLetters:
  286. result[j] = chr(ord(s[i]) + (ord('a') - ord('A')))
  287. inc j
  288. elif s[i] != '_':
  289. result[j] = s[i]
  290. inc j
  291. if j != s.len: setLen(result, j)
  292. func cmpIgnoreCase*(a, b: string): int {.rtl, extern: "nsuCmpIgnoreCase".} =
  293. ## Compares two strings in a case insensitive manner. Returns:
  294. ##
  295. ## | 0 if a == b
  296. ## | < 0 if a < b
  297. ## | > 0 if a > b
  298. runnableExamples:
  299. doAssert cmpIgnoreCase("FooBar", "foobar") == 0
  300. doAssert cmpIgnoreCase("bar", "Foo") < 0
  301. doAssert cmpIgnoreCase("Foo5", "foo4") > 0
  302. cmpIgnoreCaseImpl(a, b)
  303. {.push checks: off, line_trace: off.} # this is a hot-spot in the compiler!
  304. # thus we compile without checks here
  305. func cmpIgnoreStyle*(a, b: string): int {.rtl, extern: "nsuCmpIgnoreStyle".} =
  306. ## Semantically the same as `cmp(normalize(a), normalize(b))`. It
  307. ## is just optimized to not allocate temporary strings. This should
  308. ## NOT be used to compare Nim identifier names.
  309. ## Use `macros.eqIdent<macros.html#eqIdent,string,string>`_ for that.
  310. ##
  311. ## Returns:
  312. ##
  313. ## | 0 if a == b
  314. ## | < 0 if a < b
  315. ## | > 0 if a > b
  316. runnableExamples:
  317. doAssert cmpIgnoreStyle("foo_bar", "FooBar") == 0
  318. doAssert cmpIgnoreStyle("foo_bar_5", "FooBar4") > 0
  319. cmpIgnoreStyleImpl(a, b)
  320. {.pop.}
  321. # --------- Private templates for different split separators -----------
  322. func substrEq(s: string, pos: int, substr: string): bool =
  323. var i = 0
  324. var length = substr.len
  325. while i < length and pos+i < s.len and s[pos+i] == substr[i]:
  326. inc i
  327. return i == length
  328. template stringHasSep(s: string, index: int, seps: set[char]): bool =
  329. s[index] in seps
  330. template stringHasSep(s: string, index: int, sep: char): bool =
  331. s[index] == sep
  332. template stringHasSep(s: string, index: int, sep: string): bool =
  333. s.substrEq(index, sep)
  334. template splitCommon(s, sep, maxsplit, sepLen) =
  335. ## Common code for split procs
  336. var last = 0
  337. var splits = maxsplit
  338. while last <= len(s):
  339. var first = last
  340. while last < len(s) and not stringHasSep(s, last, sep):
  341. inc(last)
  342. if splits == 0: last = len(s)
  343. yield substr(s, first, last-1)
  344. if splits == 0: break
  345. dec(splits)
  346. inc(last, sepLen)
  347. template oldSplit(s, seps, maxsplit) =
  348. var last = 0
  349. var splits = maxsplit
  350. assert(not ('\0' in seps))
  351. while last < len(s):
  352. while last < len(s) and s[last] in seps: inc(last)
  353. var first = last
  354. while last < len(s) and s[last] notin seps: inc(last)
  355. if first <= last-1:
  356. if splits == 0: last = len(s)
  357. yield substr(s, first, last-1)
  358. if splits == 0: break
  359. dec(splits)
  360. template accResult(iter: untyped) =
  361. result = @[]
  362. for x in iter: add(result, x)
  363. iterator split*(s: string, sep: char, maxsplit: int = -1): string =
  364. ## Splits the string `s` into substrings using a single separator.
  365. ##
  366. ## Substrings are separated by the character `sep`.
  367. ## The code:
  368. ##
  369. ## .. code-block:: nim
  370. ## for word in split(";;this;is;an;;example;;;", ';'):
  371. ## writeLine(stdout, word)
  372. ##
  373. ## Results in:
  374. ##
  375. ## .. code-block::
  376. ## ""
  377. ## ""
  378. ## "this"
  379. ## "is"
  380. ## "an"
  381. ## ""
  382. ## "example"
  383. ## ""
  384. ## ""
  385. ## ""
  386. ##
  387. ## See also:
  388. ## * `rsplit iterator<#rsplit.i,string,char,int>`_
  389. ## * `splitLines iterator<#splitLines.i,string>`_
  390. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  391. ## * `split func<#split,string,char,int>`_
  392. splitCommon(s, sep, maxsplit, 1)
  393. iterator split*(s: string, seps: set[char] = Whitespace,
  394. maxsplit: int = -1): string =
  395. ## Splits the string `s` into substrings using a group of separators.
  396. ##
  397. ## Substrings are separated by a substring containing only `seps`.
  398. ##
  399. ## .. code-block:: nim
  400. ## for word in split("this\lis an\texample"):
  401. ## writeLine(stdout, word)
  402. ##
  403. ## ...generates this output:
  404. ##
  405. ## .. code-block::
  406. ## "this"
  407. ## "is"
  408. ## "an"
  409. ## "example"
  410. ##
  411. ## And the following code:
  412. ##
  413. ## .. code-block:: nim
  414. ## for word in split("this:is;an$example", {';', ':', '$'}):
  415. ## writeLine(stdout, word)
  416. ##
  417. ## ...produces the same output as the first example. The code:
  418. ##
  419. ## .. code-block:: nim
  420. ## let date = "2012-11-20T22:08:08.398990"
  421. ## let separators = {' ', '-', ':', 'T'}
  422. ## for number in split(date, separators):
  423. ## writeLine(stdout, number)
  424. ##
  425. ## ...results in:
  426. ##
  427. ## .. code-block::
  428. ## "2012"
  429. ## "11"
  430. ## "20"
  431. ## "22"
  432. ## "08"
  433. ## "08.398990"
  434. ##
  435. ## See also:
  436. ## * `rsplit iterator<#rsplit.i,string,set[char],int>`_
  437. ## * `splitLines iterator<#splitLines.i,string>`_
  438. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  439. ## * `split func<#split,string,set[char],int>`_
  440. splitCommon(s, seps, maxsplit, 1)
  441. iterator split*(s: string, sep: string, maxsplit: int = -1): string =
  442. ## Splits the string `s` into substrings using a string separator.
  443. ##
  444. ## Substrings are separated by the string `sep`.
  445. ## The code:
  446. ##
  447. ## .. code-block:: nim
  448. ## for word in split("thisDATAisDATAcorrupted", "DATA"):
  449. ## writeLine(stdout, word)
  450. ##
  451. ## Results in:
  452. ##
  453. ## .. code-block::
  454. ## "this"
  455. ## "is"
  456. ## "corrupted"
  457. ##
  458. ## See also:
  459. ## * `rsplit iterator<#rsplit.i,string,string,int,bool>`_
  460. ## * `splitLines iterator<#splitLines.i,string>`_
  461. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  462. ## * `split func<#split,string,string,int>`_
  463. splitCommon(s, sep, maxsplit, sep.len)
  464. template rsplitCommon(s, sep, maxsplit, sepLen) =
  465. ## Common code for rsplit functions
  466. var
  467. last = s.len - 1
  468. first = last
  469. splits = maxsplit
  470. startPos = 0
  471. # go to -1 in order to get separators at the beginning
  472. while first >= -1:
  473. while first >= 0 and not stringHasSep(s, first, sep):
  474. dec(first)
  475. if splits == 0:
  476. # No more splits means set first to the beginning
  477. first = -1
  478. if first == -1:
  479. startPos = 0
  480. else:
  481. startPos = first + sepLen
  482. yield substr(s, startPos, last)
  483. if splits == 0: break
  484. dec(splits)
  485. dec(first)
  486. last = first
  487. iterator rsplit*(s: string, sep: char,
  488. maxsplit: int = -1): string =
  489. ## Splits the string `s` into substrings from the right using a
  490. ## string separator. Works exactly the same as `split iterator
  491. ## <#split.i,string,char,int>`_ except in reverse order.
  492. ##
  493. ## .. code-block:: nim
  494. ## for piece in "foo:bar".rsplit(':'):
  495. ## echo piece
  496. ##
  497. ## Results in:
  498. ##
  499. ## .. code-block:: nim
  500. ## "bar"
  501. ## "foo"
  502. ##
  503. ## Substrings are separated from the right by the char `sep`.
  504. ##
  505. ## See also:
  506. ## * `split iterator<#split.i,string,char,int>`_
  507. ## * `splitLines iterator<#splitLines.i,string>`_
  508. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  509. ## * `rsplit func<#rsplit,string,char,int>`_
  510. rsplitCommon(s, sep, maxsplit, 1)
  511. iterator rsplit*(s: string, seps: set[char] = Whitespace,
  512. maxsplit: int = -1): string =
  513. ## Splits the string `s` into substrings from the right using a
  514. ## string separator. Works exactly the same as `split iterator
  515. ## <#split.i,string,char,int>`_ except in reverse order.
  516. ##
  517. ## .. code-block:: nim
  518. ## for piece in "foo bar".rsplit(WhiteSpace):
  519. ## echo piece
  520. ##
  521. ## Results in:
  522. ##
  523. ## .. code-block:: nim
  524. ## "bar"
  525. ## "foo"
  526. ##
  527. ## Substrings are separated from the right by the set of chars `seps`
  528. ##
  529. ## See also:
  530. ## * `split iterator<#split.i,string,set[char],int>`_
  531. ## * `splitLines iterator<#splitLines.i,string>`_
  532. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  533. ## * `rsplit func<#rsplit,string,set[char],int>`_
  534. rsplitCommon(s, seps, maxsplit, 1)
  535. iterator rsplit*(s: string, sep: string, maxsplit: int = -1,
  536. keepSeparators: bool = false): string =
  537. ## Splits the string `s` into substrings from the right using a
  538. ## string separator. Works exactly the same as `split iterator
  539. ## <#split.i,string,string,int>`_ except in reverse order.
  540. ##
  541. ## .. code-block:: nim
  542. ## for piece in "foothebar".rsplit("the"):
  543. ## echo piece
  544. ##
  545. ## Results in:
  546. ##
  547. ## .. code-block:: nim
  548. ## "bar"
  549. ## "foo"
  550. ##
  551. ## Substrings are separated from the right by the string `sep`
  552. ##
  553. ## See also:
  554. ## * `split iterator<#split.i,string,string,int>`_
  555. ## * `splitLines iterator<#splitLines.i,string>`_
  556. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  557. ## * `rsplit func<#rsplit,string,string,int>`_
  558. rsplitCommon(s, sep, maxsplit, sep.len)
  559. iterator splitLines*(s: string, keepEol = false): string =
  560. ## Splits the string `s` into its containing lines.
  561. ##
  562. ## Every `character literal <manual.html#lexical-analysis-character-literals>`_
  563. ## newline combination (CR, LF, CR-LF) is supported. The result strings
  564. ## contain no trailing end of line characters unless the parameter `keepEol`
  565. ## is set to `true`.
  566. ##
  567. ## Example:
  568. ##
  569. ## .. code-block:: nim
  570. ## for line in splitLines("\nthis\nis\nan\n\nexample\n"):
  571. ## writeLine(stdout, line)
  572. ##
  573. ## Results in:
  574. ##
  575. ## .. code-block:: nim
  576. ## ""
  577. ## "this"
  578. ## "is"
  579. ## "an"
  580. ## ""
  581. ## "example"
  582. ## ""
  583. ##
  584. ## See also:
  585. ## * `splitWhitespace iterator<#splitWhitespace.i,string,int>`_
  586. ## * `splitLines func<#splitLines,string>`_
  587. var first = 0
  588. var last = 0
  589. var eolpos = 0
  590. while true:
  591. while last < s.len and s[last] notin {'\c', '\l'}: inc(last)
  592. eolpos = last
  593. if last < s.len:
  594. if s[last] == '\l': inc(last)
  595. elif s[last] == '\c':
  596. inc(last)
  597. if last < s.len and s[last] == '\l': inc(last)
  598. yield substr(s, first, if keepEol: last-1 else: eolpos-1)
  599. # no eol characters consumed means that the string is over
  600. if eolpos == last:
  601. break
  602. first = last
  603. iterator splitWhitespace*(s: string, maxsplit: int = -1): string =
  604. ## Splits the string `s` at whitespace stripping leading and trailing
  605. ## whitespace if necessary. If `maxsplit` is specified and is positive,
  606. ## no more than `maxsplit` splits is made.
  607. ##
  608. ## The following code:
  609. ##
  610. ## .. code-block:: nim
  611. ## let s = " foo \t bar baz "
  612. ## for ms in [-1, 1, 2, 3]:
  613. ## echo "------ maxsplit = ", ms, ":"
  614. ## for item in s.splitWhitespace(maxsplit=ms):
  615. ## echo '"', item, '"'
  616. ##
  617. ## ...results in:
  618. ##
  619. ## .. code-block::
  620. ## ------ maxsplit = -1:
  621. ## "foo"
  622. ## "bar"
  623. ## "baz"
  624. ## ------ maxsplit = 1:
  625. ## "foo"
  626. ## "bar baz "
  627. ## ------ maxsplit = 2:
  628. ## "foo"
  629. ## "bar"
  630. ## "baz "
  631. ## ------ maxsplit = 3:
  632. ## "foo"
  633. ## "bar"
  634. ## "baz"
  635. ##
  636. ## See also:
  637. ## * `splitLines iterator<#splitLines.i,string>`_
  638. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  639. oldSplit(s, Whitespace, maxsplit)
  640. func split*(s: string, sep: char, maxsplit: int = -1): seq[string] {.rtl,
  641. extern: "nsuSplitChar".} =
  642. ## The same as the `split iterator <#split.i,string,char,int>`_ (see its
  643. ## documentation), but is a func that returns a sequence of substrings.
  644. ##
  645. ## See also:
  646. ## * `split iterator <#split.i,string,char,int>`_
  647. ## * `rsplit func<#rsplit,string,char,int>`_
  648. ## * `splitLines func<#splitLines,string>`_
  649. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  650. runnableExamples:
  651. doAssert "a,b,c".split(',') == @["a", "b", "c"]
  652. doAssert "".split(' ') == @[""]
  653. accResult(split(s, sep, maxsplit))
  654. func split*(s: string, seps: set[char] = Whitespace, maxsplit: int = -1): seq[
  655. string] {.rtl, extern: "nsuSplitCharSet".} =
  656. ## The same as the `split iterator <#split.i,string,set[char],int>`_ (see its
  657. ## documentation), but is a func that returns a sequence of substrings.
  658. ##
  659. ## See also:
  660. ## * `split iterator <#split.i,string,set[char],int>`_
  661. ## * `rsplit func<#rsplit,string,set[char],int>`_
  662. ## * `splitLines func<#splitLines,string>`_
  663. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  664. runnableExamples:
  665. doAssert "a,b;c".split({',', ';'}) == @["a", "b", "c"]
  666. doAssert "".split({' '}) == @[""]
  667. accResult(split(s, seps, maxsplit))
  668. func split*(s: string, sep: string, maxsplit: int = -1): seq[string] {.rtl,
  669. extern: "nsuSplitString".} =
  670. ## Splits the string `s` into substrings using a string separator.
  671. ##
  672. ## Substrings are separated by the string `sep`. This is a wrapper around the
  673. ## `split iterator <#split.i,string,string,int>`_.
  674. ##
  675. ## See also:
  676. ## * `split iterator <#split.i,string,string,int>`_
  677. ## * `rsplit func<#rsplit,string,string,int>`_
  678. ## * `splitLines func<#splitLines,string>`_
  679. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  680. runnableExamples:
  681. doAssert "a,b,c".split(",") == @["a", "b", "c"]
  682. doAssert "a man a plan a canal panama".split("a ") == @["", "man ", "plan ", "canal panama"]
  683. doAssert "".split("Elon Musk") == @[""]
  684. doAssert "a largely spaced sentence".split(" ") == @["a", "", "largely",
  685. "", "", "", "spaced", "sentence"]
  686. doAssert "a largely spaced sentence".split(" ", maxsplit = 1) == @["a", " largely spaced sentence"]
  687. doAssert(sep.len > 0)
  688. accResult(split(s, sep, maxsplit))
  689. func rsplit*(s: string, sep: char, maxsplit: int = -1): seq[string] {.rtl,
  690. extern: "nsuRSplitChar".} =
  691. ## The same as the `rsplit iterator <#rsplit.i,string,char,int>`_, but is a func
  692. ## that returns a sequence of substrings.
  693. ##
  694. ## A possible common use case for `rsplit` is path manipulation,
  695. ## particularly on systems that don't use a common delimiter.
  696. ##
  697. ## For example, if a system had `#` as a delimiter, you could
  698. ## do the following to get the tail of the path:
  699. ##
  700. ## .. code-block:: nim
  701. ## var tailSplit = rsplit("Root#Object#Method#Index", '#', maxsplit=1)
  702. ##
  703. ## Results in `tailSplit` containing:
  704. ##
  705. ## .. code-block:: nim
  706. ## @["Root#Object#Method", "Index"]
  707. ##
  708. ## See also:
  709. ## * `rsplit iterator <#rsplit.i,string,char,int>`_
  710. ## * `split func<#split,string,char,int>`_
  711. ## * `splitLines func<#splitLines,string>`_
  712. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  713. accResult(rsplit(s, sep, maxsplit))
  714. result.reverse()
  715. func rsplit*(s: string, seps: set[char] = Whitespace,
  716. maxsplit: int = -1): seq[string]
  717. {.rtl, extern: "nsuRSplitCharSet".} =
  718. ## The same as the `rsplit iterator <#rsplit.i,string,set[char],int>`_, but is a
  719. ## func that returns a sequence of substrings.
  720. ##
  721. ## A possible common use case for `rsplit` is path manipulation,
  722. ## particularly on systems that don't use a common delimiter.
  723. ##
  724. ## For example, if a system had `#` as a delimiter, you could
  725. ## do the following to get the tail of the path:
  726. ##
  727. ## .. code-block:: nim
  728. ## var tailSplit = rsplit("Root#Object#Method#Index", {'#'}, maxsplit=1)
  729. ##
  730. ## Results in `tailSplit` containing:
  731. ##
  732. ## .. code-block:: nim
  733. ## @["Root#Object#Method", "Index"]
  734. ##
  735. ## See also:
  736. ## * `rsplit iterator <#rsplit.i,string,set[char],int>`_
  737. ## * `split func<#split,string,set[char],int>`_
  738. ## * `splitLines func<#splitLines,string>`_
  739. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  740. accResult(rsplit(s, seps, maxsplit))
  741. result.reverse()
  742. func rsplit*(s: string, sep: string, maxsplit: int = -1): seq[string] {.rtl,
  743. extern: "nsuRSplitString".} =
  744. ## The same as the `rsplit iterator <#rsplit.i,string,string,int,bool>`_, but is a func
  745. ## that returns a sequence of substrings.
  746. ##
  747. ## A possible common use case for `rsplit` is path manipulation,
  748. ## particularly on systems that don't use a common delimiter.
  749. ##
  750. ## For example, if a system had `#` as a delimiter, you could
  751. ## do the following to get the tail of the path:
  752. ##
  753. ## .. code-block:: nim
  754. ## var tailSplit = rsplit("Root#Object#Method#Index", "#", maxsplit=1)
  755. ##
  756. ## Results in `tailSplit` containing:
  757. ##
  758. ## .. code-block:: nim
  759. ## @["Root#Object#Method", "Index"]
  760. ##
  761. ## See also:
  762. ## * `rsplit iterator <#rsplit.i,string,string,int,bool>`_
  763. ## * `split func<#split,string,string,int>`_
  764. ## * `splitLines func<#splitLines,string>`_
  765. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  766. runnableExamples:
  767. doAssert "a largely spaced sentence".rsplit(" ", maxsplit = 1) == @[
  768. "a largely spaced", "sentence"]
  769. doAssert "a,b,c".rsplit(",") == @["a", "b", "c"]
  770. doAssert "a man a plan a canal panama".rsplit("a ") == @["", "man ",
  771. "plan ", "canal panama"]
  772. doAssert "".rsplit("Elon Musk") == @[""]
  773. doAssert "a largely spaced sentence".rsplit(" ") == @["a", "",
  774. "largely", "", "", "", "spaced", "sentence"]
  775. accResult(rsplit(s, sep, maxsplit))
  776. result.reverse()
  777. func splitLines*(s: string, keepEol = false): seq[string] {.rtl,
  778. extern: "nsuSplitLines".} =
  779. ## The same as the `splitLines iterator<#splitLines.i,string>`_ (see its
  780. ## documentation), but is a func that returns a sequence of substrings.
  781. ##
  782. ## See also:
  783. ## * `splitLines iterator<#splitLines.i,string>`_
  784. ## * `splitWhitespace func<#splitWhitespace,string,int>`_
  785. ## * `countLines func<#countLines,string>`_
  786. accResult(splitLines(s, keepEol = keepEol))
  787. func splitWhitespace*(s: string, maxsplit: int = -1): seq[string] {.rtl,
  788. extern: "nsuSplitWhitespace".} =
  789. ## The same as the `splitWhitespace iterator <#splitWhitespace.i,string,int>`_
  790. ## (see its documentation), but is a func that returns a sequence of substrings.
  791. ##
  792. ## See also:
  793. ## * `splitWhitespace iterator <#splitWhitespace.i,string,int>`_
  794. ## * `splitLines func<#splitLines,string>`_
  795. accResult(splitWhitespace(s, maxsplit))
  796. func toBin*(x: BiggestInt, len: Positive): string {.rtl, extern: "nsuToBin".} =
  797. ## Converts `x` into its binary representation.
  798. ##
  799. ## The resulting string is always `len` characters long. No leading `0b`
  800. ## prefix is generated.
  801. runnableExamples:
  802. let
  803. a = 29
  804. b = 257
  805. doAssert a.toBin(8) == "00011101"
  806. doAssert b.toBin(8) == "00000001"
  807. doAssert b.toBin(9) == "100000001"
  808. var
  809. mask = BiggestUInt 1
  810. shift = BiggestUInt 0
  811. assert(len > 0)
  812. result = newString(len)
  813. for j in countdown(len-1, 0):
  814. result[j] = chr(int((BiggestUInt(x) and mask) shr shift) + ord('0'))
  815. inc shift
  816. mask = mask shl BiggestUInt(1)
  817. func toOct*(x: BiggestInt, len: Positive): string {.rtl, extern: "nsuToOct".} =
  818. ## Converts `x` into its octal representation.
  819. ##
  820. ## The resulting string is always `len` characters long. No leading `0o`
  821. ## prefix is generated.
  822. ##
  823. ## Do not confuse it with `toOctal func<#toOctal,char>`_.
  824. runnableExamples:
  825. let
  826. a = 62
  827. b = 513
  828. doAssert a.toOct(3) == "076"
  829. doAssert b.toOct(3) == "001"
  830. doAssert b.toOct(5) == "01001"
  831. var
  832. mask = BiggestUInt 7
  833. shift = BiggestUInt 0
  834. assert(len > 0)
  835. result = newString(len)
  836. for j in countdown(len-1, 0):
  837. result[j] = chr(int((BiggestUInt(x) and mask) shr shift) + ord('0'))
  838. inc shift, 3
  839. mask = mask shl BiggestUInt(3)
  840. func toHexImpl(x: BiggestUInt, len: Positive, handleNegative: bool): string =
  841. const
  842. HexChars = "0123456789ABCDEF"
  843. var n = x
  844. result = newString(len)
  845. for j in countdown(len-1, 0):
  846. result[j] = HexChars[int(n and 0xF)]
  847. n = n shr 4
  848. # handle negative overflow
  849. if n == 0 and handleNegative: n = not(BiggestUInt 0)
  850. func toHex*[T: SomeInteger](x: T, len: Positive): string =
  851. ## Converts `x` to its hexadecimal representation.
  852. ##
  853. ## The resulting string will be exactly `len` characters long. No prefix like
  854. ## `0x` is generated. `x` is treated as an unsigned value.
  855. runnableExamples:
  856. let
  857. a = 62'u64
  858. b = 4097'u64
  859. doAssert a.toHex(3) == "03E"
  860. doAssert b.toHex(3) == "001"
  861. doAssert b.toHex(4) == "1001"
  862. doAssert toHex(62, 3) == "03E"
  863. doAssert toHex(-8, 6) == "FFFFF8"
  864. whenJsNoBigInt64:
  865. toHexImpl(cast[BiggestUInt](x), len, x < 0)
  866. do:
  867. when T is SomeSignedInt:
  868. toHexImpl(cast[BiggestUInt](BiggestInt(x)), len, x < 0)
  869. else:
  870. toHexImpl(BiggestUInt(x), len, x < 0)
  871. func toHex*[T: SomeInteger](x: T): string =
  872. ## Shortcut for `toHex(x, T.sizeof * 2)`
  873. runnableExamples:
  874. doAssert toHex(1984'i64) == "00000000000007C0"
  875. doAssert toHex(1984'i16) == "07C0"
  876. whenJsNoBigInt64:
  877. toHexImpl(cast[BiggestUInt](x), 2*sizeof(T), x < 0)
  878. do:
  879. when T is SomeSignedInt:
  880. toHexImpl(cast[BiggestUInt](BiggestInt(x)), 2*sizeof(T), x < 0)
  881. else:
  882. toHexImpl(BiggestUInt(x), 2*sizeof(T), x < 0)
  883. func toHex*(s: string): string {.rtl.} =
  884. ## Converts a bytes string to its hexadecimal representation.
  885. ##
  886. ## The output is twice the input long. No prefix like
  887. ## `0x` is generated.
  888. ##
  889. ## See also:
  890. ## * `parseHexStr func<#parseHexStr,string>`_ for the reverse operation
  891. runnableExamples:
  892. let
  893. a = "1"
  894. b = "A"
  895. c = "\0\255"
  896. doAssert a.toHex() == "31"
  897. doAssert b.toHex() == "41"
  898. doAssert c.toHex() == "00FF"
  899. const HexChars = "0123456789ABCDEF"
  900. result = newString(s.len * 2)
  901. for pos, c in s:
  902. var n = ord(c)
  903. result[pos * 2 + 1] = HexChars[n and 0xF]
  904. n = n shr 4
  905. result[pos * 2] = HexChars[n]
  906. func toOctal*(c: char): string {.rtl, extern: "nsuToOctal".} =
  907. ## Converts a character `c` to its octal representation.
  908. ##
  909. ## The resulting string may not have a leading zero. Its length is always
  910. ## exactly 3.
  911. ##
  912. ## Do not confuse it with `toOct func<#toOct,BiggestInt,Positive>`_.
  913. runnableExamples:
  914. doAssert toOctal('1') == "061"
  915. doAssert toOctal('A') == "101"
  916. doAssert toOctal('a') == "141"
  917. doAssert toOctal('!') == "041"
  918. result = newString(3)
  919. var val = ord(c)
  920. for i in countdown(2, 0):
  921. result[i] = chr(val mod 8 + ord('0'))
  922. val = val div 8
  923. func fromBin*[T: SomeInteger](s: string): T =
  924. ## Parses a binary integer value from a string `s`.
  925. ##
  926. ## If `s` is not a valid binary integer, `ValueError` is raised. `s` can have
  927. ## one of the following optional prefixes: `0b`, `0B`. Underscores within
  928. ## `s` are ignored.
  929. ##
  930. ## Does not check for overflow. If the value represented by `s`
  931. ## is too big to fit into a return type, only the value of the rightmost
  932. ## binary digits of `s` is returned without producing an error.
  933. runnableExamples:
  934. let s = "0b_0100_1000_1000_1000_1110_1110_1001_1001"
  935. doAssert fromBin[int](s) == 1216933529
  936. doAssert fromBin[int8](s) == 0b1001_1001'i8
  937. doAssert fromBin[int8](s) == -103'i8
  938. doAssert fromBin[uint8](s) == 153
  939. doAssert s.fromBin[:int16] == 0b1110_1110_1001_1001'i16
  940. doAssert s.fromBin[:uint64] == 1216933529'u64
  941. let p = parseutils.parseBin(s, result)
  942. if p != s.len or p == 0:
  943. raise newException(ValueError, "invalid binary integer: " & s)
  944. func fromOct*[T: SomeInteger](s: string): T =
  945. ## Parses an octal integer value from a string `s`.
  946. ##
  947. ## If `s` is not a valid octal integer, `ValueError` is raised. `s` can have
  948. ## one of the following optional prefixes: `0o`, `0O`. Underscores within
  949. ## `s` are ignored.
  950. ##
  951. ## Does not check for overflow. If the value represented by `s`
  952. ## is too big to fit into a return type, only the value of the rightmost
  953. ## octal digits of `s` is returned without producing an error.
  954. runnableExamples:
  955. let s = "0o_123_456_777"
  956. doAssert fromOct[int](s) == 21913087
  957. doAssert fromOct[int8](s) == 0o377'i8
  958. doAssert fromOct[int8](s) == -1'i8
  959. doAssert fromOct[uint8](s) == 255'u8
  960. doAssert s.fromOct[:int16] == 24063'i16
  961. doAssert s.fromOct[:uint64] == 21913087'u64
  962. let p = parseutils.parseOct(s, result)
  963. if p != s.len or p == 0:
  964. raise newException(ValueError, "invalid oct integer: " & s)
  965. func fromHex*[T: SomeInteger](s: string): T =
  966. ## Parses a hex integer value from a string `s`.
  967. ##
  968. ## If `s` is not a valid hex integer, `ValueError` is raised. `s` can have
  969. ## one of the following optional prefixes: `0x`, `0X`, `#`. Underscores within
  970. ## `s` are ignored.
  971. ##
  972. ## Does not check for overflow. If the value represented by `s`
  973. ## is too big to fit into a return type, only the value of the rightmost
  974. ## hex digits of `s` is returned without producing an error.
  975. runnableExamples:
  976. let s = "0x_1235_8df6"
  977. doAssert fromHex[int](s) == 305499638
  978. doAssert fromHex[int8](s) == 0xf6'i8
  979. doAssert fromHex[int8](s) == -10'i8
  980. doAssert fromHex[uint8](s) == 246'u8
  981. doAssert s.fromHex[:int16] == -29194'i16
  982. doAssert s.fromHex[:uint64] == 305499638'u64
  983. let p = parseutils.parseHex(s, result)
  984. if p != s.len or p == 0:
  985. raise newException(ValueError, "invalid hex integer: " & s)
  986. func intToStr*(x: int, minchars: Positive = 1): string {.rtl,
  987. extern: "nsuIntToStr".} =
  988. ## Converts `x` to its decimal representation.
  989. ##
  990. ## The resulting string will be minimally `minchars` characters long. This is
  991. ## achieved by adding leading zeros.
  992. runnableExamples:
  993. doAssert intToStr(1984) == "1984"
  994. doAssert intToStr(1984, 6) == "001984"
  995. result = $abs(x)
  996. for i in 1 .. minchars - len(result):
  997. result = '0' & result
  998. if x < 0:
  999. result = '-' & result
  1000. func parseInt*(s: string): int {.rtl, extern: "nsuParseInt".} =
  1001. ## Parses a decimal integer value contained in `s`.
  1002. ##
  1003. ## If `s` is not a valid integer, `ValueError` is raised.
  1004. runnableExamples:
  1005. doAssert parseInt("-0042") == -42
  1006. result = 0
  1007. let L = parseutils.parseInt(s, result, 0)
  1008. if L != s.len or L == 0:
  1009. raise newException(ValueError, "invalid integer: " & s)
  1010. func parseBiggestInt*(s: string): BiggestInt {.rtl,
  1011. extern: "nsuParseBiggestInt".} =
  1012. ## Parses a decimal integer value contained in `s`.
  1013. ##
  1014. ## If `s` is not a valid integer, `ValueError` is raised.
  1015. result = BiggestInt(0)
  1016. let L = parseutils.parseBiggestInt(s, result, 0)
  1017. if L != s.len or L == 0:
  1018. raise newException(ValueError, "invalid integer: " & s)
  1019. func parseUInt*(s: string): uint {.rtl, extern: "nsuParseUInt".} =
  1020. ## Parses a decimal unsigned integer value contained in `s`.
  1021. ##
  1022. ## If `s` is not a valid integer, `ValueError` is raised.
  1023. result = uint(0)
  1024. let L = parseutils.parseUInt(s, result, 0)
  1025. if L != s.len or L == 0:
  1026. raise newException(ValueError, "invalid unsigned integer: " & s)
  1027. func parseBiggestUInt*(s: string): BiggestUInt {.rtl,
  1028. extern: "nsuParseBiggestUInt".} =
  1029. ## Parses a decimal unsigned integer value contained in `s`.
  1030. ##
  1031. ## If `s` is not a valid integer, `ValueError` is raised.
  1032. result = BiggestUInt(0)
  1033. let L = parseutils.parseBiggestUInt(s, result, 0)
  1034. if L != s.len or L == 0:
  1035. raise newException(ValueError, "invalid unsigned integer: " & s)
  1036. func parseFloat*(s: string): float {.rtl, extern: "nsuParseFloat".} =
  1037. ## Parses a decimal floating point value contained in `s`.
  1038. ##
  1039. ## If `s` is not a valid floating point number, `ValueError` is raised.
  1040. ##`NAN`, `INF`, `-INF` are also supported (case insensitive comparison).
  1041. runnableExamples:
  1042. doAssert parseFloat("3.14") == 3.14
  1043. doAssert parseFloat("inf") == 1.0/0
  1044. result = 0.0
  1045. let L = parseutils.parseFloat(s, result, 0)
  1046. if L != s.len or L == 0:
  1047. raise newException(ValueError, "invalid float: " & s)
  1048. func parseBinInt*(s: string): int {.rtl, extern: "nsuParseBinInt".} =
  1049. ## Parses a binary integer value contained in `s`.
  1050. ##
  1051. ## If `s` is not a valid binary integer, `ValueError` is raised. `s` can have
  1052. ## one of the following optional prefixes: `0b`, `0B`. Underscores within
  1053. ## `s` are ignored.
  1054. runnableExamples:
  1055. let
  1056. a = "0b11_0101"
  1057. b = "111"
  1058. doAssert a.parseBinInt() == 53
  1059. doAssert b.parseBinInt() == 7
  1060. result = 0
  1061. let L = parseutils.parseBin(s, result, 0)
  1062. if L != s.len or L == 0:
  1063. raise newException(ValueError, "invalid binary integer: " & s)
  1064. func parseOctInt*(s: string): int {.rtl, extern: "nsuParseOctInt".} =
  1065. ## Parses an octal integer value contained in `s`.
  1066. ##
  1067. ## If `s` is not a valid oct integer, `ValueError` is raised. `s` can have one
  1068. ## of the following optional prefixes: `0o`, `0O`. Underscores within
  1069. ## `s` are ignored.
  1070. result = 0
  1071. let L = parseutils.parseOct(s, result, 0)
  1072. if L != s.len or L == 0:
  1073. raise newException(ValueError, "invalid oct integer: " & s)
  1074. func parseHexInt*(s: string): int {.rtl, extern: "nsuParseHexInt".} =
  1075. ## Parses a hexadecimal integer value contained in `s`.
  1076. ##
  1077. ## If `s` is not a valid hex integer, `ValueError` is raised. `s` can have one
  1078. ## of the following optional prefixes: `0x`, `0X`, `#`. Underscores
  1079. ## within `s` are ignored.
  1080. result = 0
  1081. let L = parseutils.parseHex(s, result, 0)
  1082. if L != s.len or L == 0:
  1083. raise newException(ValueError, "invalid hex integer: " & s)
  1084. func generateHexCharToValueMap(): string =
  1085. ## Generates a string to map a hex digit to uint value.
  1086. result = ""
  1087. for inp in 0..255:
  1088. let ch = chr(inp)
  1089. let o =
  1090. case ch
  1091. of '0'..'9': inp - ord('0')
  1092. of 'a'..'f': inp - ord('a') + 10
  1093. of 'A'..'F': inp - ord('A') + 10
  1094. else: 17 # indicates an invalid hex char
  1095. result.add chr(o)
  1096. const hexCharToValueMap = generateHexCharToValueMap()
  1097. func parseHexStr*(s: string): string {.rtl, extern: "nsuParseHexStr".} =
  1098. ## Converts hex-encoded string to byte string, e.g.:
  1099. ##
  1100. ## Raises `ValueError` for an invalid hex values. The comparison is
  1101. ## case-insensitive.
  1102. ##
  1103. ## See also:
  1104. ## * `toHex func<#toHex,string>`_ for the reverse operation
  1105. runnableExamples:
  1106. let
  1107. a = "41"
  1108. b = "3161"
  1109. c = "00ff"
  1110. doAssert parseHexStr(a) == "A"
  1111. doAssert parseHexStr(b) == "1a"
  1112. doAssert parseHexStr(c) == "\0\255"
  1113. if s.len mod 2 != 0:
  1114. raise newException(ValueError, "Incorrect hex string len")
  1115. result = newString(s.len div 2)
  1116. var buf = 0
  1117. for pos, c in s:
  1118. let val = hexCharToValueMap[ord(c)].ord
  1119. if val == 17:
  1120. raise newException(ValueError, "Invalid hex char `" &
  1121. c & "` (ord " & $c.ord & ")")
  1122. if pos mod 2 == 0:
  1123. buf = val
  1124. else:
  1125. result[pos div 2] = chr(val + buf shl 4)
  1126. func parseBool*(s: string): bool =
  1127. ## Parses a value into a `bool`.
  1128. ##
  1129. ## If `s` is one of the following values: `y, yes, true, 1, on`, then
  1130. ## returns `true`. If `s` is one of the following values: `n, no, false,
  1131. ## 0, off`, then returns `false`. If `s` is something else a
  1132. ## `ValueError` exception is raised.
  1133. runnableExamples:
  1134. let a = "n"
  1135. doAssert parseBool(a) == false
  1136. case normalize(s)
  1137. of "y", "yes", "true", "1", "on": result = true
  1138. of "n", "no", "false", "0", "off": result = false
  1139. else: raise newException(ValueError, "cannot interpret as a bool: " & s)
  1140. func parseEnum*[T: enum](s: string): T =
  1141. ## Parses an enum `T`. This errors at compile time, if the given enum
  1142. ## type contains multiple fields with the same string value.
  1143. ##
  1144. ## Raises `ValueError` for an invalid value in `s`. The comparison is
  1145. ## done in a style insensitive way.
  1146. runnableExamples:
  1147. type
  1148. MyEnum = enum
  1149. first = "1st",
  1150. second,
  1151. third = "3rd"
  1152. doAssert parseEnum[MyEnum]("1_st") == first
  1153. doAssert parseEnum[MyEnum]("second") == second
  1154. doAssertRaises(ValueError):
  1155. echo parseEnum[MyEnum]("third")
  1156. genEnumCaseStmt(T, s, default = nil, ord(low(T)), ord(high(T)), nimIdentNormalize)
  1157. func parseEnum*[T: enum](s: string, default: T): T =
  1158. ## Parses an enum `T`. This errors at compile time, if the given enum
  1159. ## type contains multiple fields with the same string value.
  1160. ##
  1161. ## Uses `default` for an invalid value in `s`. The comparison is done in a
  1162. ## style insensitive way.
  1163. runnableExamples:
  1164. type
  1165. MyEnum = enum
  1166. first = "1st",
  1167. second,
  1168. third = "3rd"
  1169. doAssert parseEnum[MyEnum]("1_st") == first
  1170. doAssert parseEnum[MyEnum]("second") == second
  1171. doAssert parseEnum[MyEnum]("last", third) == third
  1172. genEnumCaseStmt(T, s, default, ord(low(T)), ord(high(T)), nimIdentNormalize)
  1173. func repeat*(c: char, count: Natural): string {.rtl, extern: "nsuRepeatChar".} =
  1174. ## Returns a string of length `count` consisting only of
  1175. ## the character `c`.
  1176. runnableExamples:
  1177. let a = 'z'
  1178. doAssert a.repeat(5) == "zzzzz"
  1179. result = newString(count)
  1180. for i in 0..count-1: result[i] = c
  1181. func repeat*(s: string, n: Natural): string {.rtl, extern: "nsuRepeatStr".} =
  1182. ## Returns string `s` concatenated `n` times.
  1183. runnableExamples:
  1184. doAssert "+ foo +".repeat(3) == "+ foo ++ foo ++ foo +"
  1185. result = newStringOfCap(n * s.len)
  1186. for i in 1..n: result.add(s)
  1187. func spaces*(n: Natural): string {.inline.} =
  1188. ## Returns a string with `n` space characters. You can use this func
  1189. ## to left align strings.
  1190. ##
  1191. ## See also:
  1192. ## * `align func<#align,string,Natural,char>`_
  1193. ## * `alignLeft func<#alignLeft,string,Natural,char>`_
  1194. ## * `indent func<#indent,string,Natural,string>`_
  1195. ## * `center func<#center,string,int,char>`_
  1196. runnableExamples:
  1197. let
  1198. width = 15
  1199. text1 = "Hello user!"
  1200. text2 = "This is a very long string"
  1201. doAssert text1 & spaces(max(0, width - text1.len)) & "|" ==
  1202. "Hello user! |"
  1203. doAssert text2 & spaces(max(0, width - text2.len)) & "|" ==
  1204. "This is a very long string|"
  1205. repeat(' ', n)
  1206. func align*(s: string, count: Natural, padding = ' '): string {.rtl,
  1207. extern: "nsuAlignString".} =
  1208. ## Aligns a string `s` with `padding`, so that it is of length `count`.
  1209. ##
  1210. ## `padding` characters (by default spaces) are added before `s` resulting in
  1211. ## right alignment. If `s.len >= count`, no spaces are added and `s` is
  1212. ## returned unchanged. If you need to left align a string use the `alignLeft
  1213. ## func<#alignLeft,string,Natural,char>`_.
  1214. ##
  1215. ## See also:
  1216. ## * `alignLeft func<#alignLeft,string,Natural,char>`_
  1217. ## * `spaces func<#spaces,Natural>`_
  1218. ## * `indent func<#indent,string,Natural,string>`_
  1219. ## * `center func<#center,string,int,char>`_
  1220. runnableExamples:
  1221. assert align("abc", 4) == " abc"
  1222. assert align("a", 0) == "a"
  1223. assert align("1232", 6) == " 1232"
  1224. assert align("1232", 6, '#') == "##1232"
  1225. if s.len < count:
  1226. result = newString(count)
  1227. let spaces = count - s.len
  1228. for i in 0..spaces-1: result[i] = padding
  1229. for i in spaces..count-1: result[i] = s[i-spaces]
  1230. else:
  1231. result = s
  1232. func alignLeft*(s: string, count: Natural, padding = ' '): string =
  1233. ## Left-Aligns a string `s` with `padding`, so that it is of length `count`.
  1234. ##
  1235. ## `padding` characters (by default spaces) are added after `s` resulting in
  1236. ## left alignment. If `s.len >= count`, no spaces are added and `s` is
  1237. ## returned unchanged. If you need to right align a string use the `align
  1238. ## func<#align,string,Natural,char>`_.
  1239. ##
  1240. ## See also:
  1241. ## * `align func<#align,string,Natural,char>`_
  1242. ## * `spaces func<#spaces,Natural>`_
  1243. ## * `indent func<#indent,string,Natural,string>`_
  1244. ## * `center func<#center,string,int,char>`_
  1245. runnableExamples:
  1246. assert alignLeft("abc", 4) == "abc "
  1247. assert alignLeft("a", 0) == "a"
  1248. assert alignLeft("1232", 6) == "1232 "
  1249. assert alignLeft("1232", 6, '#') == "1232##"
  1250. if s.len < count:
  1251. result = newString(count)
  1252. if s.len > 0:
  1253. result[0 .. (s.len - 1)] = s
  1254. for i in s.len ..< count:
  1255. result[i] = padding
  1256. else:
  1257. result = s
  1258. func center*(s: string, width: int, fillChar: char = ' '): string {.rtl,
  1259. extern: "nsuCenterString".} =
  1260. ## Return the contents of `s` centered in a string `width` long using
  1261. ## `fillChar` (default: space) as padding.
  1262. ##
  1263. ## The original string is returned if `width` is less than or equal
  1264. ## to `s.len`.
  1265. ##
  1266. ## See also:
  1267. ## * `align func<#align,string,Natural,char>`_
  1268. ## * `alignLeft func<#alignLeft,string,Natural,char>`_
  1269. ## * `spaces func<#spaces,Natural>`_
  1270. ## * `indent func<#indent,string,Natural,string>`_
  1271. runnableExamples:
  1272. let a = "foo"
  1273. doAssert a.center(2) == "foo"
  1274. doAssert a.center(5) == " foo "
  1275. doAssert a.center(6) == " foo "
  1276. if width <= s.len: return s
  1277. result = newString(width)
  1278. # Left padding will be one fillChar
  1279. # smaller if there are an odd number
  1280. # of characters
  1281. let
  1282. charsLeft = (width - s.len)
  1283. leftPadding = charsLeft div 2
  1284. for i in 0 ..< width:
  1285. if i >= leftPadding and i < leftPadding + s.len:
  1286. # we are where the string should be located
  1287. result[i] = s[i-leftPadding]
  1288. else:
  1289. # we are either before or after where
  1290. # the string s should go
  1291. result[i] = fillChar
  1292. func indent*(s: string, count: Natural, padding: string = " "): string {.rtl,
  1293. extern: "nsuIndent".} =
  1294. ## Indents each line in `s` by `count` amount of `padding`.
  1295. ##
  1296. ## **Note:** This does not preserve the new line characters used in `s`.
  1297. ##
  1298. ## See also:
  1299. ## * `align func<#align,string,Natural,char>`_
  1300. ## * `alignLeft func<#alignLeft,string,Natural,char>`_
  1301. ## * `spaces func<#spaces,Natural>`_
  1302. ## * `unindent func<#unindent,string,Natural,string>`_
  1303. ## * `dedent func<#dedent,string,Natural>`_
  1304. runnableExamples:
  1305. doAssert indent("First line\c\l and second line.", 2) ==
  1306. " First line\l and second line."
  1307. result = ""
  1308. var i = 0
  1309. for line in s.splitLines():
  1310. if i != 0:
  1311. result.add("\n")
  1312. for j in 1..count:
  1313. result.add(padding)
  1314. result.add(line)
  1315. i.inc
  1316. func unindent*(s: string, count: Natural = int.high,
  1317. padding: string = " "): string {.rtl, extern: "nsuUnindent".} =
  1318. ## Unindents each line in `s` by `count` amount of `padding`.
  1319. ##
  1320. ## **Note:** This does not preserve the new line characters used in `s`.
  1321. ##
  1322. ## See also:
  1323. ## * `dedent func<#dedent,string,Natural>`_
  1324. ## * `align func<#align,string,Natural,char>`_
  1325. ## * `alignLeft func<#alignLeft,string,Natural,char>`_
  1326. ## * `spaces func<#spaces,Natural>`_
  1327. ## * `indent func<#indent,string,Natural,string>`_
  1328. runnableExamples:
  1329. let x = """
  1330. Hello
  1331. There
  1332. """.unindent()
  1333. doAssert x == "Hello\nThere\n"
  1334. result = ""
  1335. var i = 0
  1336. for line in s.splitLines():
  1337. if i != 0:
  1338. result.add("\n")
  1339. var indentCount = 0
  1340. for j in 0..<count.int:
  1341. indentCount.inc
  1342. if j + padding.len-1 >= line.len or line[j .. j + padding.len-1] != padding:
  1343. indentCount = j
  1344. break
  1345. result.add(line[indentCount*padding.len .. ^1])
  1346. i.inc
  1347. func indentation*(s: string): Natural {.since: (1, 3).} =
  1348. ## Returns the amount of indentation all lines of `s` have in common,
  1349. ## ignoring lines that consist only of whitespace.
  1350. result = int.high
  1351. for line in s.splitLines:
  1352. for i, c in line:
  1353. if i >= result: break
  1354. elif c != ' ':
  1355. result = i
  1356. break
  1357. if result == int.high:
  1358. result = 0
  1359. func dedent*(s: string, count: Natural = indentation(s)): string {.rtl,
  1360. extern: "nsuDedent", since: (1, 3).} =
  1361. ## Unindents each line in `s` by `count` amount of `padding`.
  1362. ## The only difference between this and the
  1363. ## `unindent func<#unindent,string,Natural,string>`_ is that this by default
  1364. ## only cuts off the amount of indentation that all lines of `s` share as
  1365. ## opposed to all indentation. It only supports spaces as padding.
  1366. ##
  1367. ## **Note:** This does not preserve the new line characters used in `s`.
  1368. ##
  1369. ## See also:
  1370. ## * `unindent func<#unindent,string,Natural,string>`_
  1371. ## * `align func<#align,string,Natural,char>`_
  1372. ## * `alignLeft func<#alignLeft,string,Natural,char>`_
  1373. ## * `spaces func<#spaces,Natural>`_
  1374. ## * `indent func<#indent,string,Natural,string>`_
  1375. runnableExamples:
  1376. let x = """
  1377. Hello
  1378. There
  1379. """.dedent()
  1380. doAssert x == "Hello\n There\n"
  1381. unindent(s, count, " ")
  1382. func delete*(s: var string, slice: Slice[int]) =
  1383. ## Deletes the items `s[slice]`, raising `IndexDefect` if the slice contains
  1384. ## elements out of range.
  1385. ##
  1386. ## This operation moves all elements after `s[slice]` in linear time, and
  1387. ## is the string analog to `sequtils.delete`.
  1388. runnableExamples:
  1389. var a = "abcde"
  1390. doAssertRaises(IndexDefect): a.delete(4..5)
  1391. assert a == "abcde"
  1392. a.delete(4..4)
  1393. assert a == "abcd"
  1394. a.delete(1..2)
  1395. assert a == "ad"
  1396. a.delete(1..<1) # empty slice
  1397. assert a == "ad"
  1398. when compileOption("boundChecks"):
  1399. if not (slice.a < s.len and slice.a >= 0 and slice.b < s.len):
  1400. raise newException(IndexDefect, $(slice: slice, len: s.len))
  1401. if slice.b >= slice.a:
  1402. var i = slice.a
  1403. var j = slice.b + 1
  1404. var newLen = s.len - j + i
  1405. # if j < s.len: moveMem(addr s[i], addr s[j], s.len - j) # pending benchmark
  1406. while i < newLen:
  1407. s[i] = s[j]
  1408. inc(i)
  1409. inc(j)
  1410. setLen(s, newLen)
  1411. func delete*(s: var string, first, last: int) {.rtl, extern: "nsuDelete",
  1412. deprecated: "use `delete(s, first..last)`".} =
  1413. ## Deletes in `s` the characters at positions `first .. last` (both ends included).
  1414. runnableExamples("--warning:deprecated:off"):
  1415. var a = "abracadabra"
  1416. a.delete(4, 5)
  1417. doAssert a == "abradabra"
  1418. a.delete(1, 6)
  1419. doAssert a == "ara"
  1420. a.delete(2, 999)
  1421. doAssert a == "ar"
  1422. var i = first
  1423. var j = min(len(s), last+1)
  1424. var newLen = len(s)-j+i
  1425. while i < newLen:
  1426. s[i] = s[j]
  1427. inc(i)
  1428. inc(j)
  1429. setLen(s, newLen)
  1430. func startsWith*(s: string, prefix: char): bool {.inline.} =
  1431. ## Returns true if `s` starts with character `prefix`.
  1432. ##
  1433. ## See also:
  1434. ## * `endsWith func<#endsWith,string,char>`_
  1435. ## * `continuesWith func<#continuesWith,string,string,Natural>`_
  1436. ## * `removePrefix func<#removePrefix,string,char>`_
  1437. runnableExamples:
  1438. let a = "abracadabra"
  1439. doAssert a.startsWith('a') == true
  1440. doAssert a.startsWith('b') == false
  1441. result = s.len > 0 and s[0] == prefix
  1442. func startsWith*(s, prefix: string): bool {.rtl, extern: "nsuStartsWith".} =
  1443. ## Returns true if `s` starts with string `prefix`.
  1444. ##
  1445. ## If `prefix == ""` true is returned.
  1446. ##
  1447. ## See also:
  1448. ## * `endsWith func<#endsWith,string,string>`_
  1449. ## * `continuesWith func<#continuesWith,string,string,Natural>`_
  1450. ## * `removePrefix func<#removePrefix,string,string>`_
  1451. runnableExamples:
  1452. let a = "abracadabra"
  1453. doAssert a.startsWith("abra") == true
  1454. doAssert a.startsWith("bra") == false
  1455. startsWithImpl(s, prefix)
  1456. func endsWith*(s: string, suffix: char): bool {.inline.} =
  1457. ## Returns true if `s` ends with `suffix`.
  1458. ##
  1459. ## See also:
  1460. ## * `startsWith func<#startsWith,string,char>`_
  1461. ## * `continuesWith func<#continuesWith,string,string,Natural>`_
  1462. ## * `removeSuffix func<#removeSuffix,string,char>`_
  1463. runnableExamples:
  1464. let a = "abracadabra"
  1465. doAssert a.endsWith('a') == true
  1466. doAssert a.endsWith('b') == false
  1467. result = s.len > 0 and s[s.high] == suffix
  1468. func endsWith*(s, suffix: string): bool {.rtl, extern: "nsuEndsWith".} =
  1469. ## Returns true if `s` ends with `suffix`.
  1470. ##
  1471. ## If `suffix == ""` true is returned.
  1472. ##
  1473. ## See also:
  1474. ## * `startsWith func<#startsWith,string,string>`_
  1475. ## * `continuesWith func<#continuesWith,string,string,Natural>`_
  1476. ## * `removeSuffix func<#removeSuffix,string,string>`_
  1477. runnableExamples:
  1478. let a = "abracadabra"
  1479. doAssert a.endsWith("abra") == true
  1480. doAssert a.endsWith("dab") == false
  1481. endsWithImpl(s, suffix)
  1482. func continuesWith*(s, substr: string, start: Natural): bool {.rtl,
  1483. extern: "nsuContinuesWith".} =
  1484. ## Returns true if `s` continues with `substr` at position `start`.
  1485. ##
  1486. ## If `substr == ""` true is returned.
  1487. ##
  1488. ## See also:
  1489. ## * `startsWith func<#startsWith,string,string>`_
  1490. ## * `endsWith func<#endsWith,string,string>`_
  1491. runnableExamples:
  1492. let a = "abracadabra"
  1493. doAssert a.continuesWith("ca", 4) == true
  1494. doAssert a.continuesWith("ca", 5) == false
  1495. doAssert a.continuesWith("dab", 6) == true
  1496. var i = 0
  1497. while true:
  1498. if i >= substr.len: return true
  1499. if i+start >= s.len or s[i+start] != substr[i]: return false
  1500. inc(i)
  1501. func removePrefix*(s: var string, chars: set[char] = Newlines) {.rtl,
  1502. extern: "nsuRemovePrefixCharSet".} =
  1503. ## Removes all characters from `chars` from the start of the string `s`
  1504. ## (in-place).
  1505. ##
  1506. ## See also:
  1507. ## * `removeSuffix func<#removeSuffix,string,set[char]>`_
  1508. runnableExamples:
  1509. var userInput = "\r\n*~Hello World!"
  1510. userInput.removePrefix
  1511. doAssert userInput == "*~Hello World!"
  1512. userInput.removePrefix({'~', '*'})
  1513. doAssert userInput == "Hello World!"
  1514. var otherInput = "?!?Hello!?!"
  1515. otherInput.removePrefix({'!', '?'})
  1516. doAssert otherInput == "Hello!?!"
  1517. var start = 0
  1518. while start < s.len and s[start] in chars: start += 1
  1519. if start > 0: s.delete(0..start - 1)
  1520. func removePrefix*(s: var string, c: char) {.rtl,
  1521. extern: "nsuRemovePrefixChar".} =
  1522. ## Removes all occurrences of a single character (in-place) from the start
  1523. ## of a string.
  1524. ##
  1525. ## See also:
  1526. ## * `removeSuffix func<#removeSuffix,string,char>`_
  1527. ## * `startsWith func<#startsWith,string,char>`_
  1528. runnableExamples:
  1529. var ident = "pControl"
  1530. ident.removePrefix('p')
  1531. doAssert ident == "Control"
  1532. removePrefix(s, chars = {c})
  1533. func removePrefix*(s: var string, prefix: string) {.rtl,
  1534. extern: "nsuRemovePrefixString".} =
  1535. ## Remove the first matching prefix (in-place) from a string.
  1536. ##
  1537. ## See also:
  1538. ## * `removeSuffix func<#removeSuffix,string,string>`_
  1539. ## * `startsWith func<#startsWith,string,string>`_
  1540. runnableExamples:
  1541. var answers = "yesyes"
  1542. answers.removePrefix("yes")
  1543. doAssert answers == "yes"
  1544. if s.startsWith(prefix) and prefix.len > 0:
  1545. s.delete(0..prefix.len - 1)
  1546. func removeSuffix*(s: var string, chars: set[char] = Newlines) {.rtl,
  1547. extern: "nsuRemoveSuffixCharSet".} =
  1548. ## Removes all characters from `chars` from the end of the string `s`
  1549. ## (in-place).
  1550. ##
  1551. ## See also:
  1552. ## * `removePrefix func<#removePrefix,string,set[char]>`_
  1553. runnableExamples:
  1554. var userInput = "Hello World!*~\r\n"
  1555. userInput.removeSuffix
  1556. doAssert userInput == "Hello World!*~"
  1557. userInput.removeSuffix({'~', '*'})
  1558. doAssert userInput == "Hello World!"
  1559. var otherInput = "Hello!?!"
  1560. otherInput.removeSuffix({'!', '?'})
  1561. doAssert otherInput == "Hello"
  1562. if s.len == 0: return
  1563. var last = s.high
  1564. while last > -1 and s[last] in chars: last -= 1
  1565. s.setLen(last + 1)
  1566. func removeSuffix*(s: var string, c: char) {.rtl,
  1567. extern: "nsuRemoveSuffixChar".} =
  1568. ## Removes all occurrences of a single character (in-place) from the end
  1569. ## of a string.
  1570. ##
  1571. ## See also:
  1572. ## * `removePrefix func<#removePrefix,string,char>`_
  1573. ## * `endsWith func<#endsWith,string,char>`_
  1574. runnableExamples:
  1575. var table = "users"
  1576. table.removeSuffix('s')
  1577. doAssert table == "user"
  1578. var dots = "Trailing dots......."
  1579. dots.removeSuffix('.')
  1580. doAssert dots == "Trailing dots"
  1581. removeSuffix(s, chars = {c})
  1582. func removeSuffix*(s: var string, suffix: string) {.rtl,
  1583. extern: "nsuRemoveSuffixString".} =
  1584. ## Remove the first matching suffix (in-place) from a string.
  1585. ##
  1586. ## See also:
  1587. ## * `removePrefix func<#removePrefix,string,string>`_
  1588. ## * `endsWith func<#endsWith,string,string>`_
  1589. runnableExamples:
  1590. var answers = "yeses"
  1591. answers.removeSuffix("es")
  1592. doAssert answers == "yes"
  1593. var newLen = s.len
  1594. if s.endsWith(suffix):
  1595. newLen -= len(suffix)
  1596. s.setLen(newLen)
  1597. func addSep*(dest: var string, sep = ", ", startLen: Natural = 0) {.inline.} =
  1598. ## Adds a separator to `dest` only if its length is bigger than `startLen`.
  1599. ##
  1600. ## A shorthand for:
  1601. ##
  1602. ## .. code-block:: nim
  1603. ## if dest.len > startLen: add(dest, sep)
  1604. ##
  1605. ## This is often useful for generating some code where the items need to
  1606. ## be *separated* by `sep`. `sep` is only added if `dest` is longer than
  1607. ## `startLen`. The following example creates a string describing
  1608. ## an array of integers.
  1609. runnableExamples:
  1610. var arr = "["
  1611. for x in items([2, 3, 5, 7, 11]):
  1612. addSep(arr, startLen = len("["))
  1613. add(arr, $x)
  1614. add(arr, "]")
  1615. doAssert arr == "[2, 3, 5, 7, 11]"
  1616. if dest.len > startLen: add(dest, sep)
  1617. func allCharsInSet*(s: string, theSet: set[char]): bool =
  1618. ## Returns true if every character of `s` is in the set `theSet`.
  1619. runnableExamples:
  1620. doAssert allCharsInSet("aeea", {'a', 'e'}) == true
  1621. doAssert allCharsInSet("", {'a', 'e'}) == true
  1622. for c in items(s):
  1623. if c notin theSet: return false
  1624. return true
  1625. func abbrev*(s: string, possibilities: openArray[string]): int =
  1626. ## Returns the index of the first item in `possibilities` which starts
  1627. ## with `s`, if not ambiguous.
  1628. ##
  1629. ## Returns -1 if no item has been found and -2 if multiple items match.
  1630. runnableExamples:
  1631. doAssert abbrev("fac", ["college", "faculty", "industry"]) == 1
  1632. doAssert abbrev("foo", ["college", "faculty", "industry"]) == -1 # Not found
  1633. doAssert abbrev("fac", ["college", "faculty", "faculties"]) == -2 # Ambiguous
  1634. doAssert abbrev("college", ["college", "colleges", "industry"]) == 0
  1635. result = -1 # none found
  1636. for i in 0..possibilities.len-1:
  1637. if possibilities[i].startsWith(s):
  1638. if possibilities[i] == s:
  1639. # special case: exact match shouldn't be ambiguous
  1640. return i
  1641. if result >= 0: return -2 # ambiguous
  1642. result = i
  1643. # ---------------------------------------------------------------------------
  1644. func join*(a: openArray[string], sep: string = ""): string {.rtl,
  1645. extern: "nsuJoinSep".} =
  1646. ## Concatenates all strings in the container `a`, separating them with `sep`.
  1647. runnableExamples:
  1648. doAssert join(["A", "B", "Conclusion"], " -> ") == "A -> B -> Conclusion"
  1649. if len(a) > 0:
  1650. var L = sep.len * (a.len-1)
  1651. for i in 0..high(a): inc(L, a[i].len)
  1652. result = newStringOfCap(L)
  1653. add(result, a[0])
  1654. for i in 1..high(a):
  1655. add(result, sep)
  1656. add(result, a[i])
  1657. else:
  1658. result = ""
  1659. func join*[T: not string](a: openArray[T], sep: string = ""): string =
  1660. ## Converts all elements in the container `a` to strings using `$`,
  1661. ## and concatenates them with `sep`.
  1662. runnableExamples:
  1663. doAssert join([1, 2, 3], " -> ") == "1 -> 2 -> 3"
  1664. result = ""
  1665. for i, x in a:
  1666. if i > 0:
  1667. add(result, sep)
  1668. add(result, $x)
  1669. type
  1670. SkipTable* = array[char, int] ## Character table for efficient substring search.
  1671. func initSkipTable*(a: var SkipTable, sub: string) {.rtl,
  1672. extern: "nsuInitSkipTable".} =
  1673. ## Initializes table `a` for efficient search of substring `sub`.
  1674. ##
  1675. ## See also:
  1676. ## * `initSkipTable func<#initSkipTable,string>`_
  1677. ## * `find func<#find,SkipTable,string,string,Natural,int>`_
  1678. # TODO: this should be the `default()` initializer for the type.
  1679. let m = len(sub)
  1680. fill(a, m)
  1681. for i in 0 ..< m - 1:
  1682. a[sub[i]] = m - 1 - i
  1683. func initSkipTable*(sub: string): SkipTable {.noinit, rtl,
  1684. extern: "nsuInitNewSkipTable".} =
  1685. ## Returns a new table initialized for `sub`.
  1686. ##
  1687. ## See also:
  1688. ## * `initSkipTable func<#initSkipTable,SkipTable,string>`_
  1689. ## * `find func<#find,SkipTable,string,string,Natural,int>`_
  1690. initSkipTable(result, sub)
  1691. func find*(a: SkipTable, s, sub: string, start: Natural = 0, last = -1): int {.
  1692. rtl, extern: "nsuFindStrA".} =
  1693. ## Searches for `sub` in `s` inside range `start..last` using preprocessed
  1694. ## table `a`. If `last` is unspecified, it defaults to `s.high` (the last
  1695. ## element).
  1696. ##
  1697. ## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
  1698. ##
  1699. ## See also:
  1700. ## * `initSkipTable func<#initSkipTable,string>`_
  1701. ## * `initSkipTable func<#initSkipTable,SkipTable,string>`_
  1702. let
  1703. last = if last < 0: s.high else: last
  1704. subLast = sub.len - 1
  1705. if subLast == -1:
  1706. # this was an empty needle string,
  1707. # we count this as match in the first possible position:
  1708. return start
  1709. # This is an implementation of the Boyer-Moore Horspool algorithms
  1710. # https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm
  1711. result = -1
  1712. var skip = start
  1713. while last - skip >= subLast:
  1714. var i = subLast
  1715. while s[skip + i] == sub[i]:
  1716. if i == 0:
  1717. return skip
  1718. dec i
  1719. inc skip, a[s[skip + subLast]]
  1720. when not (defined(js) or defined(nimdoc) or defined(nimscript)):
  1721. func c_memchr(cstr: pointer, c: char, n: csize_t): pointer {.
  1722. importc: "memchr", header: "<string.h>".}
  1723. const hasCStringBuiltin = true
  1724. else:
  1725. const hasCStringBuiltin = false
  1726. func find*(s: string, sub: char, start: Natural = 0, last = -1): int {.rtl,
  1727. extern: "nsuFindChar".} =
  1728. ## Searches for `sub` in `s` inside range `start..last` (both ends included).
  1729. ## If `last` is unspecified or negative, it defaults to `s.high` (the last element).
  1730. ##
  1731. ## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
  1732. ## Otherwise the index returned is relative to `s[0]`, not `start`.
  1733. ## Subtract `start` from the result for a `start`-origin index.
  1734. ##
  1735. ## See also:
  1736. ## * `rfind func<#rfind,string,char,Natural,int>`_
  1737. ## * `replace func<#replace,string,char,char>`_
  1738. result = -1
  1739. let last = if last < 0: s.high else: last
  1740. template findImpl =
  1741. for i in int(start)..last:
  1742. if s[i] == sub:
  1743. return i
  1744. when nimvm:
  1745. findImpl()
  1746. else:
  1747. when hasCStringBuiltin:
  1748. let length = last-start+1
  1749. if length > 0:
  1750. let found = c_memchr(s[start].unsafeAddr, sub, cast[csize_t](length))
  1751. if not found.isNil:
  1752. return cast[int](found) -% cast[int](s.cstring)
  1753. else:
  1754. findImpl()
  1755. func find*(s: string, chars: set[char], start: Natural = 0, last = -1): int {.
  1756. rtl, extern: "nsuFindCharSet".} =
  1757. ## Searches for `chars` in `s` inside range `start..last` (both ends included).
  1758. ## If `last` is unspecified or negative, it defaults to `s.high` (the last element).
  1759. ##
  1760. ## If `s` contains none of the characters in `chars`, -1 is returned.
  1761. ## Otherwise the index returned is relative to `s[0]`, not `start`.
  1762. ## Subtract `start` from the result for a `start`-origin index.
  1763. ##
  1764. ## See also:
  1765. ## * `rfind func<#rfind,string,set[char],Natural,int>`_
  1766. ## * `multiReplace func<#multiReplace,string,varargs[]>`_
  1767. result = -1
  1768. let last = if last < 0: s.high else: last
  1769. for i in int(start)..last:
  1770. if s[i] in chars:
  1771. return i
  1772. when defined(linux):
  1773. proc memmem(haystack: pointer, haystacklen: csize_t,
  1774. needle: pointer, needlelen: csize_t): pointer {.importc, header: """#define _GNU_SOURCE
  1775. #include <string.h>""".}
  1776. elif defined(bsd) or (defined(macosx) and not defined(ios)):
  1777. proc memmem(haystack: pointer, haystacklen: csize_t,
  1778. needle: pointer, needlelen: csize_t): pointer {.importc, header: "#include <string.h>".}
  1779. func find*(s, sub: string, start: Natural = 0, last = -1): int {.rtl,
  1780. extern: "nsuFindStr".} =
  1781. ## Searches for `sub` in `s` inside range `start..last` (both ends included).
  1782. ## If `last` is unspecified or negative, it defaults to `s.high` (the last element).
  1783. ##
  1784. ## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
  1785. ## Otherwise the index returned is relative to `s[0]`, not `start`.
  1786. ## Subtract `start` from the result for a `start`-origin index.
  1787. ##
  1788. ## See also:
  1789. ## * `rfind func<#rfind,string,string,Natural,int>`_
  1790. ## * `replace func<#replace,string,string,string>`_
  1791. if sub.len > s.len - start: return -1
  1792. if sub.len == 1: return find(s, sub[0], start, last)
  1793. template useSkipTable =
  1794. result = find(initSkipTable(sub), s, sub, start, last)
  1795. when nimvm:
  1796. useSkipTable()
  1797. else:
  1798. when declared(memmem):
  1799. let subLen = sub.len
  1800. if last < 0 and start < s.len and subLen != 0:
  1801. let found = memmem(s[start].unsafeAddr, csize_t(s.len - start), sub.cstring, csize_t(subLen))
  1802. result = if not found.isNil:
  1803. cast[int](found) -% cast[int](s.cstring)
  1804. else:
  1805. -1
  1806. else:
  1807. useSkipTable()
  1808. else:
  1809. useSkipTable()
  1810. func rfind*(s: string, sub: char, start: Natural = 0, last = -1): int {.rtl,
  1811. extern: "nsuRFindChar".} =
  1812. ## Searches for `sub` in `s` inside range `start..last` (both ends included)
  1813. ## in reverse -- starting at high indexes and moving lower to the first
  1814. ## character or `start`. If `last` is unspecified, it defaults to `s.high`
  1815. ## (the last element).
  1816. ##
  1817. ## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
  1818. ## Otherwise the index returned is relative to `s[0]`, not `start`.
  1819. ## Subtract `start` from the result for a `start`-origin index.
  1820. ##
  1821. ## See also:
  1822. ## * `find func<#find,string,char,Natural,int>`_
  1823. let last = if last == -1: s.high else: last
  1824. for i in countdown(last, start):
  1825. if sub == s[i]: return i
  1826. return -1
  1827. func rfind*(s: string, chars: set[char], start: Natural = 0, last = -1): int {.
  1828. rtl, extern: "nsuRFindCharSet".} =
  1829. ## Searches for `chars` in `s` inside range `start..last` (both ends
  1830. ## included) in reverse -- starting at high indexes and moving lower to the
  1831. ## first character or `start`. If `last` is unspecified, it defaults to
  1832. ## `s.high` (the last element).
  1833. ##
  1834. ## If `s` contains none of the characters in `chars`, -1 is returned.
  1835. ## Otherwise the index returned is relative to `s[0]`, not `start`.
  1836. ## Subtract `start` from the result for a `start`-origin index.
  1837. ##
  1838. ## See also:
  1839. ## * `find func<#find,string,set[char],Natural,int>`_
  1840. let last = if last == -1: s.high else: last
  1841. for i in countdown(last, start):
  1842. if s[i] in chars: return i
  1843. return -1
  1844. func rfind*(s, sub: string, start: Natural = 0, last = -1): int {.rtl,
  1845. extern: "nsuRFindStr".} =
  1846. ## Searches for `sub` in `s` inside range `start..last` (both ends included)
  1847. ## included) in reverse -- starting at high indexes and moving lower to the
  1848. ## first character or `start`. If `last` is unspecified, it defaults to
  1849. ## `s.high` (the last element).
  1850. ##
  1851. ## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
  1852. ## Otherwise the index returned is relative to `s[0]`, not `start`.
  1853. ## Subtract `start` from the result for a `start`-origin index.
  1854. ##
  1855. ## See also:
  1856. ## * `find func<#find,string,string,Natural,int>`_
  1857. if sub.len == 0:
  1858. let rightIndex: Natural = if last < 0: s.len else: last
  1859. return max(start, rightIndex)
  1860. if sub.len > s.len - start:
  1861. return -1
  1862. let last = if last == -1: s.high else: last
  1863. result = 0
  1864. for i in countdown(last - sub.len + 1, start):
  1865. for j in 0..sub.len-1:
  1866. result = i
  1867. if sub[j] != s[i+j]:
  1868. result = -1
  1869. break
  1870. if result != -1: return
  1871. return -1
  1872. func count*(s: string, sub: char): int {.rtl, extern: "nsuCountChar".} =
  1873. ## Counts the occurrences of the character `sub` in the string `s`.
  1874. ##
  1875. ## See also:
  1876. ## * `countLines func<#countLines,string>`_
  1877. result = 0
  1878. for c in s:
  1879. if c == sub: inc result
  1880. func count*(s: string, subs: set[char]): int {.rtl,
  1881. extern: "nsuCountCharSet".} =
  1882. ## Counts the occurrences of the group of character `subs` in the string `s`.
  1883. ##
  1884. ## See also:
  1885. ## * `countLines func<#countLines,string>`_
  1886. doAssert card(subs) > 0
  1887. result = 0
  1888. for c in s:
  1889. if c in subs: inc result
  1890. func count*(s: string, sub: string, overlapping: bool = false): int {.rtl,
  1891. extern: "nsuCountString".} =
  1892. ## Counts the occurrences of a substring `sub` in the string `s`.
  1893. ## Overlapping occurrences of `sub` only count when `overlapping`
  1894. ## is set to true (default: false).
  1895. ##
  1896. ## See also:
  1897. ## * `countLines func<#countLines,string>`_
  1898. doAssert sub.len > 0
  1899. result = 0
  1900. var i = 0
  1901. while true:
  1902. i = s.find(sub, i)
  1903. if i < 0: break
  1904. if overlapping: inc i
  1905. else: i += sub.len
  1906. inc result
  1907. func countLines*(s: string): int {.rtl, extern: "nsuCountLines".} =
  1908. ## Returns the number of lines in the string `s`.
  1909. ##
  1910. ## This is the same as `len(splitLines(s))`, but much more efficient
  1911. ## because it doesn't modify the string creating temporary objects. Every
  1912. ## `character literal <manual.html#lexical-analysis-character-literals>`_
  1913. ## newline combination (CR, LF, CR-LF) is supported.
  1914. ##
  1915. ## In this context, a line is any string separated by a newline combination.
  1916. ## A line can be an empty string.
  1917. ##
  1918. ## See also:
  1919. ## * `splitLines func<#splitLines,string>`_
  1920. runnableExamples:
  1921. doAssert countLines("First line\l and second line.") == 2
  1922. result = 1
  1923. var i = 0
  1924. while i < s.len:
  1925. case s[i]
  1926. of '\c':
  1927. if i+1 < s.len and s[i+1] == '\l': inc i
  1928. inc result
  1929. of '\l': inc result
  1930. else: discard
  1931. inc i
  1932. func contains*(s, sub: string): bool =
  1933. ## Same as `find(s, sub) >= 0`.
  1934. ##
  1935. ## See also:
  1936. ## * `find func<#find,string,string,Natural,int>`_
  1937. return find(s, sub) >= 0
  1938. func contains*(s: string, chars: set[char]): bool =
  1939. ## Same as `find(s, chars) >= 0`.
  1940. ##
  1941. ## See also:
  1942. ## * `find func<#find,string,set[char],Natural,int>`_
  1943. return find(s, chars) >= 0
  1944. func replace*(s, sub: string, by = ""): string {.rtl,
  1945. extern: "nsuReplaceStr".} =
  1946. ## Replaces every occurrence of the string `sub` in `s` with the string `by`.
  1947. ##
  1948. ## See also:
  1949. ## * `find func<#find,string,string,Natural,int>`_
  1950. ## * `replace func<#replace,string,char,char>`_ for replacing
  1951. ## single characters
  1952. ## * `replaceWord func<#replaceWord,string,string,string>`_
  1953. ## * `multiReplace func<#multiReplace,string,varargs[]>`_
  1954. result = ""
  1955. let subLen = sub.len
  1956. if subLen == 0:
  1957. result = s
  1958. elif subLen == 1:
  1959. # when the pattern is a single char, we use a faster
  1960. # char-based search that doesn't need a skip table:
  1961. let c = sub[0]
  1962. let last = s.high
  1963. var i = 0
  1964. while true:
  1965. let j = find(s, c, i, last)
  1966. if j < 0: break
  1967. add result, substr(s, i, j - 1)
  1968. add result, by
  1969. i = j + subLen
  1970. # copy the rest:
  1971. add result, substr(s, i)
  1972. else:
  1973. var a = initSkipTable(sub)
  1974. let last = s.high
  1975. var i = 0
  1976. while true:
  1977. let j = find(a, s, sub, i, last)
  1978. if j < 0: break
  1979. add result, substr(s, i, j - 1)
  1980. add result, by
  1981. i = j + subLen
  1982. # copy the rest:
  1983. add result, substr(s, i)
  1984. func replace*(s: string, sub, by: char): string {.rtl,
  1985. extern: "nsuReplaceChar".} =
  1986. ## Replaces every occurrence of the character `sub` in `s` with the character
  1987. ## `by`.
  1988. ##
  1989. ## Optimized version of `replace <#replace,string,string,string>`_ for
  1990. ## characters.
  1991. ##
  1992. ## See also:
  1993. ## * `find func<#find,string,char,Natural,int>`_
  1994. ## * `replaceWord func<#replaceWord,string,string,string>`_
  1995. ## * `multiReplace func<#multiReplace,string,varargs[]>`_
  1996. result = newString(s.len)
  1997. var i = 0
  1998. while i < s.len:
  1999. if s[i] == sub: result[i] = by
  2000. else: result[i] = s[i]
  2001. inc(i)
  2002. func replaceWord*(s, sub: string, by = ""): string {.rtl,
  2003. extern: "nsuReplaceWord".} =
  2004. ## Replaces every occurrence of the string `sub` in `s` with the string `by`.
  2005. ##
  2006. ## Each occurrence of `sub` has to be surrounded by word boundaries
  2007. ## (comparable to `\b` in regular expressions), otherwise it is not
  2008. ## replaced.
  2009. if sub.len == 0: return s
  2010. const wordChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'}
  2011. result = ""
  2012. var a = initSkipTable(sub)
  2013. var i = 0
  2014. let last = s.high
  2015. let sublen = sub.len
  2016. if sublen > 0:
  2017. while true:
  2018. var j = find(a, s, sub, i, last)
  2019. if j < 0: break
  2020. # word boundary?
  2021. if (j == 0 or s[j-1] notin wordChars) and
  2022. (j+sub.len >= s.len or s[j+sub.len] notin wordChars):
  2023. add result, substr(s, i, j - 1)
  2024. add result, by
  2025. i = j + sublen
  2026. else:
  2027. add result, substr(s, i, j)
  2028. i = j + 1
  2029. # copy the rest:
  2030. add result, substr(s, i)
  2031. func multiReplace*(s: string, replacements: varargs[(string, string)]): string =
  2032. ## Same as replace, but specialized for doing multiple replacements in a single
  2033. ## pass through the input string.
  2034. ##
  2035. ## `multiReplace` performs all replacements in a single pass, this means it
  2036. ## can be used to swap the occurrences of "a" and "b", for instance.
  2037. ##
  2038. ## If the resulting string is not longer than the original input string,
  2039. ## only a single memory allocation is required.
  2040. ##
  2041. ## The order of the replacements does matter. Earlier replacements are
  2042. ## preferred over later replacements in the argument list.
  2043. result = newStringOfCap(s.len)
  2044. var i = 0
  2045. var fastChk: set[char] = {}
  2046. for sub, by in replacements.items:
  2047. if sub.len > 0:
  2048. # Include first character of all replacements
  2049. fastChk.incl sub[0]
  2050. while i < s.len:
  2051. block sIteration:
  2052. # Assume most chars in s are not candidates for any replacement operation
  2053. if s[i] in fastChk:
  2054. for sub, by in replacements.items:
  2055. if sub.len > 0 and s.continuesWith(sub, i):
  2056. add result, by
  2057. inc(i, sub.len)
  2058. break sIteration
  2059. # No matching replacement found
  2060. # copy current character from s
  2061. add result, s[i]
  2062. inc(i)
  2063. func insertSep*(s: string, sep = '_', digits = 3): string {.rtl,
  2064. extern: "nsuInsertSep".} =
  2065. ## Inserts the separator `sep` after `digits` characters (default: 3)
  2066. ## from right to left.
  2067. ##
  2068. ## Even though the algorithm works with any string `s`, it is only useful
  2069. ## if `s` contains a number.
  2070. runnableExamples:
  2071. doAssert insertSep("1000000") == "1_000_000"
  2072. result = newStringOfCap(s.len)
  2073. let hasPrefix = isDigit(s[s.low]) == false
  2074. var idx: int
  2075. if hasPrefix:
  2076. result.add s[s.low]
  2077. for i in (s.low + 1)..s.high:
  2078. idx = i
  2079. if not isDigit(s[i]):
  2080. result.add s[i]
  2081. else:
  2082. break
  2083. let partsLen = s.len - idx
  2084. var L = (partsLen-1) div digits + partsLen
  2085. result.setLen(L + idx)
  2086. var j = 0
  2087. dec(L)
  2088. for i in countdown(partsLen-1, 0):
  2089. if j == digits:
  2090. result[L + idx] = sep
  2091. dec(L)
  2092. j = 0
  2093. result[L + idx] = s[i + idx]
  2094. inc(j)
  2095. dec(L)
  2096. func escape*(s: string, prefix = "\"", suffix = "\""): string {.rtl,
  2097. extern: "nsuEscape".} =
  2098. ## Escapes a string `s`.
  2099. ##
  2100. ## .. note:: The escaping scheme is different from
  2101. ## `system.addEscapedChar`.
  2102. ##
  2103. ## * replaces `'\0'..'\31'` and `'\127'..'\255'` by `\xHH` where `HH` is its hexadecimal value
  2104. ## * replaces ``\`` by `\\`
  2105. ## * replaces `'` by `\'`
  2106. ## * replaces `"` by `\"`
  2107. ##
  2108. ## The resulting string is prefixed with `prefix` and suffixed with `suffix`.
  2109. ## Both may be empty strings.
  2110. ##
  2111. ## See also:
  2112. ## * `addEscapedChar proc<system.html#addEscapedChar,string,char>`_
  2113. ## * `unescape func<#unescape,string,string,string>`_ for the opposite
  2114. ## operation
  2115. result = newStringOfCap(s.len + s.len shr 2)
  2116. result.add(prefix)
  2117. for c in items(s):
  2118. case c
  2119. of '\0'..'\31', '\127'..'\255':
  2120. add(result, "\\x")
  2121. add(result, toHex(ord(c), 2))
  2122. of '\\': add(result, "\\\\")
  2123. of '\'': add(result, "\\'")
  2124. of '\"': add(result, "\\\"")
  2125. else: add(result, c)
  2126. add(result, suffix)
  2127. func unescape*(s: string, prefix = "\"", suffix = "\""): string {.rtl,
  2128. extern: "nsuUnescape".} =
  2129. ## Unescapes a string `s`.
  2130. ##
  2131. ## This complements `escape func<#escape,string,string,string>`_
  2132. ## as it performs the opposite operations.
  2133. ##
  2134. ## If `s` does not begin with `prefix` and end with `suffix` a
  2135. ## ValueError exception will be raised.
  2136. result = newStringOfCap(s.len)
  2137. var i = prefix.len
  2138. if not s.startsWith(prefix):
  2139. raise newException(ValueError,
  2140. "String does not start with: " & prefix)
  2141. while true:
  2142. if i >= s.len-suffix.len: break
  2143. if s[i] == '\\':
  2144. if i+1 >= s.len:
  2145. result.add('\\')
  2146. break
  2147. case s[i+1]:
  2148. of 'x':
  2149. inc i, 2
  2150. var c = 0
  2151. i += parseutils.parseHex(s, c, i, maxLen = 2)
  2152. result.add(chr(c))
  2153. dec i, 2
  2154. of '\\':
  2155. result.add('\\')
  2156. of '\'':
  2157. result.add('\'')
  2158. of '\"':
  2159. result.add('\"')
  2160. else:
  2161. result.add("\\" & s[i+1])
  2162. inc(i, 2)
  2163. else:
  2164. result.add(s[i])
  2165. inc(i)
  2166. if not s.endsWith(suffix):
  2167. raise newException(ValueError,
  2168. "String does not end in: " & suffix)
  2169. func validIdentifier*(s: string): bool {.rtl, extern: "nsuValidIdentifier".} =
  2170. ## Returns true if `s` is a valid identifier.
  2171. ##
  2172. ## A valid identifier starts with a character of the set `IdentStartChars`
  2173. ## and is followed by any number of characters of the set `IdentChars`.
  2174. runnableExamples:
  2175. doAssert "abc_def08".validIdentifier
  2176. if s.len > 0 and s[0] in IdentStartChars:
  2177. for i in 1..s.len-1:
  2178. if s[i] notin IdentChars: return false
  2179. return true
  2180. # floating point formatting:
  2181. when not defined(js):
  2182. func c_sprintf(buf, frmt: cstring): cint {.header: "<stdio.h>",
  2183. importc: "sprintf", varargs.}
  2184. type
  2185. FloatFormatMode* = enum
  2186. ## The different modes of floating point formatting.
  2187. ffDefault, ## use the shorter floating point notation
  2188. ffDecimal, ## use decimal floating point notation
  2189. ffScientific ## use scientific notation (using `e` character)
  2190. func formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
  2191. precision: range[-1..32] = 16;
  2192. decimalSep = '.'): string {.rtl, extern: "nsu$1".} =
  2193. ## Converts a floating point value `f` to a string.
  2194. ##
  2195. ## If `format == ffDecimal` then precision is the number of digits to
  2196. ## be printed after the decimal point.
  2197. ## If `format == ffScientific` then precision is the maximum number
  2198. ## of significant digits to be printed.
  2199. ## `precision`'s default value is the maximum number of meaningful digits
  2200. ## after the decimal point for Nim's `biggestFloat` type.
  2201. ##
  2202. ## If `precision == -1`, it tries to format it nicely.
  2203. runnableExamples:
  2204. let x = 123.456
  2205. doAssert x.formatBiggestFloat() == "123.4560000000000"
  2206. doAssert x.formatBiggestFloat(ffDecimal, 4) == "123.4560"
  2207. doAssert x.formatBiggestFloat(ffScientific, 2) == "1.23e+02"
  2208. when nimvm:
  2209. discard "implemented in the vmops"
  2210. else:
  2211. when defined(js):
  2212. var precision = precision
  2213. if precision == -1:
  2214. # use the same default precision as c_sprintf
  2215. precision = 6
  2216. var res: cstring
  2217. case format
  2218. of ffDefault:
  2219. {.emit: "`res` = `f`.toString();".}
  2220. of ffDecimal:
  2221. {.emit: "`res` = `f`.toFixed(`precision`);".}
  2222. of ffScientific:
  2223. {.emit: "`res` = `f`.toExponential(`precision`);".}
  2224. result = $res
  2225. if 1.0 / f == -Inf:
  2226. # JavaScript removes the "-" from negative Zero, add it back here
  2227. result = "-" & $res
  2228. for i in 0 ..< result.len:
  2229. # Depending on the locale either dot or comma is produced,
  2230. # but nothing else is possible:
  2231. if result[i] in {'.', ','}: result[i] = decimalSep
  2232. else:
  2233. const floatFormatToChar: array[FloatFormatMode, char] = ['g', 'f', 'e']
  2234. var
  2235. frmtstr {.noinit.}: array[0..5, char]
  2236. buf {.noinit.}: array[0..2500, char]
  2237. L: cint
  2238. frmtstr[0] = '%'
  2239. if precision >= 0:
  2240. frmtstr[1] = '#'
  2241. frmtstr[2] = '.'
  2242. frmtstr[3] = '*'
  2243. frmtstr[4] = floatFormatToChar[format]
  2244. frmtstr[5] = '\0'
  2245. L = c_sprintf(cast[cstring](addr buf), cast[cstring](addr frmtstr), precision, f)
  2246. else:
  2247. frmtstr[1] = floatFormatToChar[format]
  2248. frmtstr[2] = '\0'
  2249. L = c_sprintf(cast[cstring](addr buf), cast[cstring](addr frmtstr), f)
  2250. result = newString(L)
  2251. for i in 0 ..< L:
  2252. # Depending on the locale either dot or comma is produced,
  2253. # but nothing else is possible:
  2254. if buf[i] in {'.', ','}: result[i] = decimalSep
  2255. else: result[i] = buf[i]
  2256. when defined(windows):
  2257. # VS pre 2015 violates the C standard: "The exponent always contains at
  2258. # least two digits, and only as many more digits as necessary to
  2259. # represent the exponent." [C11 §7.21.6.1]
  2260. # The following post-processing fixes this behavior.
  2261. if result.len > 4 and result[^4] == '+' and result[^3] == '0':
  2262. result[^3] = result[^2]
  2263. result[^2] = result[^1]
  2264. result.setLen(result.len - 1)
  2265. func formatFloat*(f: float, format: FloatFormatMode = ffDefault,
  2266. precision: range[-1..32] = 16; decimalSep = '.'): string {.
  2267. rtl, extern: "nsu$1".} =
  2268. ## Converts a floating point value `f` to a string.
  2269. ##
  2270. ## If `format == ffDecimal` then precision is the number of digits to
  2271. ## be printed after the decimal point.
  2272. ## If `format == ffScientific` then precision is the maximum number
  2273. ## of significant digits to be printed.
  2274. ## `precision`'s default value is the maximum number of meaningful digits
  2275. ## after the decimal point for Nim's `float` type.
  2276. ##
  2277. ## If `precision == -1`, it tries to format it nicely.
  2278. runnableExamples:
  2279. let x = 123.456
  2280. doAssert x.formatFloat() == "123.4560000000000"
  2281. doAssert x.formatFloat(ffDecimal, 4) == "123.4560"
  2282. doAssert x.formatFloat(ffScientific, 2) == "1.23e+02"
  2283. result = formatBiggestFloat(f, format, precision, decimalSep)
  2284. func trimZeros*(x: var string; decimalSep = '.') =
  2285. ## Trim trailing zeros from a formatted floating point
  2286. ## value `x` (must be declared as `var`).
  2287. ##
  2288. ## This modifies `x` itself, it does not return a copy.
  2289. runnableExamples:
  2290. var x = "123.456000000"
  2291. x.trimZeros()
  2292. doAssert x == "123.456"
  2293. let sPos = find(x, decimalSep)
  2294. if sPos >= 0:
  2295. var last = find(x, 'e', start = sPos)
  2296. last = if last >= 0: last - 1 else: high(x)
  2297. var pos = last
  2298. while pos >= 0 and x[pos] == '0': dec(pos)
  2299. if pos > sPos: inc(pos)
  2300. if last >= pos:
  2301. x.delete(pos..last)
  2302. type
  2303. BinaryPrefixMode* = enum ## The different names for binary prefixes.
  2304. bpIEC, # use the IEC/ISO standard prefixes such as kibi
  2305. bpColloquial # use the colloquial kilo, mega etc
  2306. func formatSize*(bytes: int64,
  2307. decimalSep = '.',
  2308. prefix = bpIEC,
  2309. includeSpace = false): string =
  2310. ## Rounds and formats `bytes`.
  2311. ##
  2312. ## By default, uses the IEC/ISO standard binary prefixes, so 1024 will be
  2313. ## formatted as 1KiB. Set prefix to `bpColloquial` to use the colloquial
  2314. ## names from the SI standard (e.g. k for 1000 being reused as 1024).
  2315. ##
  2316. ## `includeSpace` can be set to true to include the (SI preferred) space
  2317. ## between the number and the unit (e.g. 1 KiB).
  2318. ##
  2319. ## See also:
  2320. ## * `strformat module<strformat.html>`_ for string interpolation and formatting
  2321. runnableExamples:
  2322. doAssert formatSize((1'i64 shl 31) + (300'i64 shl 20)) == "2.293GiB"
  2323. doAssert formatSize((2.234*1024*1024).int) == "2.234MiB"
  2324. doAssert formatSize(4096, includeSpace = true) == "4 KiB"
  2325. doAssert formatSize(4096, prefix = bpColloquial, includeSpace = true) == "4 kB"
  2326. doAssert formatSize(4096) == "4KiB"
  2327. doAssert formatSize(5_378_934, prefix = bpColloquial, decimalSep = ',') == "5,13MB"
  2328. const iecPrefixes = ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"]
  2329. const collPrefixes = ["", "k", "M", "G", "T", "P", "E", "Z", "Y"]
  2330. var
  2331. xb: int64 = bytes
  2332. fbytes: float
  2333. lastXb: int64 = bytes
  2334. matchedIndex = 0
  2335. prefixes: array[9, string]
  2336. if prefix == bpColloquial:
  2337. prefixes = collPrefixes
  2338. else:
  2339. prefixes = iecPrefixes
  2340. # Iterate through prefixes seeing if value will be greater than
  2341. # 0 in each case
  2342. for index in 1..<prefixes.len:
  2343. lastXb = xb
  2344. xb = bytes div (1'i64 shl (index*10))
  2345. matchedIndex = index
  2346. if xb == 0:
  2347. xb = lastXb
  2348. matchedIndex = index - 1
  2349. break
  2350. # xb has the integer number for the latest value; index should be correct
  2351. fbytes = bytes.float / (1'i64 shl (matchedIndex*10)).float
  2352. result = formatFloat(fbytes, format = ffDecimal, precision = 3,
  2353. decimalSep = decimalSep)
  2354. result.trimZeros(decimalSep)
  2355. if includeSpace:
  2356. result &= " "
  2357. result &= prefixes[matchedIndex]
  2358. result &= "B"
  2359. func formatEng*(f: BiggestFloat,
  2360. precision: range[0..32] = 10,
  2361. trim: bool = true,
  2362. siPrefix: bool = false,
  2363. unit: string = "",
  2364. decimalSep = '.',
  2365. useUnitSpace = false): string =
  2366. ## Converts a floating point value `f` to a string using engineering notation.
  2367. ##
  2368. ## Numbers in of the range -1000.0<f<1000.0 will be formatted without an
  2369. ## exponent. Numbers outside of this range will be formatted as a
  2370. ## significand in the range -1000.0<f<1000.0 and an exponent that will always
  2371. ## be an integer multiple of 3, corresponding with the SI prefix scale k, M,
  2372. ## G, T etc for numbers with an absolute value greater than 1 and m, μ, n, p
  2373. ## etc for numbers with an absolute value less than 1.
  2374. ##
  2375. ## The default configuration (`trim=true` and `precision=10`) shows the
  2376. ## **shortest** form that precisely (up to a maximum of 10 decimal places)
  2377. ## displays the value. For example, 4.100000 will be displayed as 4.1 (which
  2378. ## is mathematically identical) whereas 4.1000003 will be displayed as
  2379. ## 4.1000003.
  2380. ##
  2381. ## If `trim` is set to true, trailing zeros will be removed; if false, the
  2382. ## number of digits specified by `precision` will always be shown.
  2383. ##
  2384. ## `precision` can be used to set the number of digits to be shown after the
  2385. ## decimal point or (if `trim` is true) the maximum number of digits to be
  2386. ## shown.
  2387. ##
  2388. ## .. code-block:: nim
  2389. ##
  2390. ## formatEng(0, 2, trim=false) == "0.00"
  2391. ## formatEng(0, 2) == "0"
  2392. ## formatEng(0.053, 0) == "53e-3"
  2393. ## formatEng(52731234, 2) == "52.73e6"
  2394. ## formatEng(-52731234, 2) == "-52.73e6"
  2395. ##
  2396. ## If `siPrefix` is set to true, the number will be displayed with the SI
  2397. ## prefix corresponding to the exponent. For example 4100 will be displayed
  2398. ## as "4.1 k" instead of "4.1e3". Note that `u` is used for micro- in place
  2399. ## of the greek letter mu (μ) as per ISO 2955. Numbers with an absolute
  2400. ## value outside of the range 1e-18<f<1000e18 (1a<f<1000E) will be displayed
  2401. ## with an exponent rather than an SI prefix, regardless of whether
  2402. ## `siPrefix` is true.
  2403. ##
  2404. ## If `useUnitSpace` is true, the provided unit will be appended to the string
  2405. ## (with a space as required by the SI standard). This behaviour is slightly
  2406. ## different to appending the unit to the result as the location of the space
  2407. ## is altered depending on whether there is an exponent.
  2408. ##
  2409. ## .. code-block:: nim
  2410. ##
  2411. ## formatEng(4100, siPrefix=true, unit="V") == "4.1 kV"
  2412. ## formatEng(4.1, siPrefix=true, unit="V") == "4.1 V"
  2413. ## formatEng(4.1, siPrefix=true) == "4.1" # Note lack of space
  2414. ## formatEng(4100, siPrefix=true) == "4.1 k"
  2415. ## formatEng(4.1, siPrefix=true, unit="") == "4.1 " # Space with unit=""
  2416. ## formatEng(4100, siPrefix=true, unit="") == "4.1 k"
  2417. ## formatEng(4100) == "4.1e3"
  2418. ## formatEng(4100, unit="V") == "4.1e3 V"
  2419. ## formatEng(4100, unit="", useUnitSpace=true) == "4.1e3 " # Space with useUnitSpace=true
  2420. ##
  2421. ## `decimalSep` is used as the decimal separator.
  2422. ##
  2423. ## See also:
  2424. ## * `strformat module<strformat.html>`_ for string interpolation and formatting
  2425. var
  2426. absolute: BiggestFloat
  2427. significand: BiggestFloat
  2428. fexponent: BiggestFloat
  2429. exponent: int
  2430. splitResult: seq[string]
  2431. suffix: string = ""
  2432. func getPrefix(exp: int): char =
  2433. ## Get the SI prefix for a given exponent
  2434. ##
  2435. ## Assumes exponent is a multiple of 3; returns ' ' if no prefix found
  2436. const siPrefixes = ['a', 'f', 'p', 'n', 'u', 'm', ' ', 'k', 'M', 'G', 'T',
  2437. 'P', 'E']
  2438. var index: int = (exp div 3) + 6
  2439. result = ' '
  2440. if index in low(siPrefixes)..high(siPrefixes):
  2441. result = siPrefixes[index]
  2442. # Most of the work is done with the sign ignored, so get the absolute value
  2443. absolute = abs(f)
  2444. significand = f
  2445. if absolute == 0.0:
  2446. # Simple case: just format it and force the exponent to 0
  2447. exponent = 0
  2448. result = significand.formatBiggestFloat(ffDecimal, precision,
  2449. decimalSep = '.')
  2450. else:
  2451. # Find the best exponent that's a multiple of 3
  2452. fexponent = floor(log10(absolute))
  2453. fexponent = 3.0 * floor(fexponent / 3.0)
  2454. # Adjust the significand for the new exponent
  2455. significand /= pow(10.0, fexponent)
  2456. # Adjust the significand and check whether it has affected
  2457. # the exponent
  2458. absolute = abs(significand)
  2459. if absolute >= 1000.0:
  2460. significand *= 0.001
  2461. fexponent += 3
  2462. # Components of the result:
  2463. result = significand.formatBiggestFloat(ffDecimal, precision,
  2464. decimalSep = '.')
  2465. exponent = fexponent.int()
  2466. splitResult = result.split('.')
  2467. result = splitResult[0]
  2468. # result should have at most one decimal character
  2469. if splitResult.len() > 1:
  2470. # If trim is set, we get rid of trailing zeros. Don't use trimZeros here as
  2471. # we can be a bit more efficient through knowledge that there will never be
  2472. # an exponent in this part.
  2473. if trim:
  2474. while splitResult[1].endsWith("0"):
  2475. # Trim last character
  2476. splitResult[1].setLen(splitResult[1].len-1)
  2477. if splitResult[1].len() > 0:
  2478. result &= decimalSep & splitResult[1]
  2479. else:
  2480. result &= decimalSep & splitResult[1]
  2481. # Combine the results accordingly
  2482. if siPrefix and exponent != 0:
  2483. var p = getPrefix(exponent)
  2484. if p != ' ':
  2485. suffix = " " & p
  2486. exponent = 0 # Exponent replaced by SI prefix
  2487. if suffix == "" and useUnitSpace:
  2488. suffix = " "
  2489. suffix &= unit
  2490. if exponent != 0:
  2491. result &= "e" & $exponent
  2492. result &= suffix
  2493. func findNormalized(x: string, inArray: openArray[string]): int =
  2494. var i = 0
  2495. while i < high(inArray):
  2496. if cmpIgnoreStyle(x, inArray[i]) == 0: return i
  2497. inc(i, 2) # incrementing by 1 would probably lead to a
  2498. # security hole...
  2499. return -1
  2500. func invalidFormatString(formatstr: string) {.noinline.} =
  2501. raise newException(ValueError, "invalid format string: " & formatstr)
  2502. func addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {.rtl,
  2503. extern: "nsuAddf".} =
  2504. ## The same as `add(s, formatstr % a)`, but more efficient.
  2505. const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'}
  2506. var i = 0
  2507. var num = 0
  2508. while i < len(formatstr):
  2509. if formatstr[i] == '$' and i+1 < len(formatstr):
  2510. case formatstr[i+1]
  2511. of '#':
  2512. if num > a.high: invalidFormatString(formatstr)
  2513. add s, a[num]
  2514. inc i, 2
  2515. inc num
  2516. of '$':
  2517. add s, '$'
  2518. inc(i, 2)
  2519. of '1'..'9', '-':
  2520. var j = 0
  2521. inc(i) # skip $
  2522. var negative = formatstr[i] == '-'
  2523. if negative: inc i
  2524. while i < formatstr.len and formatstr[i] in Digits:
  2525. j = j * 10 + ord(formatstr[i]) - ord('0')
  2526. inc(i)
  2527. let idx = if not negative: j-1 else: a.len-j
  2528. if idx < 0 or idx > a.high: invalidFormatString(formatstr)
  2529. add s, a[idx]
  2530. of '{':
  2531. var j = i+2
  2532. var k = 0
  2533. var negative = formatstr[j] == '-'
  2534. if negative: inc j
  2535. var isNumber = 0
  2536. while j < formatstr.len and formatstr[j] notin {'\0', '}'}:
  2537. if formatstr[j] in Digits:
  2538. k = k * 10 + ord(formatstr[j]) - ord('0')
  2539. if isNumber == 0: isNumber = 1
  2540. else:
  2541. isNumber = -1
  2542. inc(j)
  2543. if isNumber == 1:
  2544. let idx = if not negative: k-1 else: a.len-k
  2545. if idx < 0 or idx > a.high: invalidFormatString(formatstr)
  2546. add s, a[idx]
  2547. else:
  2548. var x = findNormalized(substr(formatstr, i+2, j-1), a)
  2549. if x >= 0 and x < high(a): add s, a[x+1]
  2550. else: invalidFormatString(formatstr)
  2551. i = j+1
  2552. of 'a'..'z', 'A'..'Z', '\128'..'\255', '_':
  2553. var j = i+1
  2554. while j < formatstr.len and formatstr[j] in PatternChars: inc(j)
  2555. var x = findNormalized(substr(formatstr, i+1, j-1), a)
  2556. if x >= 0 and x < high(a): add s, a[x+1]
  2557. else: invalidFormatString(formatstr)
  2558. i = j
  2559. else:
  2560. invalidFormatString(formatstr)
  2561. else:
  2562. add s, formatstr[i]
  2563. inc(i)
  2564. func `%`*(formatstr: string, a: openArray[string]): string {.rtl,
  2565. extern: "nsuFormatOpenArray".} =
  2566. ## Interpolates a format string with the values from `a`.
  2567. ##
  2568. ## The `substitution`:idx: operator performs string substitutions in
  2569. ## `formatstr` and returns a modified `formatstr`. This is often called
  2570. ## `string interpolation`:idx:.
  2571. ##
  2572. ## This is best explained by an example:
  2573. ##
  2574. ## .. code-block:: nim
  2575. ## "$1 eats $2." % ["The cat", "fish"]
  2576. ##
  2577. ## Results in:
  2578. ##
  2579. ## .. code-block:: nim
  2580. ## "The cat eats fish."
  2581. ##
  2582. ## The substitution variables (the thing after the `$`) are enumerated
  2583. ## from 1 to `a.len`.
  2584. ## To produce a verbatim `$`, use `$$`.
  2585. ## The notation `$#` can be used to refer to the next substitution
  2586. ## variable:
  2587. ##
  2588. ## .. code-block:: nim
  2589. ## "$# eats $#." % ["The cat", "fish"]
  2590. ##
  2591. ## Substitution variables can also be words (that is
  2592. ## `[A-Za-z_]+[A-Za-z0-9_]*`) in which case the arguments in `a` with even
  2593. ## indices are keys and with odd indices are the corresponding values.
  2594. ## An example:
  2595. ##
  2596. ## .. code-block:: nim
  2597. ## "$animal eats $food." % ["animal", "The cat", "food", "fish"]
  2598. ##
  2599. ## Results in:
  2600. ##
  2601. ## .. code-block:: nim
  2602. ## "The cat eats fish."
  2603. ##
  2604. ## The variables are compared with `cmpIgnoreStyle`. `ValueError` is
  2605. ## raised if an ill-formed format string has been passed to the `%` operator.
  2606. ##
  2607. ## See also:
  2608. ## * `strformat module<strformat.html>`_ for string interpolation and formatting
  2609. result = newStringOfCap(formatstr.len + a.len shl 4)
  2610. addf(result, formatstr, a)
  2611. func `%`*(formatstr, a: string): string {.rtl,
  2612. extern: "nsuFormatSingleElem".} =
  2613. ## This is the same as `formatstr % [a]` (see
  2614. ## `% func<#%25,string,openArray[string]>`_).
  2615. result = newStringOfCap(formatstr.len + a.len)
  2616. addf(result, formatstr, [a])
  2617. func format*(formatstr: string, a: varargs[string, `$`]): string {.rtl,
  2618. extern: "nsuFormatVarargs".} =
  2619. ## This is the same as `formatstr % a` (see
  2620. ## `% func<#%25,string,openArray[string]>`_) except that it supports
  2621. ## auto stringification.
  2622. ##
  2623. ## See also:
  2624. ## * `strformat module<strformat.html>`_ for string interpolation and formatting
  2625. result = newStringOfCap(formatstr.len + a.len)
  2626. addf(result, formatstr, a)
  2627. func strip*(s: string, leading = true, trailing = true,
  2628. chars: set[char] = Whitespace): string {.rtl, extern: "nsuStrip".} =
  2629. ## Strips leading or trailing `chars` (default: whitespace characters)
  2630. ## from `s` and returns the resulting string.
  2631. ##
  2632. ## If `leading` is true (default), leading `chars` are stripped.
  2633. ## If `trailing` is true (default), trailing `chars` are stripped.
  2634. ## If both are false, the string is returned unchanged.
  2635. ##
  2636. ## See also:
  2637. ## * `strip proc<strbasics.html#strip,string,set[char]>`_ Inplace version.
  2638. ## * `stripLineEnd func<#stripLineEnd,string>`_
  2639. runnableExamples:
  2640. let a = " vhellov "
  2641. let b = strip(a)
  2642. doAssert b == "vhellov"
  2643. doAssert a.strip(leading = false) == " vhellov"
  2644. doAssert a.strip(trailing = false) == "vhellov "
  2645. doAssert b.strip(chars = {'v'}) == "hello"
  2646. doAssert b.strip(leading = false, chars = {'v'}) == "vhello"
  2647. let c = "blaXbla"
  2648. doAssert c.strip(chars = {'b', 'a'}) == "laXbl"
  2649. doAssert c.strip(chars = {'b', 'a', 'l'}) == "X"
  2650. var
  2651. first = 0
  2652. last = len(s)-1
  2653. if leading:
  2654. while first <= last and s[first] in chars: inc(first)
  2655. if trailing:
  2656. while last >= first and s[last] in chars: dec(last)
  2657. result = substr(s, first, last)
  2658. func stripLineEnd*(s: var string) =
  2659. ## Strips one of these suffixes from `s` in-place:
  2660. ## `\r, \n, \r\n, \f, \v` (at most once instance).
  2661. ## For example, can be useful in conjunction with `osproc.execCmdEx`.
  2662. ## aka: `chomp`:idx:
  2663. runnableExamples:
  2664. var s = "foo\n\n"
  2665. s.stripLineEnd
  2666. doAssert s == "foo\n"
  2667. s = "foo\r\n"
  2668. s.stripLineEnd
  2669. doAssert s == "foo"
  2670. if s.len > 0:
  2671. case s[^1]
  2672. of '\n':
  2673. if s.len > 1 and s[^2] == '\r':
  2674. s.setLen s.len-2
  2675. else:
  2676. s.setLen s.len-1
  2677. of '\r', '\v', '\f':
  2678. s.setLen s.len-1
  2679. else:
  2680. discard
  2681. iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[
  2682. token: string, isSep: bool] =
  2683. ## Tokenizes the string `s` into substrings.
  2684. ##
  2685. ## Substrings are separated by a substring containing only `seps`.
  2686. ## Example:
  2687. ##
  2688. ## .. code-block:: nim
  2689. ## for word in tokenize(" this is an example "):
  2690. ## writeLine(stdout, word)
  2691. ##
  2692. ## Results in:
  2693. ##
  2694. ## .. code-block:: nim
  2695. ## (" ", true)
  2696. ## ("this", false)
  2697. ## (" ", true)
  2698. ## ("is", false)
  2699. ## (" ", true)
  2700. ## ("an", false)
  2701. ## (" ", true)
  2702. ## ("example", false)
  2703. ## (" ", true)
  2704. var i = 0
  2705. while true:
  2706. var j = i
  2707. var isSep = j < s.len and s[j] in seps
  2708. while j < s.len and (s[j] in seps) == isSep: inc(j)
  2709. if j > i:
  2710. yield (substr(s, i, j-1), isSep)
  2711. else:
  2712. break
  2713. i = j
  2714. func isEmptyOrWhitespace*(s: string): bool {.rtl,
  2715. extern: "nsuIsEmptyOrWhitespace".} =
  2716. ## Checks if `s` is empty or consists entirely of whitespace characters.
  2717. result = s.allCharsInSet(Whitespace)