unicode.nim 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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. ## This module provides support to handle the Unicode UTF-8 encoding.
  10. ##
  11. ## There are no specialized ``insert``, ``delete``, ``add`` and ``contains``
  12. ## procedures for ``seq[Rune]`` in this module because the generic variants
  13. ## of these procedures in the system module already work with it.
  14. ##
  15. ## The current version is compatible with Unicode v12.0.0.
  16. ##
  17. ## **See also:**
  18. ## * `strutils module <strutils.html>`_
  19. ## * `unidecode module <unidecode.html>`_
  20. ## * `encodings module <encodings.html>`_
  21. include "system/inclrtl"
  22. import std/strbasics
  23. template toOa(s: string): auto = s.toOpenArray(0, s.high)
  24. proc substr(s: openArray[char] , first, last: int): string =
  25. # Copied substr from system
  26. let first = max(first, 0)
  27. let L = max(min(last, high(s)) - first + 1, 0)
  28. result = newString(L)
  29. for i in 0 .. L-1:
  30. result[i] = s[i+first]
  31. type
  32. RuneImpl = int32 # underlying type of Rune
  33. Rune* = distinct RuneImpl ## \
  34. ## Type that can hold a single Unicode code point.
  35. ##
  36. ## A Rune may be composed with other Runes to a character on the screen.
  37. ## `RuneImpl` is the underlying type used to store Runes, currently `int32`.
  38. template ones(n: untyped): untyped = ((1 shl n)-1)
  39. proc runeLen*(s: openArray[char]): int {.rtl, extern: "nuc$1".} =
  40. ## Returns the number of runes of the string ``s``.
  41. runnableExamples:
  42. let a = "añyóng"
  43. doAssert a.runeLen == 6
  44. ## note: a.len == 8
  45. result = 0
  46. var i = 0
  47. while i < len(s):
  48. if uint(s[i]) <= 127: inc(i)
  49. elif uint(s[i]) shr 5 == 0b110: inc(i, 2)
  50. elif uint(s[i]) shr 4 == 0b1110: inc(i, 3)
  51. elif uint(s[i]) shr 3 == 0b11110: inc(i, 4)
  52. elif uint(s[i]) shr 2 == 0b111110: inc(i, 5)
  53. elif uint(s[i]) shr 1 == 0b1111110: inc(i, 6)
  54. else: inc i
  55. inc(result)
  56. proc runeLenAt*(s: openArray[char], i: Natural): int =
  57. ## Returns the number of bytes the rune starting at ``s[i]`` takes.
  58. ##
  59. ## See also:
  60. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  61. runnableExamples:
  62. let a = "añyóng"
  63. doAssert a.runeLenAt(0) == 1
  64. doAssert a.runeLenAt(1) == 2
  65. if uint(s[i]) <= 127: result = 1
  66. elif uint(s[i]) shr 5 == 0b110: result = 2
  67. elif uint(s[i]) shr 4 == 0b1110: result = 3
  68. elif uint(s[i]) shr 3 == 0b11110: result = 4
  69. elif uint(s[i]) shr 2 == 0b111110: result = 5
  70. elif uint(s[i]) shr 1 == 0b1111110: result = 6
  71. else: result = 1
  72. const replRune = Rune(0xFFFD)
  73. template fastRuneAt*(s: openArray[char] or string, i: int, result: untyped, doInc = true) =
  74. ## Returns the rune ``s[i]`` in ``result``.
  75. ##
  76. ## If ``doInc == true`` (default), ``i`` is incremented by the number
  77. ## of bytes that have been processed.
  78. bind ones
  79. if uint(s[i]) <= 127:
  80. result = Rune(uint(s[i]))
  81. when doInc: inc(i)
  82. elif uint(s[i]) shr 5 == 0b110:
  83. # assert(uint(s[i+1]) shr 6 == 0b10)
  84. if i <= s.len - 2:
  85. result = Rune((uint(s[i]) and (ones(5))) shl 6 or
  86. (uint(s[i+1]) and ones(6)))
  87. when doInc: inc(i, 2)
  88. else:
  89. result = replRune
  90. when doInc: inc(i)
  91. elif uint(s[i]) shr 4 == 0b1110:
  92. # assert(uint(s[i+1]) shr 6 == 0b10)
  93. # assert(uint(s[i+2]) shr 6 == 0b10)
  94. if i <= s.len - 3:
  95. result = Rune((uint(s[i]) and ones(4)) shl 12 or
  96. (uint(s[i+1]) and ones(6)) shl 6 or
  97. (uint(s[i+2]) and ones(6)))
  98. when doInc: inc(i, 3)
  99. else:
  100. result = replRune
  101. when doInc: inc(i)
  102. elif uint(s[i]) shr 3 == 0b11110:
  103. # assert(uint(s[i+1]) shr 6 == 0b10)
  104. # assert(uint(s[i+2]) shr 6 == 0b10)
  105. # assert(uint(s[i+3]) shr 6 == 0b10)
  106. if i <= s.len - 4:
  107. result = Rune((uint(s[i]) and ones(3)) shl 18 or
  108. (uint(s[i+1]) and ones(6)) shl 12 or
  109. (uint(s[i+2]) and ones(6)) shl 6 or
  110. (uint(s[i+3]) and ones(6)))
  111. when doInc: inc(i, 4)
  112. else:
  113. result = replRune
  114. when doInc: inc(i)
  115. elif uint(s[i]) shr 2 == 0b111110:
  116. # assert(uint(s[i+1]) shr 6 == 0b10)
  117. # assert(uint(s[i+2]) shr 6 == 0b10)
  118. # assert(uint(s[i+3]) shr 6 == 0b10)
  119. # assert(uint(s[i+4]) shr 6 == 0b10)
  120. if i <= s.len - 5:
  121. result = Rune((uint(s[i]) and ones(2)) shl 24 or
  122. (uint(s[i+1]) and ones(6)) shl 18 or
  123. (uint(s[i+2]) and ones(6)) shl 12 or
  124. (uint(s[i+3]) and ones(6)) shl 6 or
  125. (uint(s[i+4]) and ones(6)))
  126. when doInc: inc(i, 5)
  127. else:
  128. result = replRune
  129. when doInc: inc(i)
  130. elif uint(s[i]) shr 1 == 0b1111110:
  131. # assert(uint(s[i+1]) shr 6 == 0b10)
  132. # assert(uint(s[i+2]) shr 6 == 0b10)
  133. # assert(uint(s[i+3]) shr 6 == 0b10)
  134. # assert(uint(s[i+4]) shr 6 == 0b10)
  135. # assert(uint(s[i+5]) shr 6 == 0b10)
  136. if i <= s.len - 6:
  137. result = Rune((uint(s[i]) and ones(1)) shl 30 or
  138. (uint(s[i+1]) and ones(6)) shl 24 or
  139. (uint(s[i+2]) and ones(6)) shl 18 or
  140. (uint(s[i+3]) and ones(6)) shl 12 or
  141. (uint(s[i+4]) and ones(6)) shl 6 or
  142. (uint(s[i+5]) and ones(6)))
  143. when doInc: inc(i, 6)
  144. else:
  145. result = replRune
  146. when doInc: inc(i)
  147. else:
  148. result = Rune(uint(s[i]))
  149. when doInc: inc(i)
  150. proc runeAt*(s: openArray[char], i: Natural): Rune =
  151. ## Returns the rune in ``s`` at **byte index** ``i``.
  152. ##
  153. ## See also:
  154. ## * `runeAtPos proc <#runeAtPos,string,int>`_
  155. ## * `runeStrAtPos proc <#runeStrAtPos,string,Natural>`_
  156. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  157. runnableExamples:
  158. let a = "añyóng"
  159. doAssert a.runeAt(1) == "ñ".runeAt(0)
  160. doAssert a.runeAt(2) == "ñ".runeAt(1)
  161. doAssert a.runeAt(3) == "y".runeAt(0)
  162. fastRuneAt(s, i, result, false)
  163. proc validateUtf8*(s: openArray[char]): int =
  164. ## Returns the position of the invalid byte in ``s`` if the string ``s`` does
  165. ## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
  166. ##
  167. ## See also:
  168. ## * `toUTF8 proc <#toUTF8,Rune>`_
  169. ## * `$ proc <#$,Rune>`_ alias for `toUTF8`
  170. ## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
  171. var i = 0
  172. let L = s.len
  173. while i < L:
  174. if uint(s[i]) <= 127:
  175. inc(i)
  176. elif uint(s[i]) shr 5 == 0b110:
  177. if uint(s[i]) < 0xc2: return i # Catch overlong ascii representations.
  178. if i+1 < L and uint(s[i+1]) shr 6 == 0b10: inc(i, 2)
  179. else: return i
  180. elif uint(s[i]) shr 4 == 0b1110:
  181. if i+2 < L and uint(s[i+1]) shr 6 == 0b10 and uint(s[i+2]) shr 6 == 0b10:
  182. inc i, 3
  183. else: return i
  184. elif uint(s[i]) shr 3 == 0b11110:
  185. if i+3 < L and uint(s[i+1]) shr 6 == 0b10 and
  186. uint(s[i+2]) shr 6 == 0b10 and
  187. uint(s[i+3]) shr 6 == 0b10:
  188. inc i, 4
  189. else: return i
  190. else:
  191. return i
  192. return -1
  193. template fastToUTF8Copy*(c: Rune, s: var string, pos: int, doInc = true) =
  194. ## Copies UTF-8 representation of ``c`` into the preallocated string ``s``
  195. ## starting at position ``pos``.
  196. ##
  197. ## If ``doInc == true`` (default), ``pos`` is incremented
  198. ## by the number of bytes that have been processed.
  199. ##
  200. ## To be the most efficient, make sure ``s`` is preallocated
  201. ## with an additional amount equal to the byte length of ``c``.
  202. ##
  203. ## See also:
  204. ## * `validateUtf8 proc <#validateUtf8,string>`_
  205. ## * `toUTF8 proc <#toUTF8,Rune>`_
  206. ## * `$ proc <#$,Rune>`_ alias for `toUTF8`
  207. var i = RuneImpl(c)
  208. if i <=% 127:
  209. s.setLen(pos+1)
  210. s[pos+0] = chr(i)
  211. when doInc: inc(pos)
  212. elif i <=% 0x07FF:
  213. s.setLen(pos+2)
  214. s[pos+0] = chr((i shr 6) or 0b110_00000)
  215. s[pos+1] = chr((i and ones(6)) or 0b10_0000_00)
  216. when doInc: inc(pos, 2)
  217. elif i <=% 0xFFFF:
  218. s.setLen(pos+3)
  219. s[pos+0] = chr(i shr 12 or 0b1110_0000)
  220. s[pos+1] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  221. s[pos+2] = chr(i and ones(6) or 0b10_0000_00)
  222. when doInc: inc(pos, 3)
  223. elif i <=% 0x001FFFFF:
  224. s.setLen(pos+4)
  225. s[pos+0] = chr(i shr 18 or 0b1111_0000)
  226. s[pos+1] = chr(i shr 12 and ones(6) or 0b10_0000_00)
  227. s[pos+2] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  228. s[pos+3] = chr(i and ones(6) or 0b10_0000_00)
  229. when doInc: inc(pos, 4)
  230. elif i <=% 0x03FFFFFF:
  231. s.setLen(pos+5)
  232. s[pos+0] = chr(i shr 24 or 0b111110_00)
  233. s[pos+1] = chr(i shr 18 and ones(6) or 0b10_0000_00)
  234. s[pos+2] = chr(i shr 12 and ones(6) or 0b10_0000_00)
  235. s[pos+3] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  236. s[pos+4] = chr(i and ones(6) or 0b10_0000_00)
  237. when doInc: inc(pos, 5)
  238. elif i <=% 0x7FFFFFFF:
  239. s.setLen(pos+6)
  240. s[pos+0] = chr(i shr 30 or 0b1111110_0)
  241. s[pos+1] = chr(i shr 24 and ones(6) or 0b10_0000_00)
  242. s[pos+2] = chr(i shr 18 and ones(6) or 0b10_0000_00)
  243. s[pos+3] = chr(i shr 12 and ones(6) or 0b10_0000_00)
  244. s[pos+4] = chr(i shr 6 and ones(6) or 0b10_0000_00)
  245. s[pos+5] = chr(i and ones(6) or 0b10_0000_00)
  246. when doInc: inc(pos, 6)
  247. else:
  248. discard # error, exception?
  249. proc toUTF8*(c: Rune): string {.rtl, extern: "nuc$1".} =
  250. ## Converts a rune into its UTF-8 representation.
  251. ##
  252. ## See also:
  253. ## * `validateUtf8 proc <#validateUtf8,string>`_
  254. ## * `$ proc <#$,Rune>`_ alias for `toUTF8`
  255. ## * `utf8 iterator <#utf8.i,string>`_
  256. ## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
  257. runnableExamples:
  258. let a = "añyóng"
  259. doAssert a.runeAt(1).toUTF8 == "ñ"
  260. result = ""
  261. fastToUTF8Copy(c, result, 0, false)
  262. proc add*(s: var string; c: Rune) =
  263. ## Adds a rune ``c`` to a string ``s``.
  264. runnableExamples:
  265. var s = "abc"
  266. let c = "ä".runeAt(0)
  267. s.add(c)
  268. doAssert s == "abcä"
  269. let pos = s.len
  270. fastToUTF8Copy(c, s, pos, false)
  271. proc `$`*(rune: Rune): string =
  272. ## An alias for `toUTF8 <#toUTF8,Rune>`_.
  273. ##
  274. ## See also:
  275. ## * `validateUtf8 proc <#validateUtf8,string>`_
  276. ## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
  277. rune.toUTF8
  278. proc `$`*(runes: seq[Rune]): string =
  279. ## Converts a sequence of Runes to a string.
  280. ##
  281. ## See also:
  282. ## * `toRunes <#toRunes,string>`_ for a reverse operation
  283. runnableExamples:
  284. let
  285. someString = "öÑ"
  286. someRunes = toRunes(someString)
  287. doAssert $someRunes == someString
  288. result = ""
  289. for rune in runes:
  290. result.add rune
  291. proc runeOffset*(s: openArray[char], pos: Natural, start: Natural = 0): int =
  292. ## Returns the byte position of rune
  293. ## at position ``pos`` in ``s`` with an optional start byte position.
  294. ## Returns the special value -1 if it runs out of the string.
  295. ##
  296. ## **Beware:** This can lead to unoptimized code and slow execution!
  297. ## Most problems can be solved more efficiently by using an iterator
  298. ## or conversion to a seq of Rune.
  299. ##
  300. ## See also:
  301. ## * `runeReverseOffset proc <#runeReverseOffset,string,Positive>`_
  302. runnableExamples:
  303. let a = "añyóng"
  304. doAssert a.runeOffset(1) == 1
  305. doAssert a.runeOffset(3) == 4
  306. doAssert a.runeOffset(4) == 6
  307. var
  308. i = 0
  309. o = start
  310. while i < pos:
  311. o += runeLenAt(s, o)
  312. if o >= s.len:
  313. return -1
  314. inc i
  315. return o
  316. proc runeReverseOffset*(s: openArray[char], rev: Positive): (int, int) =
  317. ## Returns a tuple with the byte offset of the
  318. ## rune at position ``rev`` in ``s``, counting
  319. ## from the end (starting with 1) and the total
  320. ## number of runes in the string.
  321. ##
  322. ## Returns a negative value for offset if there are too few runes in
  323. ## the string to satisfy the request.
  324. ##
  325. ## **Beware:** This can lead to unoptimized code and slow execution!
  326. ## Most problems can be solved more efficiently by using an iterator
  327. ## or conversion to a seq of Rune.
  328. ##
  329. ## See also:
  330. ## * `runeOffset proc <#runeOffset,string,Natural,Natural>`_
  331. var
  332. a = rev.int
  333. o = 0
  334. x = 0
  335. let times = 2*rev.int-s.runeLen # transformed from rev.int - a < s.runeLen - rev.int
  336. while o < s.len:
  337. let r = runeLenAt(s, o)
  338. o += r
  339. if a > times:
  340. x += r
  341. dec a
  342. result = if a > 0: (-a, rev.int-a) else: (x, -a+rev.int)
  343. proc runeAtPos*(s: openArray[char], pos: int): Rune =
  344. ## Returns the rune at position ``pos``.
  345. ##
  346. ## **Beware:** This can lead to unoptimized code and slow execution!
  347. ## Most problems can be solved more efficiently by using an iterator
  348. ## or conversion to a seq of Rune.
  349. ##
  350. ## See also:
  351. ## * `runeAt proc <#runeAt,string,Natural>`_
  352. ## * `runeStrAtPos proc <#runeStrAtPos,string,Natural>`_
  353. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  354. fastRuneAt(s, runeOffset(s, pos), result, false)
  355. proc runeStrAtPos*(s: openArray[char], pos: Natural): string =
  356. ## Returns the rune at position ``pos`` as UTF8 String.
  357. ##
  358. ## **Beware:** This can lead to unoptimized code and slow execution!
  359. ## Most problems can be solved more efficiently by using an iterator
  360. ## or conversion to a seq of Rune.
  361. ##
  362. ## See also:
  363. ## * `runeAt proc <#runeAt,string,Natural>`_
  364. ## * `runeAtPos proc <#runeAtPos,string,int>`_
  365. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  366. let o = runeOffset(s, pos)
  367. substr(s.toOpenArray(o, (o+runeLenAt(s, o)-1)))
  368. proc runeSubStr*(s: openArray[char], pos: int, len: int = int.high): string =
  369. ## Returns the UTF-8 substring starting at code point ``pos``
  370. ## with ``len`` code points.
  371. ##
  372. ## If ``pos`` or ``len`` is negative they count from
  373. ## the end of the string. If ``len`` is not given it means the longest
  374. ## possible string.
  375. runnableExamples:
  376. let s = "Hänsel ««: 10,00€"
  377. doAssert(runeSubStr(s, 0, 2) == "Hä")
  378. doAssert(runeSubStr(s, 10, 1) == ":")
  379. doAssert(runeSubStr(s, -6) == "10,00€")
  380. doAssert(runeSubStr(s, 10) == ": 10,00€")
  381. doAssert(runeSubStr(s, 12, 5) == "10,00")
  382. doAssert(runeSubStr(s, -6, 3) == "10,")
  383. if pos < 0:
  384. let (o, rl) = runeReverseOffset(s, -pos)
  385. if len >= rl:
  386. result = s.substr(o, s.high)
  387. elif len < 0:
  388. let e = rl + len
  389. if e < 0:
  390. result = ""
  391. else:
  392. result = s.substr(o, runeOffset(s, e-(rl+pos), o)-1)
  393. else:
  394. result = s.substr(o, runeOffset(s, len, o)-1)
  395. else:
  396. let o = runeOffset(s, pos)
  397. if o < 0:
  398. result = ""
  399. elif len == int.high:
  400. result = s.substr(o, s.len-1)
  401. elif len < 0:
  402. let (e, rl) = runeReverseOffset(s, -len)
  403. discard rl
  404. if e <= 0:
  405. result = ""
  406. else:
  407. result = s.substr(o, e-1)
  408. else:
  409. var e = runeOffset(s, len, o)
  410. if e < 0:
  411. e = s.len
  412. result = s.substr(o, e-1)
  413. proc `<=%`*(a, b: Rune): bool =
  414. ## Checks if code point of `a` is smaller or equal to code point of `b`.
  415. runnableExamples:
  416. let
  417. a = "ú".runeAt(0)
  418. b = "ü".runeAt(0)
  419. doAssert a <=% b
  420. return int(a) <=% int(b)
  421. proc `<%`*(a, b: Rune): bool =
  422. ## Checks if code point of `a` is smaller than code point of `b`.
  423. runnableExamples:
  424. let
  425. a = "ú".runeAt(0)
  426. b = "ü".runeAt(0)
  427. doAssert a <% b
  428. return int(a) <% int(b)
  429. proc `==`*(a, b: Rune): bool =
  430. ## Checks if two runes are equal.
  431. return int(a) == int(b)
  432. include "includes/unicode_ranges"
  433. proc binarySearch(c: RuneImpl, tab: openArray[int32], len, stride: int): int =
  434. var n = len
  435. var t = 0
  436. while n > 1:
  437. var m = n div 2
  438. var p = t + m*stride
  439. if c >= tab[p]:
  440. t = p
  441. n = n-m
  442. else:
  443. n = m
  444. if n != 0 and c >= tab[t]:
  445. return t
  446. return -1
  447. proc toLower*(c: Rune): Rune {.rtl, extern: "nuc$1".} =
  448. ## Converts ``c`` into lower case. This works for any rune.
  449. ##
  450. ## If possible, prefer ``toLower`` over ``toUpper``.
  451. ##
  452. ## See also:
  453. ## * `toUpper proc <#toUpper,Rune>`_
  454. ## * `toTitle proc <#toTitle,Rune>`_
  455. ## * `isLower proc <#isLower,Rune>`_
  456. var c = RuneImpl(c)
  457. var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
  458. if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
  459. return Rune(c + toLowerRanges[p+2] - 500)
  460. p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
  461. if p >= 0 and c == toLowerSinglets[p]:
  462. return Rune(c + toLowerSinglets[p+1] - 500)
  463. return Rune(c)
  464. proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1".} =
  465. ## Converts ``c`` into upper case. This works for any rune.
  466. ##
  467. ## If possible, prefer ``toLower`` over ``toUpper``.
  468. ##
  469. ## See also:
  470. ## * `toLower proc <#toLower,Rune>`_
  471. ## * `toTitle proc <#toTitle,Rune>`_
  472. ## * `isUpper proc <#isUpper,Rune>`_
  473. var c = RuneImpl(c)
  474. var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
  475. if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
  476. return Rune(c + toUpperRanges[p+2] - 500)
  477. p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
  478. if p >= 0 and c == toUpperSinglets[p]:
  479. return Rune(c + toUpperSinglets[p+1] - 500)
  480. return Rune(c)
  481. proc toTitle*(c: Rune): Rune {.rtl, extern: "nuc$1".} =
  482. ## Converts ``c`` to title case.
  483. ##
  484. ## See also:
  485. ## * `toLower proc <#toLower,Rune>`_
  486. ## * `toUpper proc <#toUpper,Rune>`_
  487. ## * `isTitle proc <#isTitle,Rune>`_
  488. var c = RuneImpl(c)
  489. var p = binarySearch(c, toTitleSinglets, len(toTitleSinglets) div 2, 2)
  490. if p >= 0 and c == toTitleSinglets[p]:
  491. return Rune(c + toTitleSinglets[p+1] - 500)
  492. return Rune(c)
  493. proc isLower*(c: Rune): bool {.rtl, extern: "nuc$1".} =
  494. ## Returns true if ``c`` is a lower case rune.
  495. ##
  496. ## If possible, prefer ``isLower`` over ``isUpper``.
  497. ##
  498. ## See also:
  499. ## * `toLower proc <#toLower,Rune>`_
  500. ## * `isUpper proc <#isUpper,Rune>`_
  501. ## * `isTitle proc <#isTitle,Rune>`_
  502. var c = RuneImpl(c)
  503. # Note: toUpperRanges is correct here!
  504. var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
  505. if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
  506. return true
  507. p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
  508. if p >= 0 and c == toUpperSinglets[p]:
  509. return true
  510. proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1".} =
  511. ## Returns true if ``c`` is a upper case rune.
  512. ##
  513. ## If possible, prefer ``isLower`` over ``isUpper``.
  514. ##
  515. ## See also:
  516. ## * `toUpper proc <#toUpper,Rune>`_
  517. ## * `isLower proc <#isLower,Rune>`_
  518. ## * `isTitle proc <#isTitle,Rune>`_
  519. ## * `isAlpha proc <#isAlpha,Rune>`_
  520. ## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
  521. var c = RuneImpl(c)
  522. # Note: toLowerRanges is correct here!
  523. var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
  524. if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
  525. return true
  526. p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
  527. if p >= 0 and c == toLowerSinglets[p]:
  528. return true
  529. proc isAlpha*(c: Rune): bool {.rtl, extern: "nuc$1".} =
  530. ## Returns true if ``c`` is an *alpha* rune (i.e., a letter).
  531. ##
  532. ## See also:
  533. ## * `isLower proc <#isLower,Rune>`_
  534. ## * `isTitle proc <#isTitle,Rune>`_
  535. ## * `isAlpha proc <#isAlpha,Rune>`_
  536. ## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
  537. ## * `isCombining proc <#isCombining,Rune>`_
  538. if isUpper(c) or isLower(c):
  539. return true
  540. var c = RuneImpl(c)
  541. var p = binarySearch(c, alphaRanges, len(alphaRanges) div 2, 2)
  542. if p >= 0 and c >= alphaRanges[p] and c <= alphaRanges[p+1]:
  543. return true
  544. p = binarySearch(c, alphaSinglets, len(alphaSinglets), 1)
  545. if p >= 0 and c == alphaSinglets[p]:
  546. return true
  547. proc isTitle*(c: Rune): bool {.rtl, extern: "nuc$1".} =
  548. ## Returns true if ``c`` is a Unicode titlecase code point.
  549. ##
  550. ## See also:
  551. ## * `toTitle proc <#toTitle,Rune>`_
  552. ## * `isLower proc <#isLower,Rune>`_
  553. ## * `isUpper proc <#isUpper,Rune>`_
  554. ## * `isAlpha proc <#isAlpha,Rune>`_
  555. ## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
  556. return isUpper(c) and isLower(c)
  557. proc isWhiteSpace*(c: Rune): bool {.rtl, extern: "nuc$1".} =
  558. ## Returns true if ``c`` is a Unicode whitespace code point.
  559. ##
  560. ## See also:
  561. ## * `isLower proc <#isLower,Rune>`_
  562. ## * `isUpper proc <#isUpper,Rune>`_
  563. ## * `isTitle proc <#isTitle,Rune>`_
  564. ## * `isAlpha proc <#isAlpha,Rune>`_
  565. var c = RuneImpl(c)
  566. var p = binarySearch(c, spaceRanges, len(spaceRanges) div 2, 2)
  567. if p >= 0 and c >= spaceRanges[p] and c <= spaceRanges[p+1]:
  568. return true
  569. proc isCombining*(c: Rune): bool {.rtl, extern: "nuc$1".} =
  570. ## Returns true if ``c`` is a Unicode combining code unit.
  571. ##
  572. ## See also:
  573. ## * `isLower proc <#isLower,Rune>`_
  574. ## * `isUpper proc <#isUpper,Rune>`_
  575. ## * `isTitle proc <#isTitle,Rune>`_
  576. ## * `isAlpha proc <#isAlpha,Rune>`_
  577. var c = RuneImpl(c)
  578. # Optimized to return false immediately for ASCII
  579. return c >= 0x0300 and (c <= 0x036f or
  580. (c >= 0x1ab0 and c <= 0x1aff) or
  581. (c >= 0x1dc0 and c <= 0x1dff) or
  582. (c >= 0x20d0 and c <= 0x20ff) or
  583. (c >= 0xfe20 and c <= 0xfe2f))
  584. template runeCheck(s, runeProc) =
  585. ## Common code for isAlpha and isSpace.
  586. result = if len(s) == 0: false else: true
  587. var
  588. i = 0
  589. rune: Rune
  590. while i < len(s) and result:
  591. fastRuneAt(s, i, rune, doInc = true)
  592. result = runeProc(rune) and result
  593. proc isAlpha*(s: openArray[char]): bool {.noSideEffect,
  594. rtl, extern: "nuc$1Str".} =
  595. ## Returns true if ``s`` contains all alphabetic runes.
  596. runnableExamples:
  597. let a = "añyóng"
  598. doAssert a.isAlpha
  599. runeCheck(s, isAlpha)
  600. proc isSpace*(s: openArray[char]): bool {.noSideEffect,
  601. rtl, extern: "nuc$1Str".} =
  602. ## Returns true if ``s`` contains all whitespace runes.
  603. runnableExamples:
  604. let a = "\t\l \v\r\f"
  605. doAssert a.isSpace
  606. runeCheck(s, isWhiteSpace)
  607. template convertRune(s, runeProc) =
  608. ## Convert runes in ``s`` using ``runeProc`` as the converter.
  609. result = newString(len(s))
  610. var
  611. i = 0
  612. resultIndex = 0
  613. rune: Rune
  614. while i < len(s):
  615. fastRuneAt(s, i, rune, doInc = true)
  616. rune = runeProc(rune)
  617. fastToUTF8Copy(rune, result, resultIndex, doInc = true)
  618. proc toUpper*(s: openArray[char]): string {.noSideEffect,
  619. rtl, extern: "nuc$1Str".} =
  620. ## Converts ``s`` into upper-case runes.
  621. runnableExamples:
  622. doAssert toUpper("abγ") == "ABΓ"
  623. convertRune(s, toUpper)
  624. proc toLower*(s: openArray[char]): string {.noSideEffect,
  625. rtl, extern: "nuc$1Str".} =
  626. ## Converts ``s`` into lower-case runes.
  627. runnableExamples:
  628. doAssert toLower("ABΓ") == "abγ"
  629. convertRune(s, toLower)
  630. proc swapCase*(s: openArray[char]): string {.noSideEffect,
  631. rtl, extern: "nuc$1".} =
  632. ## Swaps the case of runes in ``s``.
  633. ##
  634. ## Returns a new string such that the cases of all runes
  635. ## are swapped if possible.
  636. runnableExamples:
  637. doAssert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA"
  638. var
  639. i = 0
  640. resultIndex = 0
  641. rune: Rune
  642. result = newString(len(s))
  643. while i < len(s):
  644. fastRuneAt(s, i, rune)
  645. if rune.isUpper():
  646. rune = rune.toLower()
  647. elif rune.isLower():
  648. rune = rune.toUpper()
  649. fastToUTF8Copy(rune, result, resultIndex, doInc = true)
  650. proc capitalize*(s: openArray[char]): string {.noSideEffect,
  651. rtl, extern: "nuc$1".} =
  652. ## Converts the first character of ``s`` into an upper-case rune.
  653. runnableExamples:
  654. doAssert capitalize("βeta") == "Βeta"
  655. if len(s) == 0:
  656. return ""
  657. var
  658. rune: Rune
  659. i = 0
  660. fastRuneAt(s, i, rune, doInc = true)
  661. result = $toUpper(rune) & substr(s.toOpenArray(i, s.high))
  662. when not defined(nimHasEffectsOf):
  663. {.pragma: effectsOf.}
  664. proc translate*(s: openArray[char], replacements: proc(key: string): string): string {.
  665. rtl, extern: "nuc$1", effectsOf: replacements.} =
  666. ## Translates words in a string using the ``replacements`` proc to substitute
  667. ## words inside ``s`` with their replacements.
  668. ##
  669. ## ``replacements`` is any proc that takes a word and returns
  670. ## a new word to fill it's place.
  671. runnableExamples:
  672. proc wordToNumber(s: string): string =
  673. case s
  674. of "one": "1"
  675. of "two": "2"
  676. else: s
  677. let a = "one two three four"
  678. doAssert a.translate(wordToNumber) == "1 2 three four"
  679. # Allocate memory for the new string based on the old one.
  680. # If the new string length is less than the old, no allocations
  681. # will be needed. If the new string length is greater than the
  682. # old, then maybe only one allocation is needed
  683. result = newStringOfCap(s.len)
  684. var
  685. index = 0
  686. lastIndex = 0
  687. wordStart = 0
  688. inWord = false
  689. rune: Rune
  690. while index < len(s):
  691. lastIndex = index
  692. fastRuneAt(s, index, rune)
  693. let whiteSpace = rune.isWhiteSpace()
  694. if whiteSpace and inWord:
  695. # If we've reached the end of a word
  696. let word = substr(s.toOpenArray(wordStart, lastIndex - 1))
  697. result.add(replacements(word))
  698. result.add($rune)
  699. inWord = false
  700. elif not whiteSpace and not inWord:
  701. # If we've hit a non space character and
  702. # are not currently in a word, track
  703. # the starting index of the word
  704. inWord = true
  705. wordStart = lastIndex
  706. elif whiteSpace:
  707. result.add($rune)
  708. if wordStart < len(s) and inWord:
  709. # Get the trailing word at the end
  710. let word = substr(s.toOpenArray(wordStart, s.high))
  711. result.add(replacements(word))
  712. proc title*(s: openArray[char]): string {.noSideEffect,
  713. rtl, extern: "nuc$1".} =
  714. ## Converts ``s`` to a unicode title.
  715. ##
  716. ## Returns a new string such that the first character
  717. ## in each word inside ``s`` is capitalized.
  718. runnableExamples:
  719. doAssert title("αlpha βeta γamma") == "Αlpha Βeta Γamma"
  720. var
  721. i = 0
  722. resultIndex = 0
  723. rune: Rune
  724. result = newString(len(s))
  725. var firstRune = true
  726. while i < len(s):
  727. fastRuneAt(s, i, rune)
  728. if not rune.isWhiteSpace() and firstRune:
  729. rune = rune.toUpper()
  730. firstRune = false
  731. elif rune.isWhiteSpace():
  732. firstRune = true
  733. fastToUTF8Copy(rune, result, resultIndex, doInc = true)
  734. iterator runes*(s: openArray[char]): Rune =
  735. ## Iterates over any rune of the string ``s`` returning runes.
  736. var
  737. i = 0
  738. result: Rune
  739. while i < len(s):
  740. fastRuneAt(s, i, result, true)
  741. yield result
  742. iterator utf8*(s: openArray[char]): string =
  743. ## Iterates over any rune of the string ``s`` returning utf8 values.
  744. ##
  745. ## See also:
  746. ## * `validateUtf8 proc <#validateUtf8,string>`_
  747. ## * `toUTF8 proc <#toUTF8,Rune>`_
  748. ## * `$ proc <#$,Rune>`_ alias for `toUTF8`
  749. ## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
  750. var o = 0
  751. while o < s.len:
  752. let n = runeLenAt(s, o)
  753. yield substr(s.toOpenArray(o, (o+n-1)))
  754. o += n
  755. proc toRunes*(s: openArray[char]): seq[Rune] =
  756. ## Obtains a sequence containing the Runes in ``s``.
  757. ##
  758. ## See also:
  759. ## * `$ proc <#$,Rune>`_ for a reverse operation
  760. runnableExamples:
  761. let a = toRunes("aáä")
  762. doAssert a == @["a".runeAt(0), "á".runeAt(0), "ä".runeAt(0)]
  763. result = newSeq[Rune]()
  764. for r in s.runes:
  765. result.add(r)
  766. proc cmpRunesIgnoreCase*(a, b: openArray[char]): int {.rtl, extern: "nuc$1".} =
  767. ## Compares two UTF-8 strings and ignores the case. Returns:
  768. ##
  769. ## | `0` if a == b
  770. ## | `< 0` if a < b
  771. ## | `> 0` if a > b
  772. var i = 0
  773. var j = 0
  774. var ar, br: Rune
  775. while i < a.len and j < b.len:
  776. # slow path:
  777. fastRuneAt(a, i, ar)
  778. fastRuneAt(b, j, br)
  779. when sizeof(int) < 4:
  780. const lo = low(int).int32
  781. const hi = high(int).int32
  782. result = clamp(RuneImpl(toLower(ar)) - RuneImpl(toLower(br)), lo, hi).int
  783. else:
  784. result = RuneImpl(toLower(ar)) - RuneImpl(toLower(br))
  785. if result != 0: return
  786. result = a.len - b.len
  787. proc reversed*(s: openArray[char]): string =
  788. ## Returns the reverse of ``s``, interpreting it as runes.
  789. ##
  790. ## Unicode combining characters are correctly interpreted as well.
  791. runnableExamples:
  792. assert reversed("Reverse this!") == "!siht esreveR"
  793. assert reversed("先秦兩漢") == "漢兩秦先"
  794. assert reversed("as⃝df̅") == "f̅ds⃝a"
  795. assert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞"
  796. var
  797. i = 0
  798. lastI = 0
  799. newPos = len(s) - 1
  800. blockPos = 0
  801. r: Rune
  802. template reverseUntil(pos) =
  803. var j = pos - 1
  804. while j > blockPos:
  805. result[newPos] = s[j]
  806. dec j
  807. dec newPos
  808. blockPos = pos - 1
  809. result = newString(len(s))
  810. while i < len(s):
  811. lastI = i
  812. fastRuneAt(s, i, r, true)
  813. if not isCombining(r):
  814. reverseUntil(lastI)
  815. reverseUntil(len(s))
  816. proc graphemeLen*(s: openArray[char]; i: Natural): Natural =
  817. ## The number of bytes belonging to byte index ``s[i]``,
  818. ## including following combining code units.
  819. runnableExamples:
  820. let a = "añyóng"
  821. doAssert a.graphemeLen(1) == 2 ## ñ
  822. doAssert a.graphemeLen(2) == 1
  823. doAssert a.graphemeLen(4) == 2 ## ó
  824. var j = i.int
  825. var r, r2: Rune
  826. if j < s.len:
  827. fastRuneAt(s, j, r, true)
  828. result = j-i
  829. while j < s.len:
  830. fastRuneAt(s, j, r2, true)
  831. if not isCombining(r2): break
  832. result = j-i
  833. proc lastRune*(s: openArray[char]; last: int): (Rune, int) =
  834. ## Length of the last rune in ``s[0..last]``. Returns the rune and its length
  835. ## in bytes.
  836. if s[last] <= chr(127):
  837. result = (Rune(s[last]), 1)
  838. else:
  839. var L = 0
  840. while last-L >= 0 and uint(s[last-L]) shr 6 == 0b10: inc(L)
  841. var r: Rune
  842. fastRuneAt(s, last-L, r, false)
  843. result = (r, L+1)
  844. proc size*(r: Rune): int {.noSideEffect.} =
  845. ## Returns the number of bytes the rune ``r`` takes.
  846. runnableExamples:
  847. let a = toRunes "aá"
  848. doAssert size(a[0]) == 1
  849. doAssert size(a[1]) == 2
  850. let v = r.uint32
  851. if v <= 0x007F'u32: result = 1
  852. elif v <= 0x07FF'u32: result = 2
  853. elif v <= 0xFFFF'u32: result = 3
  854. elif v <= 0x1FFFFF'u32: result = 4
  855. elif v <= 0x3FFFFFF'u32: result = 5
  856. elif v <= 0x7FFFFFFF'u32: result = 6
  857. else: result = 1
  858. # --------- Private templates for different split separators -----------
  859. proc stringHasSep(s: openArray[char], index: int, seps: openArray[Rune]): bool =
  860. var rune: Rune
  861. fastRuneAt(s, index, rune, false)
  862. return seps.contains(rune)
  863. proc stringHasSep(s: openArray[char], index: int, sep: Rune): bool =
  864. var rune: Rune
  865. fastRuneAt(s, index, rune, false)
  866. return sep == rune
  867. template splitCommon(s, sep, maxsplit: untyped) =
  868. ## Common code for split procedures.
  869. let
  870. sLen = len(s)
  871. var
  872. last = 0
  873. splits = maxsplit
  874. if sLen > 0:
  875. while last <= sLen:
  876. var first = last
  877. while last < sLen and not stringHasSep(s, last, sep):
  878. inc(last, runeLenAt(s, last))
  879. if splits == 0: last = sLen
  880. yield substr(s.toOpenArray(first, (last - 1)))
  881. if splits == 0: break
  882. dec(splits)
  883. inc(last, if last < sLen: runeLenAt(s, last) else: 1)
  884. iterator split*(s: openArray[char], seps: openArray[Rune] = unicodeSpaces,
  885. maxsplit: int = -1): string =
  886. ## Splits the unicode string ``s`` into substrings using a group of separators.
  887. ##
  888. ## Substrings are separated by a substring containing only ``seps``.
  889. runnableExamples:
  890. import std/sequtils
  891. assert toSeq("hÃllo\lthis\lis an\texample\l是".split) ==
  892. @["hÃllo", "this", "is", "an", "example", "是"]
  893. # And the following code splits the same string using a sequence of Runes.
  894. assert toSeq(split("añyóng:hÃllo;是$example", ";:$".toRunes)) ==
  895. @["añyóng", "hÃllo", "是", "example"]
  896. # example with a `Rune` separator and unused one `;`:
  897. assert toSeq(split("ab是de:f:", ";:是".toRunes)) == @["ab", "de", "f", ""]
  898. # Another example that splits a string containing a date.
  899. let date = "2012-11-20T22:08:08.398990"
  900. assert toSeq(split(date, " -:T".toRunes)) ==
  901. @["2012", "11", "20", "22", "08", "08.398990"]
  902. splitCommon(s, seps, maxsplit)
  903. iterator splitWhitespace*(s: openArray[char]): string =
  904. ## Splits a unicode string at whitespace runes.
  905. splitCommon(s, unicodeSpaces, -1)
  906. template accResult(iter: untyped) =
  907. result = @[]
  908. for x in iter: add(result, x)
  909. proc splitWhitespace*(s: openArray[char]): seq[string] {.noSideEffect,
  910. rtl, extern: "ncuSplitWhitespace".} =
  911. ## The same as the `splitWhitespace <#splitWhitespace.i,string>`_
  912. ## iterator, but is a proc that returns a sequence of substrings.
  913. accResult(splitWhitespace(s))
  914. iterator split*(s: openArray[char], sep: Rune, maxsplit: int = -1): string =
  915. ## Splits the unicode string ``s`` into substrings using a single separator.
  916. ## Substrings are separated by the rune ``sep``.
  917. runnableExamples:
  918. import std/sequtils
  919. assert toSeq(split(";;hÃllo;this;is;an;;example;;;是", ";".runeAt(0))) ==
  920. @["", "", "hÃllo", "this", "is", "an", "", "example", "", "", "是"]
  921. splitCommon(s, sep, maxsplit)
  922. proc split*(s: openArray[char], seps: openArray[Rune] = unicodeSpaces, maxsplit: int = -1):
  923. seq[string] {.noSideEffect, rtl, extern: "nucSplitRunes".} =
  924. ## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
  925. ## but is a proc that returns a sequence of substrings.
  926. accResult(split(s, seps, maxsplit))
  927. proc split*(s: openArray[char], sep: Rune, maxsplit: int = -1): seq[string] {.noSideEffect,
  928. rtl, extern: "nucSplitRune".} =
  929. ## The same as the `split iterator <#split.i,string,Rune,int>`_, but is a proc
  930. ## that returns a sequence of substrings.
  931. accResult(split(s, sep, maxsplit))
  932. proc strip*(s: openArray[char], leading = true, trailing = true,
  933. runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
  934. rtl, extern: "nucStrip".} =
  935. ## Strips leading or trailing ``runes`` from ``s`` and returns
  936. ## the resulting string.
  937. ##
  938. ## If ``leading`` is true (default), leading ``runes`` are stripped.
  939. ## If ``trailing`` is true (default), trailing ``runes`` are stripped.
  940. ## If both are false, the string is returned unchanged.
  941. runnableExamples:
  942. let a = "\táñyóng "
  943. doAssert a.strip == "áñyóng"
  944. doAssert a.strip(leading = false) == "\táñyóng"
  945. doAssert a.strip(trailing = false) == "áñyóng "
  946. var
  947. sI = 0 ## starting index into string ``s``
  948. eI = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
  949. if leading:
  950. var
  951. i = 0
  952. xI: int ## value of ``sI`` at the beginning of the iteration
  953. rune: Rune
  954. while i < len(s):
  955. xI = i
  956. fastRuneAt(s, i, rune)
  957. sI = i # Assume to start from next rune
  958. if not runes.contains(rune):
  959. sI = xI # Go back to where the current rune starts
  960. break
  961. if trailing:
  962. var
  963. i = eI
  964. xI: int
  965. rune: Rune
  966. while i >= 0:
  967. xI = i
  968. fastRuneAt(s, xI, rune)
  969. var yI = i - 1
  970. while yI >= 0:
  971. var
  972. yIend = yI
  973. pRune: Rune
  974. fastRuneAt(s, yIend, pRune)
  975. if yIend < xI: break
  976. i = yI
  977. rune = pRune
  978. dec(yI)
  979. if not runes.contains(rune):
  980. eI = xI - 1
  981. break
  982. dec(i)
  983. let newLen = eI - sI + 1
  984. result = newStringOfCap(newLen)
  985. if newLen > 0:
  986. result.add substr(s.toOpenArray(sI, eI))
  987. proc repeat*(c: Rune, count: Natural): string {.noSideEffect,
  988. rtl, extern: "nucRepeatRune".} =
  989. ## Returns a string of ``count`` Runes ``c``.
  990. ##
  991. ## The returned string will have a rune-length of ``count``.
  992. runnableExamples:
  993. let a = "ñ".runeAt(0)
  994. doAssert a.repeat(5) == "ñññññ"
  995. let s = $c
  996. result = newStringOfCap(count * s.len)
  997. for i in 0 ..< count:
  998. result.add s
  999. proc align*(s: openArray[char], count: Natural, padding = ' '.Rune): string {.
  1000. noSideEffect, rtl, extern: "nucAlignString".} =
  1001. ## Aligns a unicode string ``s`` with ``padding``, so that it has a rune-length
  1002. ## of ``count``.
  1003. ##
  1004. ## ``padding`` characters (by default spaces) are added before ``s`` resulting in
  1005. ## right alignment. If ``s.runelen >= count``, no spaces are added and ``s`` is
  1006. ## returned unchanged. If you need to left align a string use the `alignLeft
  1007. ## proc <#alignLeft,string,Natural>`_.
  1008. runnableExamples:
  1009. assert align("abc", 4) == " abc"
  1010. assert align("a", 0) == "a"
  1011. assert align("1232", 6) == " 1232"
  1012. assert align("1232", 6, '#'.Rune) == "##1232"
  1013. assert align("Åge", 5) == " Åge"
  1014. assert align("×", 4, '_'.Rune) == "___×"
  1015. let sLen = s.runeLen
  1016. if sLen < count:
  1017. let padStr = $padding
  1018. result = newStringOfCap(padStr.len * count)
  1019. let spaces = count - sLen
  1020. for i in 0 ..< spaces: result.add padStr
  1021. result.add s
  1022. else:
  1023. result = s.substr
  1024. proc alignLeft*(s: openArray[char], count: Natural, padding = ' '.Rune): string {.
  1025. noSideEffect.} =
  1026. ## Left-aligns a unicode string ``s`` with ``padding``, so that it has a
  1027. ## rune-length of ``count``.
  1028. ##
  1029. ## ``padding`` characters (by default spaces) are added after ``s`` resulting in
  1030. ## left alignment. If ``s.runelen >= count``, no spaces are added and ``s`` is
  1031. ## returned unchanged. If you need to right align a string use the `align
  1032. ## proc <#align,string,Natural>`_.
  1033. runnableExamples:
  1034. assert alignLeft("abc", 4) == "abc "
  1035. assert alignLeft("a", 0) == "a"
  1036. assert alignLeft("1232", 6) == "1232 "
  1037. assert alignLeft("1232", 6, '#'.Rune) == "1232##"
  1038. assert alignLeft("Åge", 5) == "Åge "
  1039. assert alignLeft("×", 4, '_'.Rune) == "×___"
  1040. let sLen = s.runeLen
  1041. if sLen < count:
  1042. let padStr = $padding
  1043. result = newStringOfCap(s.len + (count - sLen) * padStr.len)
  1044. result.add s
  1045. for i in sLen ..< count:
  1046. result.add padStr
  1047. else:
  1048. result = s.substr
  1049. proc runeLen*(s: string): int {.inline.} =
  1050. ## Returns the number of runes of the string ``s``.
  1051. runnableExamples:
  1052. let a = "añyóng"
  1053. doAssert a.runeLen == 6
  1054. ## note: a.len == 8
  1055. runeLen(toOa(s))
  1056. proc runeLenAt*(s: string, i: Natural): int {.inline.} =
  1057. ## Returns the number of bytes the rune starting at ``s[i]`` takes.
  1058. ##
  1059. ## See also:
  1060. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  1061. runnableExamples:
  1062. let a = "añyóng"
  1063. doAssert a.runeLenAt(0) == 1
  1064. doAssert a.runeLenAt(1) == 2
  1065. runeLenAt(toOa(s), i)
  1066. proc runeAt*(s: string, i: Natural): Rune {.inline.} =
  1067. ## Returns the rune in ``s`` at **byte index** ``i``.
  1068. ##
  1069. ## See also:
  1070. ## * `runeAtPos proc <#runeAtPos,string,int>`_
  1071. ## * `runeStrAtPos proc <#runeStrAtPos,string,Natural>`_
  1072. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  1073. runnableExamples:
  1074. let a = "añyóng"
  1075. doAssert a.runeAt(1) == "ñ".runeAt(0)
  1076. doAssert a.runeAt(2) == "ñ".runeAt(1)
  1077. doAssert a.runeAt(3) == "y".runeAt(0)
  1078. fastRuneAt(s, i, result, false)
  1079. proc validateUtf8*(s: string): int {.inline.} =
  1080. ## Returns the position of the invalid byte in ``s`` if the string ``s`` does
  1081. ## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
  1082. ##
  1083. ## See also:
  1084. ## * `toUTF8 proc <#toUTF8,Rune>`_
  1085. ## * `$ proc <#$,Rune>`_ alias for `toUTF8`
  1086. ## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
  1087. validateUtf8(toOa(s))
  1088. proc runeOffset*(s: string, pos: Natural, start: Natural = 0): int {.inline.} =
  1089. ## Returns the byte position of rune
  1090. ## at position ``pos`` in ``s`` with an optional start byte position.
  1091. ## Returns the special value -1 if it runs out of the string.
  1092. ##
  1093. ## **Beware:** This can lead to unoptimized code and slow execution!
  1094. ## Most problems can be solved more efficiently by using an iterator
  1095. ## or conversion to a seq of Rune.
  1096. ##
  1097. ## See also:
  1098. ## * `runeReverseOffset proc <#runeReverseOffset,string,Positive>`_
  1099. runnableExamples:
  1100. let a = "añyóng"
  1101. doAssert a.runeOffset(1) == 1
  1102. doAssert a.runeOffset(3) == 4
  1103. doAssert a.runeOffset(4) == 6
  1104. runeOffset(toOa(s), pos, start)
  1105. proc runeReverseOffset*(s: string, rev: Positive): (int, int) {.inline.} =
  1106. ## Returns a tuple with the byte offset of the
  1107. ## rune at position ``rev`` in ``s``, counting
  1108. ## from the end (starting with 1) and the total
  1109. ## number of runes in the string.
  1110. ##
  1111. ## Returns a negative value for offset if there are too few runes in
  1112. ## the string to satisfy the request.
  1113. ##
  1114. ## **Beware:** This can lead to unoptimized code and slow execution!
  1115. ## Most problems can be solved more efficiently by using an iterator
  1116. ## or conversion to a seq of Rune.
  1117. ##
  1118. ## See also:
  1119. ## * `runeOffset proc <#runeOffset,string,Natural,Natural>`_
  1120. runeReverseOffset(toOa(s), rev)
  1121. proc runeAtPos*(s: string, pos: int): Rune {.inline.} =
  1122. ## Returns the rune at position ``pos``.
  1123. ##
  1124. ## **Beware:** This can lead to unoptimized code and slow execution!
  1125. ## Most problems can be solved more efficiently by using an iterator
  1126. ## or conversion to a seq of Rune.
  1127. ##
  1128. ## See also:
  1129. ## * `runeAt proc <#runeAt,string,Natural>`_
  1130. ## * `runeStrAtPos proc <#runeStrAtPos,string,Natural>`_
  1131. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  1132. fastRuneAt(toOa(s), runeOffset(s, pos), result, false)
  1133. proc runeStrAtPos*(s: string, pos: Natural): string {.inline.} =
  1134. ## Returns the rune at position ``pos`` as UTF8 String.
  1135. ##
  1136. ## **Beware:** This can lead to unoptimized code and slow execution!
  1137. ## Most problems can be solved more efficiently by using an iterator
  1138. ## or conversion to a seq of Rune.
  1139. ##
  1140. ## See also:
  1141. ## * `runeAt proc <#runeAt,string,Natural>`_
  1142. ## * `runeAtPos proc <#runeAtPos,string,int>`_
  1143. ## * `fastRuneAt template <#fastRuneAt.t,string,int,untyped>`_
  1144. let o = runeOffset(s, pos)
  1145. substr(s.toOpenArray(o, (o+runeLenAt(s, o)-1)))
  1146. proc runeSubStr*(s: string, pos: int, len: int = int.high): string {.inline.} =
  1147. ## Returns the UTF-8 substring starting at code point ``pos``
  1148. ## with ``len`` code points.
  1149. ##
  1150. ## If ``pos`` or ``len`` is negative they count from
  1151. ## the end of the string. If ``len`` is not given it means the longest
  1152. ## possible string.
  1153. runnableExamples:
  1154. let s = "Hänsel ««: 10,00€"
  1155. doAssert(runeSubStr(s, 0, 2) == "Hä")
  1156. doAssert(runeSubStr(s, 10, 1) == ":")
  1157. doAssert(runeSubStr(s, -6) == "10,00€")
  1158. doAssert(runeSubStr(s, 10) == ": 10,00€")
  1159. doAssert(runeSubStr(s, 12, 5) == "10,00")
  1160. doAssert(runeSubStr(s, -6, 3) == "10,")
  1161. runeSubStr(toOa(s), pos, len)
  1162. proc isAlpha*(s: string): bool {.noSideEffect, inline.} =
  1163. ## Returns true if ``s`` contains all alphabetic runes.
  1164. runnableExamples:
  1165. let a = "añyóng"
  1166. doAssert a.isAlpha
  1167. isAlpha(toOa(s))
  1168. proc isSpace*(s: string): bool {.noSideEffect, inline.} =
  1169. ## Returns true if ``s`` contains all whitespace runes.
  1170. runnableExamples:
  1171. let a = "\t\l \v\r\f"
  1172. doAssert a.isSpace
  1173. isSpace(toOa(s))
  1174. proc toUpper*(s: string): string {.noSideEffect, inline.} =
  1175. ## Converts ``s`` into upper-case runes.
  1176. runnableExamples:
  1177. doAssert toUpper("abγ") == "ABΓ"
  1178. toUpper(toOa(s))
  1179. proc toLower*(s: string): string {.noSideEffect, inline.} =
  1180. ## Converts ``s`` into lower-case runes.
  1181. runnableExamples:
  1182. doAssert toLower("ABΓ") == "abγ"
  1183. toLower(toOa(s))
  1184. proc swapCase*(s: string): string {.noSideEffect, inline.} =
  1185. ## Swaps the case of runes in ``s``.
  1186. ##
  1187. ## Returns a new string such that the cases of all runes
  1188. ## are swapped if possible.
  1189. runnableExamples:
  1190. doAssert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA"
  1191. swapCase(toOa(s))
  1192. proc capitalize*(s: string): string {.noSideEffect.} =
  1193. ## Converts the first character of ``s`` into an upper-case rune.
  1194. runnableExamples:
  1195. doAssert capitalize("βeta") == "Βeta"
  1196. capitalize(toOa(s))
  1197. proc translate*(s: string, replacements: proc(key: string): string): string {.effectsOf: replacements, inline.} =
  1198. ## Translates words in a string using the ``replacements`` proc to substitute
  1199. ## words inside ``s`` with their replacements.
  1200. ##
  1201. ## ``replacements`` is any proc that takes a word and returns
  1202. ## a new word to fill it's place.
  1203. runnableExamples:
  1204. proc wordToNumber(s: string): string =
  1205. case s
  1206. of "one": "1"
  1207. of "two": "2"
  1208. else: s
  1209. let a = "one two three four"
  1210. doAssert a.translate(wordToNumber) == "1 2 three four"
  1211. translate(toOa(s), replacements)
  1212. proc title*(s: string): string {.noSideEffect, inline.} =
  1213. ## Converts ``s`` to a unicode title.
  1214. ##
  1215. ## Returns a new string such that the first character
  1216. ## in each word inside ``s`` is capitalized.
  1217. runnableExamples:
  1218. doAssert title("αlpha βeta γamma") == "Αlpha Βeta Γamma"
  1219. title(toOa(s))
  1220. iterator runes*(s: string): Rune =
  1221. ## Iterates over any rune of the string ``s`` returning runes.
  1222. for rune in runes(toOa(s)):
  1223. yield rune
  1224. iterator utf8*(s: string): string =
  1225. ## Iterates over any rune of the string ``s`` returning utf8 values.
  1226. ##
  1227. ## See also:
  1228. ## * `validateUtf8 proc <#validateUtf8,string>`_
  1229. ## * `toUTF8 proc <#toUTF8,Rune>`_
  1230. ## * `$ proc <#$,Rune>`_ alias for `toUTF8`
  1231. ## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
  1232. for str in utf8(toOa(s)):
  1233. yield str
  1234. proc toRunes*(s: string): seq[Rune] {.inline.} =
  1235. ## Obtains a sequence containing the Runes in ``s``.
  1236. ##
  1237. ## See also:
  1238. ## * `$ proc <#$,Rune>`_ for a reverse operation
  1239. runnableExamples:
  1240. let a = toRunes("aáä")
  1241. doAssert a == @["a".runeAt(0), "á".runeAt(0), "ä".runeAt(0)]
  1242. toRunes(toOa(s))
  1243. proc cmpRunesIgnoreCase*(a, b: string): int {.inline.} =
  1244. ## Compares two UTF-8 strings and ignores the case. Returns:
  1245. ##
  1246. ## | `0` if a == b
  1247. ## | `< 0` if a < b
  1248. ## | `> 0` if a > b
  1249. cmpRunesIgnoreCase(a.toOa(), b.toOa())
  1250. proc reversed*(s: string): string {.inline.} =
  1251. ## Returns the reverse of ``s``, interpreting it as runes.
  1252. ##
  1253. ## Unicode combining characters are correctly interpreted as well.
  1254. runnableExamples:
  1255. assert reversed("Reverse this!") == "!siht esreveR"
  1256. assert reversed("先秦兩漢") == "漢兩秦先"
  1257. assert reversed("as⃝df̅") == "f̅ds⃝a"
  1258. assert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞"
  1259. reversed(toOa(s))
  1260. proc graphemeLen*(s: string; i: Natural): Natural {.inline.} =
  1261. ## The number of bytes belonging to byte index ``s[i]``,
  1262. ## including following combining code unit.
  1263. runnableExamples:
  1264. let a = "añyóng"
  1265. doAssert a.graphemeLen(1) == 2 ## ñ
  1266. doAssert a.graphemeLen(2) == 1
  1267. doAssert a.graphemeLen(4) == 2 ## ó
  1268. graphemeLen(toOa(s), i)
  1269. proc lastRune*(s: string; last: int): (Rune, int) {.inline.} =
  1270. ## Length of the last rune in ``s[0..last]``. Returns the rune and its length
  1271. ## in bytes.
  1272. lastRune(toOa(s), last)
  1273. iterator split*(s: string, seps: openArray[Rune] = unicodeSpaces,
  1274. maxsplit: int = -1): string =
  1275. ## Splits the unicode string ``s`` into substrings using a group of separators.
  1276. ##
  1277. ## Substrings are separated by a substring containing only ``seps``.
  1278. runnableExamples:
  1279. import std/sequtils
  1280. assert toSeq("hÃllo\lthis\lis an\texample\l是".split) ==
  1281. @["hÃllo", "this", "is", "an", "example", "是"]
  1282. # And the following code splits the same string using a sequence of Runes.
  1283. assert toSeq(split("añyóng:hÃllo;是$example", ";:$".toRunes)) ==
  1284. @["añyóng", "hÃllo", "是", "example"]
  1285. # example with a `Rune` separator and unused one `;`:
  1286. assert toSeq(split("ab是de:f:", ";:是".toRunes)) == @["ab", "de", "f", ""]
  1287. # Another example that splits a string containing a date.
  1288. let date = "2012-11-20T22:08:08.398990"
  1289. assert toSeq(split(date, " -:T".toRunes)) ==
  1290. @["2012", "11", "20", "22", "08", "08.398990"]
  1291. splitCommon(toOa(s), seps, maxsplit)
  1292. iterator splitWhitespace*(s: string): string =
  1293. ## Splits a unicode string at whitespace runes.
  1294. splitCommon(s.toOa(), unicodeSpaces, -1)
  1295. proc splitWhitespace*(s: string): seq[string] {.noSideEffect, inline.}=
  1296. ## The same as the `splitWhitespace <#splitWhitespace.i,string>`_
  1297. ## iterator, but is a proc that returns a sequence of substrings.
  1298. accResult(splitWhitespace(toOa(s)))
  1299. iterator split*(s: string, sep: Rune, maxsplit: int = -1): string =
  1300. ## Splits the unicode string ``s`` into substrings using a single separator.
  1301. ## Substrings are separated by the rune ``sep``.
  1302. runnableExamples:
  1303. import std/sequtils
  1304. assert toSeq(split(";;hÃllo;this;is;an;;example;;;是", ";".runeAt(0))) ==
  1305. @["", "", "hÃllo", "this", "is", "an", "", "example", "", "", "是"]
  1306. splitCommon(toOa(s), sep, maxsplit)
  1307. proc split*(s: string, seps: openArray[Rune] = unicodeSpaces, maxsplit: int = -1):
  1308. seq[string] {.noSideEffect, inline.} =
  1309. ## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
  1310. ## but is a proc that returns a sequence of substrings.
  1311. accResult(split(toOa(s), seps, maxsplit))
  1312. proc split*(s: string, sep: Rune, maxsplit: int = -1): seq[string] {.noSideEffect, inline.} =
  1313. ## The same as the `split iterator <#split.i,string,Rune,int>`_, but is a proc
  1314. ## that returns a sequence of substrings.
  1315. accResult(split(toOa(s), sep, maxsplit))
  1316. proc strip*(s: string, leading = true, trailing = true,
  1317. runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect, inline.} =
  1318. ## Strips leading or trailing ``runes`` from ``s`` and returns
  1319. ## the resulting string.
  1320. ##
  1321. ## If ``leading`` is true (default), leading ``runes`` are stripped.
  1322. ## If ``trailing`` is true (default), trailing ``runes`` are stripped.
  1323. ## If both are false, the string is returned unchanged.
  1324. runnableExamples:
  1325. let a = "\táñyóng "
  1326. doAssert a.strip == "áñyóng"
  1327. doAssert a.strip(leading = false) == "\táñyóng"
  1328. doAssert a.strip(trailing = false) == "áñyóng "
  1329. strip(toOa(s), leading, trailing, runes)
  1330. proc align*(s: string, count: Natural, padding = ' '.Rune): string {.noSideEffect, inline.} =
  1331. ## Aligns a unicode string ``s`` with ``padding``, so that it has a rune-length
  1332. ## of ``count``.
  1333. ##
  1334. ## ``padding`` characters (by default spaces) are added before ``s`` resulting in
  1335. ## right alignment. If ``s.runelen >= count``, no spaces are added and ``s`` is
  1336. ## returned unchanged. If you need to left align a string use the `alignLeft
  1337. ## proc <#alignLeft,string,Natural>`_.
  1338. runnableExamples:
  1339. assert align("abc", 4) == " abc"
  1340. assert align("a", 0) == "a"
  1341. assert align("1232", 6) == " 1232"
  1342. assert align("1232", 6, '#'.Rune) == "##1232"
  1343. assert align("Åge", 5) == " Åge"
  1344. assert align("×", 4, '_'.Rune) == "___×"
  1345. align(toOa(s), count, padding)
  1346. proc alignLeft*(s: string, count: Natural, padding = ' '.Rune): string {.noSideEffect, inline.} =
  1347. ## Left-aligns a unicode string ``s`` with ``padding``, so that it has a
  1348. ## rune-length of ``count``.
  1349. ##
  1350. ## ``padding`` characters (by default spaces) are added after ``s`` resulting in
  1351. ## left alignment. If ``s.runelen >= count``, no spaces are added and ``s`` is
  1352. ## returned unchanged. If you need to right align a string use the `align
  1353. ## proc <#align,string,Natural>`_.
  1354. runnableExamples:
  1355. assert alignLeft("abc", 4) == "abc "
  1356. assert alignLeft("a", 0) == "a"
  1357. assert alignLeft("1232", 6) == "1232 "
  1358. assert alignLeft("1232", 6, '#'.Rune) == "1232##"
  1359. assert alignLeft("Åge", 5) == "Åge "
  1360. assert alignLeft("×", 4, '_'.Rune) == "×___"
  1361. alignLeft(toOa(s), count, padding)