strutils.nim 97 KB

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