strutils.nim 102 KB

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