strutils.nim 99 KB

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