strutils.nim 96 KB

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