strings.odin 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269
  1. // Procedures to manipulate UTF-8 encoded strings
  2. package strings
  3. import "core:io"
  4. import "core:mem"
  5. import "core:unicode"
  6. import "core:unicode/utf8"
  7. /*
  8. Clones a string
  9. *Allocates Using Provided Allocator*
  10. Inputs:
  11. - s: The string to be cloned
  12. - allocator: (default: context.allocator)
  13. - loc: The caller location for debugging purposes (default: #caller_location)
  14. Returns:
  15. A cloned string
  16. */
  17. clone :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> string {
  18. c := make([]byte, len(s), allocator, loc)
  19. copy(c, s)
  20. return string(c[:len(s)])
  21. }
  22. /*
  23. Clones a string safely (returns early with an allocation error on failure)
  24. *Allocates Using Provided Allocator*
  25. Inputs:
  26. - s: The string to be cloned
  27. - allocator: (default: context.allocator)
  28. - loc: The caller location for debugging purposes (default: #caller_location)
  29. Returns:
  30. - str: A cloned string
  31. - err: A mem.Allocator_Error if an error occurs during allocation
  32. */
  33. clone_safe :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (str: string, err: mem.Allocator_Error) {
  34. c := make([]byte, len(s), allocator, loc) or_return
  35. copy(c, s)
  36. return string(c[:len(s)]), nil
  37. }
  38. /*
  39. Clones a string and appends a null-byte to make it a cstring
  40. *Allocates Using Provided Allocator*
  41. Inputs:
  42. - s: The string to be cloned
  43. - allocator: (default: context.allocator)
  44. - loc: The caller location for debugging purposes (default: #caller_location)
  45. Returns:
  46. A cloned cstring with an appended null-byte
  47. */
  48. clone_to_cstring :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> cstring {
  49. c := make([]byte, len(s)+1, allocator, loc)
  50. copy(c, s)
  51. c[len(s)] = 0
  52. return cstring(&c[0])
  53. }
  54. /*
  55. Transmutes a raw pointer into a string. Non-allocating.
  56. Inputs:
  57. - ptr: A pointer to the start of the byte sequence
  58. - len: The length of the byte sequence
  59. NOTE: The created string is only valid as long as the pointer and length are valid.
  60. Returns:
  61. A string created from the byte pointer and length
  62. */
  63. string_from_ptr :: proc(ptr: ^byte, len: int) -> string {
  64. return transmute(string)mem.Raw_String{ptr, len}
  65. }
  66. /*
  67. Transmutes a raw pointer (null-terminated) into a string. Non-allocating. Searches for a null-byte from `0..<len`, otherwise `len` will be the end size
  68. NOTE: The created string is only valid as long as the pointer and length are valid.
  69. The string is truncated at the first null-byte encountered.
  70. Inputs:
  71. - ptr: A pointer to the start of the null-terminated byte sequence
  72. - len: The length of the byte sequence
  73. Returns:
  74. A string created from the null-terminated byte pointer and length
  75. */
  76. string_from_null_terminated_ptr :: proc(ptr: ^byte, len: int) -> string {
  77. s := transmute(string)mem.Raw_String{ptr, len}
  78. s = truncate_to_byte(s, 0)
  79. return s
  80. }
  81. /*
  82. Gets the raw byte pointer for the start of a string `str`
  83. Inputs:
  84. - str: The input string
  85. Returns:
  86. A pointer to the start of the string's bytes
  87. */
  88. ptr_from_string :: proc(str: string) -> ^byte {
  89. d := transmute(mem.Raw_String)str
  90. return d.data
  91. }
  92. /*
  93. Converts a string `str` to a cstring
  94. Inputs:
  95. - str: The input string
  96. WARNING: This is unsafe because the original string may not contain a null-byte.
  97. Returns:
  98. The converted cstring
  99. */
  100. unsafe_string_to_cstring :: proc(str: string) -> cstring {
  101. d := transmute(mem.Raw_String)str
  102. return cstring(d.data)
  103. }
  104. /*
  105. Truncates a string `str` at the first occurrence of char/byte `b`
  106. Inputs:
  107. - str: The input string
  108. - b: The byte to truncate the string at
  109. NOTE: Failure to find the byte results in returning the entire string.
  110. Returns:
  111. The truncated string
  112. */
  113. truncate_to_byte :: proc(str: string, b: byte) -> string {
  114. n := index_byte(str, b)
  115. if n < 0 {
  116. n = len(str)
  117. }
  118. return str[:n]
  119. }
  120. /*
  121. Truncates a string `str` at the first occurrence of rune `r` as a slice of the original, entire string if not found
  122. Inputs:
  123. - str: The input string
  124. - r: The rune to truncate the string at
  125. Returns:
  126. The truncated string
  127. */
  128. truncate_to_rune :: proc(str: string, r: rune) -> string {
  129. n := index_rune(str, r)
  130. if n < 0 {
  131. n = len(str)
  132. }
  133. return str[:n]
  134. }
  135. /*
  136. Clones a byte array `s` and appends a null-byte
  137. *Allocates Using Provided Allocator*
  138. Inputs:
  139. - s: The byte array to be cloned
  140. - allocator: (default: context.allocator)
  141. - loc: The caller location for debugging purposes (default: `#caller_location`)
  142. Returns:
  143. A cloned string from the byte array with a null-byte
  144. */
  145. clone_from_bytes :: proc(s: []byte, allocator := context.allocator, loc := #caller_location) -> string {
  146. c := make([]byte, len(s)+1, allocator, loc)
  147. copy(c, s)
  148. c[len(s)] = 0
  149. return string(c[:len(s)])
  150. }
  151. /*
  152. Clones a cstring `s` as a string
  153. *Allocates Using Provided Allocator*
  154. Inputs:
  155. - s: The cstring to be cloned
  156. - allocator: (default: context.allocator)
  157. - loc: The caller location for debugging purposes (default: `#caller_location`)
  158. Returns:
  159. A cloned string from the cstring
  160. */
  161. clone_from_cstring :: proc(s: cstring, allocator := context.allocator, loc := #caller_location) -> string {
  162. return clone(string(s), allocator, loc)
  163. }
  164. /*
  165. Clones a string from a byte pointer `ptr` and a byte length `len`
  166. *Allocates Using Provided Allocator*
  167. Inputs:
  168. - ptr: A pointer to the start of the byte sequence
  169. - len: The length of the byte sequence
  170. - allocator: (default: context.allocator)
  171. - loc: The caller location for debugging purposes (default: `#caller_location`)
  172. NOTE: Same as `string_from_ptr`, but perform an additional `clone` operation
  173. Returns:
  174. A cloned string from the byte pointer and length
  175. */
  176. clone_from_ptr :: proc(ptr: ^byte, len: int, allocator := context.allocator, loc := #caller_location) -> string {
  177. s := string_from_ptr(ptr, len)
  178. return clone(s, allocator, loc)
  179. }
  180. // Overloaded procedure to clone from a string, `[]byte`, `cstring` or a `^byte` + length
  181. clone_from :: proc{
  182. clone,
  183. clone_from_bytes,
  184. clone_from_cstring,
  185. clone_from_ptr,
  186. }
  187. /*
  188. Clones a string from a null-terminated cstring `ptr` and a byte length `len`
  189. *Allocates Using Provided Allocator*
  190. Inputs:
  191. - ptr: A pointer to the start of the null-terminated cstring
  192. - len: The byte length of the cstring
  193. - allocator: (default: context.allocator)
  194. - loc: The caller location for debugging purposes (default: `#caller_location`)
  195. NOTE: Truncates at the first null-byte encountered or the byte length.
  196. Returns:
  197. A cloned string from the null-terminated cstring and byte length
  198. */
  199. clone_from_cstring_bounded :: proc(ptr: cstring, len: int, allocator := context.allocator, loc := #caller_location) -> string {
  200. s := string_from_ptr((^u8)(ptr), len)
  201. s = truncate_to_byte(s, 0)
  202. return clone(s, allocator, loc)
  203. }
  204. /*
  205. Compares two strings, returning a value representing which one comes first lexicographically.
  206. -1 for `lhs`; 1 for `rhs`, or 0 if they are equal.
  207. Inputs:
  208. - lhs: First string for comparison
  209. - rhs: Second string for comparison
  210. Returns:
  211. -1 if `lhs` comes first, 1 if `rhs` comes first, or 0 if they are equal
  212. */
  213. compare :: proc(lhs, rhs: string) -> int {
  214. return mem.compare(transmute([]byte)lhs, transmute([]byte)rhs)
  215. }
  216. /*
  217. Returns the byte offset of the rune `r` in the string `s`, -1 when not found
  218. Inputs:
  219. - s: The input string
  220. - r: The rune to search for
  221. Returns:
  222. The byte offset of the rune `r` in the string `s`, or -1 if not found
  223. */
  224. contains_rune :: proc(s: string, r: rune) -> int {
  225. for c, offset in s {
  226. if c == r {
  227. return offset
  228. }
  229. }
  230. return -1
  231. }
  232. /*
  233. Returns true when the string `substr` is contained inside the string `s`
  234. Inputs:
  235. - s: The input string
  236. - substr: The substring to search for
  237. Returns:
  238. `true` if `substr` is contained inside the string `s`, `false` otherwise
  239. Example:
  240. import "core:fmt"
  241. import "core:strings"
  242. contains_example :: proc() {
  243. fmt.println(strings.contains("testing", "test"))
  244. fmt.println(strings.contains("testing", "ing"))
  245. fmt.println(strings.contains("testing", "text"))
  246. }
  247. Output:
  248. true
  249. true
  250. false
  251. */
  252. contains :: proc(s, substr: string) -> bool {
  253. return index(s, substr) >= 0
  254. }
  255. /*
  256. Returns `true` when the string `s` contains any of the characters inside the string `chars`
  257. Inputs:
  258. - s: The input string
  259. - chars: The characters to search for
  260. Returns:
  261. `true` if the string `s` contains any of the characters in `chars`, `false` otherwise
  262. Example:
  263. import "core:fmt"
  264. import "core:strings"
  265. contains_any_example :: proc() {
  266. fmt.println(strings.contains_any("test", "test"))
  267. fmt.println(strings.contains_any("test", "ts"))
  268. fmt.println(strings.contains_any("test", "et"))
  269. fmt.println(strings.contains_any("test", "a"))
  270. }
  271. Output:
  272. true
  273. true
  274. true
  275. false
  276. */
  277. contains_any :: proc(s, chars: string) -> bool {
  278. return index_any(s, chars) >= 0
  279. }
  280. /*
  281. Returns the UTF-8 rune count of the string `s`
  282. Inputs:
  283. - s: The input string
  284. Returns:
  285. The UTF-8 rune count of the string `s`
  286. Example:
  287. import "core:fmt"
  288. import "core:strings"
  289. rune_count_example :: proc() {
  290. fmt.println(strings.rune_count("test"))
  291. fmt.println(strings.rune_count("testö")) // where len("testö") == 6
  292. }
  293. Output:
  294. 4
  295. 5
  296. */
  297. rune_count :: proc(s: string) -> int {
  298. return utf8.rune_count_in_string(s)
  299. }
  300. /*
  301. Returns whether the strings `u` and `v` are the same alpha characters, ignoring different casings
  302. Works with UTF-8 string content
  303. Inputs:
  304. - u: The first string for comparison
  305. - v: The second string for comparison
  306. Returns:
  307. `true` if the strings `u` and `v` are the same alpha characters (ignoring case)
  308. Example:
  309. import "core:fmt"
  310. import "core:strings"
  311. equal_fold_example :: proc() {
  312. fmt.println(strings.equal_fold("test", "test"))
  313. fmt.println(strings.equal_fold("Test", "test"))
  314. fmt.println(strings.equal_fold("Test", "tEsT"))
  315. fmt.println(strings.equal_fold("test", "tes"))
  316. }
  317. Output:
  318. true
  319. true
  320. true
  321. false
  322. */
  323. equal_fold :: proc(u, v: string) -> bool {
  324. s, t := u, v
  325. loop: for s != "" && t != "" {
  326. sr, tr: rune
  327. if s[0] < utf8.RUNE_SELF {
  328. sr, s = rune(s[0]), s[1:]
  329. } else {
  330. r, size := utf8.decode_rune_in_string(s)
  331. sr, s = r, s[size:]
  332. }
  333. if t[0] < utf8.RUNE_SELF {
  334. tr, t = rune(t[0]), t[1:]
  335. } else {
  336. r, size := utf8.decode_rune_in_string(t)
  337. tr, t = r, t[size:]
  338. }
  339. if tr == sr { // easy case
  340. continue loop
  341. }
  342. if tr < sr {
  343. tr, sr = sr, tr
  344. }
  345. if tr < utf8.RUNE_SELF {
  346. switch sr {
  347. case 'A'..='Z':
  348. if tr == (sr+'a')-'A' {
  349. continue loop
  350. }
  351. }
  352. return false
  353. }
  354. // TODO(bill): Unicode folding
  355. return false
  356. }
  357. return s == t
  358. }
  359. /*
  360. Returns the prefix length common between strings `a` and `b`
  361. Inputs:
  362. - a: The first input string
  363. - b: The second input string
  364. Returns:
  365. The prefix length common between strings `a` and `b`
  366. Example:
  367. import "core:fmt"
  368. import "core:strings"
  369. prefix_length_example :: proc() {
  370. fmt.println(strings.prefix_length("testing", "test"))
  371. fmt.println(strings.prefix_length("testing", "te"))
  372. fmt.println(strings.prefix_length("telephone", "te"))
  373. fmt.println(strings.prefix_length("testing", "est"))
  374. }
  375. Output:
  376. 4
  377. 2
  378. 2
  379. 0
  380. */
  381. prefix_length :: proc(a, b: string) -> (n: int) {
  382. _len := min(len(a), len(b))
  383. // Scan for matches including partial codepoints.
  384. #no_bounds_check for n < _len && a[n] == b[n] {
  385. n += 1
  386. }
  387. // Now scan to ignore partial codepoints.
  388. if n > 0 {
  389. s := a[:n]
  390. n = 0
  391. for {
  392. r0, w := utf8.decode_rune(s[n:])
  393. if r0 != utf8.RUNE_ERROR {
  394. n += w
  395. } else {
  396. break
  397. }
  398. }
  399. }
  400. return
  401. }
  402. /*
  403. Determines if a string `s` starts with a given `prefix`
  404. Inputs:
  405. - s: The string to check for the `prefix`
  406. - prefix: The prefix to look for
  407. Returns:
  408. `true` if the string `s` starts with the `prefix`, otherwise `false`
  409. Example:
  410. import "core:fmt"
  411. import "core:strings"
  412. has_prefix_example :: proc() {
  413. fmt.println(strings.has_prefix("testing", "test"))
  414. fmt.println(strings.has_prefix("testing", "te"))
  415. fmt.println(strings.has_prefix("telephone", "te"))
  416. fmt.println(strings.has_prefix("testing", "est"))
  417. }
  418. Output:
  419. true
  420. true
  421. true
  422. false
  423. */
  424. has_prefix :: proc(s, prefix: string) -> bool {
  425. return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
  426. }
  427. /*
  428. Determines if a string `s` ends with a given `suffix`
  429. Inputs:
  430. - s: The string to check for the `suffix`
  431. - suffix: The suffix to look for
  432. Returns:
  433. `true` if the string `s` ends with the `suffix`, otherwise `false`
  434. Example:
  435. import "core:fmt"
  436. import "core:strings"
  437. has_suffix_example :: proc() {
  438. fmt.println(strings.has_suffix("todo.txt", ".txt"))
  439. fmt.println(strings.has_suffix("todo.doc", ".txt"))
  440. fmt.println(strings.has_suffix("todo.doc.txt", ".txt"))
  441. }
  442. Output:
  443. true
  444. false
  445. true
  446. */
  447. has_suffix :: proc(s, suffix: string) -> bool {
  448. return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
  449. }
  450. /*
  451. Joins a slice of strings `a` with a `sep` string
  452. *Allocates Using Provided Allocator*
  453. Inputs:
  454. - a: A slice of strings to join
  455. - sep: The separator string
  456. - allocator: (default is context.allocator)
  457. Returns:
  458. A combined string from the slice of strings `a` separated with the `sep` string
  459. Example:
  460. import "core:fmt"
  461. import "core:strings"
  462. join_example :: proc() {
  463. a := [?]string { "a", "b", "c" }
  464. fmt.println(strings.join(a[:], " "))
  465. fmt.println(strings.join(a[:], "-"))
  466. fmt.println(strings.join(a[:], "..."))
  467. }
  468. Output:
  469. a b c
  470. a-b-c
  471. a...b...c
  472. */
  473. join :: proc(a: []string, sep: string, allocator := context.allocator) -> string {
  474. if len(a) == 0 {
  475. return ""
  476. }
  477. n := len(sep) * (len(a) - 1)
  478. for s in a {
  479. n += len(s)
  480. }
  481. b := make([]byte, n, allocator)
  482. i := copy(b, a[0])
  483. for s in a[1:] {
  484. i += copy(b[i:], sep)
  485. i += copy(b[i:], s)
  486. }
  487. return string(b)
  488. }
  489. /*
  490. Joins a slice of strings `a` with a `sep` string, returns an error on allocation failure
  491. *Allocates Using Provided Allocator*
  492. Inputs:
  493. - a: A slice of strings to join
  494. - sep: The separator string
  495. - allocator: (default is context.allocator)
  496. Returns:
  497. - str: A combined string from the slice of strings `a` separated with the `sep` string
  498. - err: An error if allocation failed, otherwise `nil`
  499. */
  500. join_safe :: proc(a: []string, sep: string, allocator := context.allocator) -> (str: string, err: mem.Allocator_Error) {
  501. if len(a) == 0 {
  502. return "", nil
  503. }
  504. n := len(sep) * (len(a) - 1)
  505. for s in a {
  506. n += len(s)
  507. }
  508. b := make([]byte, n, allocator) or_return
  509. i := copy(b, a[0])
  510. for s in a[1:] {
  511. i += copy(b[i:], sep)
  512. i += copy(b[i:], s)
  513. }
  514. return string(b), nil
  515. }
  516. /*
  517. Returns a combined string from the slice of strings `a` without a separator
  518. *Allocates Using Provided Allocator*
  519. Inputs:
  520. - a: A slice of strings to concatenate
  521. - allocator: (default is context.allocator)
  522. Returns:
  523. The concatenated string
  524. Example:
  525. import "core:fmt"
  526. import "core:strings"
  527. concatenate_example :: proc() {
  528. a := [?]string { "a", "b", "c" }
  529. fmt.println(strings.concatenate(a[:]))
  530. }
  531. Output:
  532. abc
  533. */
  534. concatenate :: proc(a: []string, allocator := context.allocator) -> string {
  535. if len(a) == 0 {
  536. return ""
  537. }
  538. n := 0
  539. for s in a {
  540. n += len(s)
  541. }
  542. b := make([]byte, n, allocator)
  543. i := 0
  544. for s in a {
  545. i += copy(b[i:], s)
  546. }
  547. return string(b)
  548. }
  549. /*
  550. Returns a combined string from the slice of strings `a` without a separator, or an error if allocation fails
  551. *Allocates Using Provided Allocator*
  552. Inputs:
  553. - a: A slice of strings to concatenate
  554. - allocator: (default is context.allocator)
  555. Returns:
  556. The concatenated string, and an error if allocation fails
  557. */
  558. concatenate_safe :: proc(a: []string, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) {
  559. if len(a) == 0 {
  560. return "", nil
  561. }
  562. n := 0
  563. for s in a {
  564. n += len(s)
  565. }
  566. b := make([]byte, n, allocator) or_return
  567. i := 0
  568. for s in a {
  569. i += copy(b[i:], s)
  570. }
  571. return string(b), nil
  572. }
  573. /*
  574. Returns a substring of the input string `s` with the specified rune offset and length
  575. *Allocates Using Provided Allocator*
  576. Inputs:
  577. - s: The input string to cut
  578. - rune_offset: The starting rune index (default is 0). In runes, not bytes.
  579. - rune_length: The number of runes to include in the substring (default is 0, which returns the remainder of the string). In runes, not bytes.
  580. - allocator: (default is context.allocator)
  581. Returns:
  582. The substring
  583. Example:
  584. import "core:fmt"
  585. import "core:strings"
  586. cut_example :: proc() {
  587. fmt.println(strings.cut("some example text", 0, 4)) // -> "some"
  588. fmt.println(strings.cut("some example text", 2, 2)) // -> "me"
  589. fmt.println(strings.cut("some example text", 5, 7)) // -> "example"
  590. }
  591. Output:
  592. some
  593. me
  594. example
  595. */
  596. cut :: proc(s: string, rune_offset := int(0), rune_length := int(0), allocator := context.allocator) -> (res: string) {
  597. s := s; rune_length := rune_length
  598. context.allocator = allocator
  599. // If we signal that we want the entire remainder (length <= 0) *and*
  600. // the offset is zero, then we can early out by cloning the input
  601. if rune_offset == 0 && rune_length <= 0 {
  602. return clone(s)
  603. }
  604. // We need to know if we have enough runes to cover offset + length.
  605. rune_count := utf8.rune_count_in_string(s)
  606. // We're asking for a substring starting after the end of the input string.
  607. // That's just an empty string.
  608. if rune_offset >= rune_count {
  609. return ""
  610. }
  611. // If we don't specify the length of the substring, use the remainder.
  612. if rune_length <= 0 {
  613. rune_length = rune_count - rune_offset
  614. }
  615. // We don't yet know how many bytes we need exactly.
  616. // But we do know it's bounded by the number of runes * 4 bytes,
  617. // and can be no more than the size of the input string.
  618. bytes_needed := min(rune_length * 4, len(s))
  619. buf := make([]u8, bytes_needed)
  620. byte_offset := 0
  621. for i := 0; i < rune_count; i += 1 {
  622. _, w := utf8.decode_rune_in_string(s)
  623. // If the rune is part of the substring, copy it to the output buffer.
  624. if i >= rune_offset {
  625. for j := 0; j < w; j += 1 {
  626. buf[byte_offset+j] = s[j]
  627. }
  628. byte_offset += w
  629. }
  630. // We're done if we reach the end of the input string, *or*
  631. // if we've reached a specified length in runes.
  632. if rune_length > 0 {
  633. if i == rune_offset + rune_length - 1 { break }
  634. }
  635. s = s[w:]
  636. }
  637. return string(buf[:byte_offset])
  638. }
  639. /*
  640. Splits the input string `s` into a slice of substrings separated by the specified `sep` string
  641. *Allocates Using Provided Allocator*
  642. *Used Internally - Private Function*
  643. Inputs:
  644. - s: The input string to split
  645. - sep: The separator string
  646. - sep_save: A flag determining if the separator should be saved in the resulting substrings
  647. - n: The maximum number of substrings to return, returns `nil` without alloc when `n=0`
  648. - allocator: (default is context.allocator)
  649. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  650. Returns:
  651. A slice of substrings
  652. */
  653. @private
  654. _split :: proc(s_, sep: string, sep_save, n_: int, allocator := context.allocator) -> []string {
  655. s, n := s_, n_
  656. if n == 0 {
  657. return nil
  658. }
  659. if sep == "" {
  660. l := utf8.rune_count_in_string(s)
  661. if n < 0 || n > l {
  662. n = l
  663. }
  664. res := make([dynamic]string, n, allocator)
  665. for i := 0; i < n-1; i += 1 {
  666. _, w := utf8.decode_rune_in_string(s)
  667. res[i] = s[:w]
  668. s = s[w:]
  669. }
  670. if n > 0 {
  671. res[n-1] = s
  672. }
  673. return res[:]
  674. }
  675. if n < 0 {
  676. n = count(s, sep) + 1
  677. }
  678. res := make([dynamic]string, n, allocator)
  679. n -= 1
  680. i := 0
  681. for ; i < n; i += 1 {
  682. m := index(s, sep)
  683. if m < 0 {
  684. break
  685. }
  686. res[i] = s[:m+sep_save]
  687. s = s[m+len(sep):]
  688. }
  689. res[i] = s
  690. return res[:i+1]
  691. }
  692. /*
  693. Splits a string into parts based on a separator.
  694. *Allocates Using Provided Allocator*
  695. Inputs:
  696. - s: The string to split.
  697. - sep: The separator string used to split the input string.
  698. - allocator: (default is context.allocator).
  699. Returns: A slice of strings, each representing a part of the split string.
  700. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  701. Example:
  702. import "core:fmt"
  703. import "core:strings"
  704. split_example :: proc() {
  705. s := "aaa.bbb.ccc.ddd.eee" // 5 parts
  706. ss := strings.split(s, ".")
  707. fmt.println(ss)
  708. }
  709. Output:
  710. ["aaa", "bbb", "ccc", "ddd", "eee"]
  711. */
  712. split :: proc(s, sep: string, allocator := context.allocator) -> []string {
  713. return _split(s, sep, 0, -1, allocator)
  714. }
  715. /*
  716. Splits a string into parts based on a separator. If n < count of seperators, the remainder of the string is returned in the last entry.
  717. *Allocates Using Provided Allocator*
  718. Inputs:
  719. - s: The string to split.
  720. - sep: The separator string used to split the input string.
  721. - allocator: (default is context.allocator)
  722. Returns: A slice of strings, each representing a part of the split string.
  723. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  724. Example:
  725. import "core:fmt"
  726. import "core:strings"
  727. split_n_example :: proc() {
  728. s := "aaa.bbb.ccc.ddd.eee" // 5 parts present
  729. ss := strings.split_n(s, ".",3) // total of 3 wanted
  730. fmt.println(ss)
  731. }
  732. Output:
  733. ["aaa", "bbb", "ccc.ddd.eee"]
  734. */
  735. split_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  736. return _split(s, sep, 0, n, allocator)
  737. }
  738. /*
  739. Splits a string into parts after the separator, retaining it in the substrings.
  740. *Allocates Using Provided Allocator*
  741. Inputs:
  742. - s: The string to split.
  743. - sep: The separator string used to split the input string.
  744. - allocator: (default is context.allocator).
  745. Returns:
  746. A slice of strings, each representing a part of the split string after the separator.
  747. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  748. Example:
  749. import "core:fmt"
  750. import "core:strings"
  751. split_after_example :: proc() {
  752. a := "aaa.bbb.ccc.ddd.eee" // 5 parts
  753. aa := strings.split_after(a, ".")
  754. fmt.println(aa)
  755. }
  756. Output:
  757. ["aaa.", "bbb.", "ccc.", "ddd.", "eee"]
  758. */
  759. split_after :: proc(s, sep: string, allocator := context.allocator) -> []string {
  760. return _split(s, sep, len(sep), -1, allocator)
  761. }
  762. /*
  763. Splits a string into a total of `n` parts after the separator.
  764. *Allocates Using Provided Allocator*
  765. Inputs:
  766. - s: The string to split.
  767. - sep: The separator string used to split the input string.
  768. - n: The maximum number of parts to split the string into.
  769. - allocator: (default is context.allocator)
  770. Returns:
  771. A slice of strings with `n` parts or fewer if there weren't
  772. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  773. Example:
  774. import "core:fmt"
  775. import "core:strings"
  776. split_after_n_example :: proc() {
  777. a := "aaa.bbb.ccc.ddd.eee"
  778. aa := strings.split_after_n(a, ".", 3)
  779. fmt.println(aa)
  780. }
  781. Output:
  782. ["aaa.", "bbb.", "ccc.ddd.eee"]
  783. */
  784. split_after_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  785. return _split(s, sep, len(sep), n, allocator)
  786. }
  787. /*
  788. Searches for the first occurrence of `sep` in the given string and returns the substring
  789. up to (but not including) the separator, as well as a boolean indicating success.
  790. *Used Internally - Private Function*
  791. Inputs:
  792. - s: Pointer to the input string, which is modified during the search.
  793. - sep: The separator string to search for.
  794. - sep_save: Number of characters from the separator to include in the result.
  795. Returns:
  796. A tuple containing the resulting substring and a boolean indicating success.
  797. */
  798. @private
  799. _split_iterator :: proc(s: ^string, sep: string, sep_save: int) -> (res: string, ok: bool) {
  800. // stop once the string is empty or nil
  801. if s == nil || len(s^) == 0 {
  802. return
  803. }
  804. if sep == "" {
  805. res = s[:]
  806. ok = true
  807. s^ = s[len(s):]
  808. return
  809. }
  810. m := index(s^, sep)
  811. if m < 0 {
  812. // not found
  813. res = s[:]
  814. ok = res != ""
  815. s^ = s[len(s):]
  816. } else {
  817. res = s[:m+sep_save]
  818. ok = true
  819. s^ = s[m+len(sep):]
  820. }
  821. return
  822. }
  823. /*
  824. Splits the input string by the byte separator in an iterator fashion.
  825. Inputs:
  826. - s: Pointer to the input string, which is modified during the search.
  827. - sep: The byte separator to search for.
  828. Returns:
  829. A tuple containing the resulting substring and a boolean indicating success.
  830. Example:
  831. import "core:fmt"
  832. import "core:strings"
  833. split_by_byte_iterator_example :: proc() {
  834. text := "a.b.c.d.e"
  835. for str in strings.split_by_byte_iterator(&text, '.') {
  836. fmt.println(str) // every loop -> a b c d e
  837. }
  838. }
  839. Output:
  840. a
  841. b
  842. c
  843. d
  844. e
  845. */
  846. split_by_byte_iterator :: proc(s: ^string, sep: u8) -> (res: string, ok: bool) {
  847. m := index_byte(s^, sep)
  848. if m < 0 {
  849. // not found
  850. res = s[:]
  851. ok = res != ""
  852. s^ = {}
  853. } else {
  854. res = s[:m]
  855. ok = true
  856. s^ = s[m+1:]
  857. }
  858. return
  859. }
  860. /*
  861. Splits the input string by the separator string in an iterator fashion.
  862. Destructively consumes the original string until the end.
  863. Inputs:
  864. - s: Pointer to the input string, which is modified during the search.
  865. - sep: The separator string to search for.
  866. Returns:
  867. A tuple containing the resulting substring and a boolean indicating success.
  868. Example:
  869. import "core:fmt"
  870. import "core:strings"
  871. split_iterator_example :: proc() {
  872. text := "a.b.c.d.e"
  873. for str in strings.split_iterator(&text, ".") {
  874. fmt.println(str)
  875. }
  876. }
  877. Output:
  878. a
  879. b
  880. c
  881. d
  882. e
  883. */
  884. split_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  885. return _split_iterator(s, sep, 0)
  886. }
  887. /*
  888. Splits the input string after every separator string in an iterator fashion.
  889. Destructively consumes the original string until the end.
  890. Inputs:
  891. - s: Pointer to the input string, which is modified during the search.
  892. - sep: The separator string to search for.
  893. Returns:
  894. A tuple containing the resulting substring and a boolean indicating success.
  895. Example:
  896. import "core:fmt"
  897. import "core:strings"
  898. split_after_iterator_example :: proc() {
  899. text := "a.b.c.d.e"
  900. for str in strings.split_after_iterator(&text, ".") {
  901. fmt.println(str)
  902. }
  903. }
  904. Output:
  905. a.
  906. b.
  907. c.
  908. d.
  909. e
  910. */
  911. split_after_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  912. return _split_iterator(s, sep, len(sep))
  913. }
  914. /*
  915. Trims the carriage return character from the end of the input string.
  916. *Used Internally - Private Function*
  917. Inputs:
  918. - s: The input string to trim.
  919. Returns:
  920. The trimmed string as a slice of the original.
  921. */
  922. @(private)
  923. _trim_cr :: proc(s: string) -> string {
  924. n := len(s)
  925. if n > 0 {
  926. if s[n-1] == '\r' {
  927. return s[:n-1]
  928. }
  929. }
  930. return s
  931. }
  932. /*
  933. Splits the input string at every line break `\n`.
  934. *Allocates Using Provided Allocator*
  935. Inputs:
  936. - s: The input string to split.
  937. - allocator: (default is context.allocator)
  938. Returns:
  939. A slice (allocated) of the split string (slices into original string)
  940. Example:
  941. import "core:fmt"
  942. import "core:strings"
  943. split_lines_example :: proc() {
  944. a := "a\nb\nc\nd\ne"
  945. b := strings.split_lines(a)
  946. fmt.println(b)
  947. }
  948. Output:
  949. ["a", "b", "c", "d", "e"]
  950. */
  951. split_lines :: proc(s: string, allocator := context.allocator) -> []string {
  952. sep :: "\n"
  953. lines := _split(s, sep, 0, -1, allocator)
  954. for line in &lines {
  955. line = _trim_cr(line)
  956. }
  957. return lines
  958. }
  959. /*
  960. Splits the input string at every line break `\n` for `n` parts.
  961. *Allocates Using Provided Allocator*
  962. Inputs:
  963. - s: The input string to split.
  964. - n: The number of parts to split into.
  965. - allocator: (default is context.allocator)
  966. Returns:
  967. A slice (allocated) of the split string (slices into original string)
  968. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  969. Example:
  970. import "core:fmt"
  971. import "core:strings"
  972. split_lines_n_example :: proc() {
  973. a := "a\nb\nc\nd\ne"
  974. b := strings.split_lines_n(a, 3)
  975. fmt.println(b)
  976. }
  977. Output:
  978. ["a", "b", "c\nd\ne"]
  979. */
  980. split_lines_n :: proc(s: string, n: int, allocator := context.allocator) -> []string {
  981. sep :: "\n"
  982. lines := _split(s, sep, 0, n, allocator)
  983. for line in &lines {
  984. line = _trim_cr(line)
  985. }
  986. return lines
  987. }
  988. /*
  989. Splits the input string at every line break `\n` leaving the `\n` in the resulting strings.
  990. *Allocates Using Provided Allocator*
  991. Inputs:
  992. - s: The input string to split.
  993. - allocator: (default is context.allocator)
  994. Returns:
  995. A slice (allocated) of the split string (slices into original string), with `\n` included.
  996. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  997. Example:
  998. import "core:fmt"
  999. import "core:strings"
  1000. split_lines_after_example :: proc() {
  1001. a := "a\nb\nc\nd\ne"
  1002. b := strings.split_lines_after(a)
  1003. fmt.println(b)
  1004. }
  1005. Output:
  1006. ["a\n", "b\n", "c\n", "d\n", "e"]
  1007. */
  1008. split_lines_after :: proc(s: string, allocator := context.allocator) -> []string {
  1009. sep :: "\n"
  1010. lines := _split(s, sep, len(sep), -1, allocator)
  1011. for line in &lines {
  1012. line = _trim_cr(line)
  1013. }
  1014. return lines
  1015. }
  1016. /*
  1017. Splits the input string at every line break `\n` leaving the `\n` in the resulting strings.
  1018. Only runs for n parts.
  1019. *Allocates Using Provided Allocator*
  1020. Inputs:
  1021. - s: The input string to split.
  1022. - n: The number of parts to split into.
  1023. - allocator: (default is context.allocator)
  1024. Returns:
  1025. A slice (allocated) of the split string (slices into original string), with `\n` included.
  1026. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  1027. Example:
  1028. import "core:fmt"
  1029. import "core:strings"
  1030. split_lines_after_n_example :: proc() {
  1031. a := "a\nb\nc\nd\ne"
  1032. b := strings.split_lines_after_n(a, 3)
  1033. fmt.println(b)
  1034. }
  1035. Output:
  1036. ["a\n", "b\n", "c\nd\ne"]
  1037. */
  1038. split_lines_after_n :: proc(s: string, n: int, allocator := context.allocator) -> []string {
  1039. sep :: "\n"
  1040. lines := _split(s, sep, len(sep), n, allocator)
  1041. for line in &lines {
  1042. line = _trim_cr(line)
  1043. }
  1044. return lines
  1045. }
  1046. /*
  1047. Splits the input string at every line break `\n`.
  1048. Returns the current split string every iteration until the string is consumed.
  1049. Inputs:
  1050. - s: Pointer to the input string, which is modified during the search.
  1051. Returns:
  1052. A tuple containing the resulting substring and a boolean indicating success.
  1053. Example:
  1054. import "core:fmt"
  1055. import "core:strings"
  1056. split_lines_iterator_example :: proc() {
  1057. text := "a\nb\nc\nd\ne"
  1058. for str in strings.split_lines_iterator(&text) {
  1059. fmt.print(str) // every loop -> a b c d e
  1060. }
  1061. fmt.print("\n")
  1062. }
  1063. Output:
  1064. abcde
  1065. */
  1066. split_lines_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  1067. sep :: "\n"
  1068. line = _split_iterator(s, sep, 0) or_return
  1069. return _trim_cr(line), true
  1070. }
  1071. /*
  1072. Splits the input string at every line break `\n`.
  1073. Returns the current split string with line breaks included every iteration until the string is consumed.
  1074. Inputs:
  1075. - s: Pointer to the input string, which is modified during the search.
  1076. Returns:
  1077. A tuple containing the resulting substring with line breaks included and a boolean indicating success.
  1078. Example:
  1079. import "core:fmt"
  1080. import "core:strings"
  1081. split_lines_after_iterator_example :: proc() {
  1082. text := "a\nb\nc\nd\ne\n"
  1083. for str in strings.split_lines_after_iterator(&text) {
  1084. fmt.print(str) // every loop -> a\n b\n c\n d\n e\n
  1085. }
  1086. }
  1087. Output:
  1088. a
  1089. b
  1090. c
  1091. d
  1092. e
  1093. */
  1094. split_lines_after_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  1095. sep :: "\n"
  1096. line = _split_iterator(s, sep, len(sep)) or_return
  1097. return _trim_cr(line), true
  1098. }
  1099. /*
  1100. Returns the byte offset of the first byte `c` in the string s it finds, -1 when not found.
  1101. NOTE: Can't find UTF-8 based runes.
  1102. Inputs:
  1103. - s: The input string to search in.
  1104. - c: The byte to search for.
  1105. Returns:
  1106. The byte offset of the first occurrence of `c` in `s`, or -1 if not found.
  1107. Example:
  1108. import "core:fmt"
  1109. import "core:strings"
  1110. index_byte_example :: proc() {
  1111. fmt.println(strings.index_byte("test", 't'))
  1112. fmt.println(strings.index_byte("test", 'e'))
  1113. fmt.println(strings.index_byte("test", 'x'))
  1114. fmt.println(strings.index_byte("teäst", 'ä'))
  1115. }
  1116. Output:
  1117. 0
  1118. 1
  1119. -1
  1120. -1
  1121. */
  1122. index_byte :: proc(s: string, c: byte) -> int {
  1123. for i := 0; i < len(s); i += 1 {
  1124. if s[i] == c {
  1125. return i
  1126. }
  1127. }
  1128. return -1
  1129. }
  1130. /*
  1131. Returns the byte offset of the last byte `c` in the string `s`, -1 when not found.
  1132. Inputs:
  1133. - s: The input string to search in.
  1134. - c: The byte to search for.
  1135. Returns:
  1136. The byte offset of the last occurrence of `c` in `s`, or -1 if not found.
  1137. NOTE: Can't find UTF-8 based runes.
  1138. Example:
  1139. import "core:fmt"
  1140. import "core:strings"
  1141. last_index_byte_example :: proc() {
  1142. fmt.println(strings.last_index_byte("test", 't'))
  1143. fmt.println(strings.last_index_byte("test", 'e'))
  1144. fmt.println(strings.last_index_byte("test", 'x'))
  1145. fmt.println(strings.last_index_byte("teäst", 'ä'))
  1146. }
  1147. Output:
  1148. 3
  1149. 1
  1150. -1
  1151. -1
  1152. */
  1153. last_index_byte :: proc(s: string, c: byte) -> int {
  1154. for i := len(s)-1; i >= 0; i -= 1 {
  1155. if s[i] == c {
  1156. return i
  1157. }
  1158. }
  1159. return -1
  1160. }
  1161. /*
  1162. Returns the byte offset of the first rune `r` in the string `s` it finds, -1 when not found.
  1163. Invalid runes return -1
  1164. Inputs:
  1165. - s: The input string to search in.
  1166. - r: The rune to search for.
  1167. Returns:
  1168. The byte offset of the first occurrence of `r` in `s`, or -1 if not found.
  1169. Example:
  1170. import "core:fmt"
  1171. import "core:strings"
  1172. index_rune_example :: proc() {
  1173. fmt.println(strings.index_rune("abcädef", 'x'))
  1174. fmt.println(strings.index_rune("abcädef", 'a'))
  1175. fmt.println(strings.index_rune("abcädef", 'b'))
  1176. fmt.println(strings.index_rune("abcädef", 'c'))
  1177. fmt.println(strings.index_rune("abcädef", 'ä'))
  1178. fmt.println(strings.index_rune("abcädef", 'd'))
  1179. fmt.println(strings.index_rune("abcädef", 'e'))
  1180. fmt.println(strings.index_rune("abcädef", 'f'))
  1181. }
  1182. Output:
  1183. -1
  1184. 0
  1185. 1
  1186. 2
  1187. 3
  1188. 5
  1189. 6
  1190. 7
  1191. */
  1192. index_rune :: proc(s: string, r: rune) -> int {
  1193. switch {
  1194. case u32(r) < utf8.RUNE_SELF:
  1195. return index_byte(s, byte(r))
  1196. case r == utf8.RUNE_ERROR:
  1197. for c, i in s {
  1198. if c == utf8.RUNE_ERROR {
  1199. return i
  1200. }
  1201. }
  1202. return -1
  1203. case !utf8.valid_rune(r):
  1204. return -1
  1205. }
  1206. b, w := utf8.encode_rune(r)
  1207. return index(s, string(b[:w]))
  1208. }
  1209. @private PRIME_RABIN_KARP :: 16777619
  1210. /*
  1211. Returns the byte offset of the string `substr` in the string `s`, -1 when not found.
  1212. Inputs:
  1213. - s: The input string to search in.
  1214. - substr: The substring to search for.
  1215. Returns:
  1216. The byte offset of the first occurrence of `substr` in `s`, or -1 if not found.
  1217. Example:
  1218. import "core:fmt"
  1219. import "core:strings"
  1220. index_example :: proc() {
  1221. fmt.println(strings.index("test", "t"))
  1222. fmt.println(strings.index("test", "te"))
  1223. fmt.println(strings.index("test", "st"))
  1224. fmt.println(strings.index("test", "tt"))
  1225. }
  1226. Output:
  1227. 0
  1228. 0
  1229. 2
  1230. -1
  1231. */
  1232. index :: proc(s, substr: string) -> int {
  1233. hash_str_rabin_karp :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  1234. for i := 0; i < len(s); i += 1 {
  1235. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  1236. }
  1237. sq := u32(PRIME_RABIN_KARP)
  1238. for i := len(s); i > 0; i >>= 1 {
  1239. if (i & 1) != 0 {
  1240. pow *= sq
  1241. }
  1242. sq *= sq
  1243. }
  1244. return
  1245. }
  1246. n := len(substr)
  1247. switch {
  1248. case n == 0:
  1249. return 0
  1250. case n == 1:
  1251. return index_byte(s, substr[0])
  1252. case n == len(s):
  1253. if s == substr {
  1254. return 0
  1255. }
  1256. return -1
  1257. case n > len(s):
  1258. return -1
  1259. }
  1260. hash, pow := hash_str_rabin_karp(substr)
  1261. h: u32
  1262. for i := 0; i < n; i += 1 {
  1263. h = h*PRIME_RABIN_KARP + u32(s[i])
  1264. }
  1265. if h == hash && s[:n] == substr {
  1266. return 0
  1267. }
  1268. for i := n; i < len(s); /**/ {
  1269. h *= PRIME_RABIN_KARP
  1270. h += u32(s[i])
  1271. h -= pow * u32(s[i-n])
  1272. i += 1
  1273. if h == hash && s[i-n:i] == substr {
  1274. return i - n
  1275. }
  1276. }
  1277. return -1
  1278. }
  1279. /*
  1280. Returns the last byte offset of the string `substr` in the string `s`, -1 when not found.
  1281. Inputs:
  1282. - s: The input string to search in.
  1283. - substr: The substring to search for.
  1284. Returns:
  1285. The byte offset of the last occurrence of `substr` in `s`, or -1 if not found.
  1286. Example:
  1287. import "core:fmt"
  1288. import "core:strings"
  1289. last_index_example :: proc() {
  1290. fmt.println(strings.last_index("test", "t"))
  1291. fmt.println(strings.last_index("test", "te"))
  1292. fmt.println(strings.last_index("test", "st"))
  1293. fmt.println(strings.last_index("test", "tt"))
  1294. }
  1295. Output:
  1296. 3
  1297. 0
  1298. 2
  1299. -1
  1300. */
  1301. last_index :: proc(s, substr: string) -> int {
  1302. hash_str_rabin_karp_reverse :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  1303. for i := len(s) - 1; i >= 0; i -= 1 {
  1304. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  1305. }
  1306. sq := u32(PRIME_RABIN_KARP)
  1307. for i := len(s); i > 0; i >>= 1 {
  1308. if (i & 1) != 0 {
  1309. pow *= sq
  1310. }
  1311. sq *= sq
  1312. }
  1313. return
  1314. }
  1315. n := len(substr)
  1316. switch {
  1317. case n == 0:
  1318. return len(s)
  1319. case n == 1:
  1320. return last_index_byte(s, substr[0])
  1321. case n == len(s):
  1322. return 0 if substr == s else -1
  1323. case n > len(s):
  1324. return -1
  1325. }
  1326. hash, pow := hash_str_rabin_karp_reverse(substr)
  1327. last := len(s) - n
  1328. h: u32
  1329. for i := len(s)-1; i >= last; i -= 1 {
  1330. h = h*PRIME_RABIN_KARP + u32(s[i])
  1331. }
  1332. if h == hash && s[last:] == substr {
  1333. return last
  1334. }
  1335. for i := last-1; i >= 0; i -= 1 {
  1336. h *= PRIME_RABIN_KARP
  1337. h += u32(s[i])
  1338. h -= pow * u32(s[i+n])
  1339. if h == hash && s[i:i+n] == substr {
  1340. return i
  1341. }
  1342. }
  1343. return -1
  1344. }
  1345. /*
  1346. Returns the index of any first char of `chars` found in `s`, -1 if not found.
  1347. Inputs:
  1348. - s: The input string to search in.
  1349. - chars: The characters to look for
  1350. Returns:
  1351. The index of the first character of `chars` found in `s`, or -1 if not found.
  1352. Example:
  1353. import "core:fmt"
  1354. import "core:strings"
  1355. index_any_example :: proc() {
  1356. fmt.println(strings.index_any("test", "s"))
  1357. fmt.println(strings.index_any("test", "se"))
  1358. fmt.println(strings.index_any("test", "et"))
  1359. fmt.println(strings.index_any("test", "set"))
  1360. fmt.println(strings.index_any("test", "x"))
  1361. }
  1362. Output:
  1363. 2
  1364. 1
  1365. 0
  1366. 0
  1367. -1
  1368. */
  1369. index_any :: proc(s, chars: string) -> int {
  1370. if chars == "" {
  1371. return -1
  1372. }
  1373. if len(chars) == 1 {
  1374. r := rune(chars[0])
  1375. if r >= utf8.RUNE_SELF {
  1376. r = utf8.RUNE_ERROR
  1377. }
  1378. return index_rune(s, r)
  1379. }
  1380. if len(s) > 8 {
  1381. if as, ok := ascii_set_make(chars); ok {
  1382. for i in 0..<len(s) {
  1383. if ascii_set_contains(as, s[i]) {
  1384. return i
  1385. }
  1386. }
  1387. return -1
  1388. }
  1389. }
  1390. for c, i in s {
  1391. if index_rune(chars, c) >= 0 {
  1392. return i
  1393. }
  1394. }
  1395. return -1
  1396. }
  1397. /*
  1398. Finds the last occurrence of any character in `chars` within `s`. Iterates in reverse.
  1399. Inputs:
  1400. - s: The string to search in
  1401. - chars: The characters to look for
  1402. Returns:
  1403. The index of the last matching character, or -1 if not found
  1404. Example:
  1405. import "core:fmt"
  1406. import "core:strings"
  1407. last_index_any_example :: proc() {
  1408. fmt.println(strings.last_index_any("test", "s"))
  1409. fmt.println(strings.last_index_any("test", "se"))
  1410. fmt.println(strings.last_index_any("test", "et"))
  1411. fmt.println(strings.last_index_any("test", "set"))
  1412. fmt.println(strings.last_index_any("test", "x"))
  1413. }
  1414. Output:
  1415. 2
  1416. 2
  1417. 3
  1418. 3
  1419. -1
  1420. */
  1421. last_index_any :: proc(s, chars: string) -> int {
  1422. if chars == "" {
  1423. return -1
  1424. }
  1425. if len(s) == 1 {
  1426. r := rune(s[0])
  1427. if r >= utf8.RUNE_SELF {
  1428. r = utf8.RUNE_ERROR
  1429. }
  1430. return index_rune(chars, r)
  1431. }
  1432. if len(s) > 8 {
  1433. if as, ok := ascii_set_make(chars); ok {
  1434. for i := len(s)-1; i >= 0; i -= 1 {
  1435. if ascii_set_contains(as, s[i]) {
  1436. return i
  1437. }
  1438. }
  1439. return -1
  1440. }
  1441. }
  1442. if len(chars) == 1 {
  1443. r := rune(chars[0])
  1444. if r >= utf8.RUNE_SELF {
  1445. r = utf8.RUNE_ERROR
  1446. }
  1447. for i := len(s); i > 0; /**/ {
  1448. c, w := utf8.decode_last_rune_in_string(s[:i])
  1449. i -= w
  1450. if c == r {
  1451. return i
  1452. }
  1453. }
  1454. return -1
  1455. }
  1456. for i := len(s); i > 0; /**/ {
  1457. r, w := utf8.decode_last_rune_in_string(s[:i])
  1458. i -= w
  1459. if index_rune(chars, r) >= 0 {
  1460. return i
  1461. }
  1462. }
  1463. return -1
  1464. }
  1465. /*
  1466. Finds the first occurrence of any substring in `substrs` within `s`
  1467. Inputs:
  1468. - s: The string to search in
  1469. - substrs: The substrings to look for
  1470. Returns:
  1471. A tuple containing the index of the first matching substring, and its length (width)
  1472. */
  1473. index_multi :: proc(s: string, substrs: []string) -> (idx: int, width: int) {
  1474. idx = -1
  1475. if s == "" || len(substrs) <= 0 {
  1476. return
  1477. }
  1478. // disallow "" substr
  1479. for substr in substrs {
  1480. if len(substr) == 0 {
  1481. return
  1482. }
  1483. }
  1484. lowest_index := len(s)
  1485. found := false
  1486. for substr in substrs {
  1487. if i := index(s, substr); i >= 0 {
  1488. if i < lowest_index {
  1489. lowest_index = i
  1490. width = len(substr)
  1491. found = true
  1492. }
  1493. }
  1494. }
  1495. if found {
  1496. idx = lowest_index
  1497. }
  1498. return
  1499. }
  1500. /*
  1501. Counts the number of non-overlapping occurrences of `substr` in `s`
  1502. Inputs:
  1503. - s: The string to search in
  1504. - substr: The substring to count
  1505. Returns:
  1506. The number of occurrences of `substr` in `s`, returns the rune_count + 1 of the string `s` on empty `substr`
  1507. Example:
  1508. import "core:fmt"
  1509. import "core:strings"
  1510. count_example :: proc() {
  1511. fmt.println(strings.count("abbccc", "a"))
  1512. fmt.println(strings.count("abbccc", "b"))
  1513. fmt.println(strings.count("abbccc", "c"))
  1514. fmt.println(strings.count("abbccc", "ab"))
  1515. fmt.println(strings.count("abbccc", " "))
  1516. }
  1517. Output:
  1518. 1
  1519. 2
  1520. 3
  1521. 1
  1522. 0
  1523. */
  1524. count :: proc(s, substr: string) -> int {
  1525. if len(substr) == 0 { // special case
  1526. return rune_count(s) + 1
  1527. }
  1528. if len(substr) == 1 {
  1529. c := substr[0]
  1530. switch len(s) {
  1531. case 0:
  1532. return 0
  1533. case 1:
  1534. return int(s[0] == c)
  1535. }
  1536. n := 0
  1537. for i := 0; i < len(s); i += 1 {
  1538. if s[i] == c {
  1539. n += 1
  1540. }
  1541. }
  1542. return n
  1543. }
  1544. // TODO(bill): Use a non-brute for approach
  1545. n := 0
  1546. str := s
  1547. for {
  1548. i := index(str, substr)
  1549. if i == -1 {
  1550. return n
  1551. }
  1552. n += 1
  1553. str = str[i+len(substr):]
  1554. }
  1555. return n
  1556. }
  1557. /*
  1558. Repeats the string `s` `count` times, concatenating the result
  1559. *Allocates Using Provided Allocator*
  1560. Inputs:
  1561. - s: The string to repeat
  1562. - count: The number of times to repeat `s`
  1563. - allocator: (default is context.allocator)
  1564. Returns:
  1565. The concatenated repeated string
  1566. WARNING: Panics if count < 0
  1567. Example:
  1568. import "core:fmt"
  1569. import "core:strings"
  1570. repeat_example :: proc() {
  1571. fmt.println(strings.repeat("abc", 2))
  1572. }
  1573. Output:
  1574. abcabc
  1575. */
  1576. repeat :: proc(s: string, count: int, allocator := context.allocator) -> string {
  1577. if count < 0 {
  1578. panic("strings: negative repeat count")
  1579. } else if count > 0 && (len(s)*count)/count != len(s) {
  1580. panic("strings: repeat count will cause an overflow")
  1581. }
  1582. b := make([]byte, len(s)*count, allocator)
  1583. i := copy(b, s)
  1584. for i < len(b) { // 2^N trick to reduce the need to copy
  1585. copy(b[i:], b[:i])
  1586. i *= 2
  1587. }
  1588. return string(b)
  1589. }
  1590. /*
  1591. Replaces all occurrences of `old` in `s` with `new`
  1592. *Allocates Using Provided Allocator*
  1593. Inputs:
  1594. - s: The string to modify
  1595. - old: The substring to replace
  1596. - new: The substring to replace `old` with
  1597. - allocator: The allocator to use for the new string (default is context.allocator)
  1598. Returns:
  1599. A tuple containing the modified string and a boolean indicating if an allocation occurred during the replacement
  1600. Example:
  1601. import "core:fmt"
  1602. import "core:strings"
  1603. replace_all_example :: proc() {
  1604. fmt.println(strings.replace_all("xyzxyz", "xyz", "abc"))
  1605. fmt.println(strings.replace_all("xyzxyz", "abc", "xyz"))
  1606. fmt.println(strings.replace_all("xyzxyz", "xy", "z"))
  1607. }
  1608. Output:
  1609. abcabc true
  1610. xyzxyz false
  1611. zzzz true
  1612. */
  1613. replace_all :: proc(s, old, new: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1614. return replace(s, old, new, -1, allocator)
  1615. }
  1616. /*
  1617. Replaces n instances of old in the string s with the new string
  1618. *Allocates Using Provided Allocator*
  1619. Inputs:
  1620. - s: The input string
  1621. - old: The substring to be replaced
  1622. - new: The replacement string
  1623. - n: The number of instances to replace (if `n < 0`, no limit on the number of replacements)
  1624. - allocator: (default: context.allocator)
  1625. Returns:
  1626. A tuple containing the modified string and a boolean indicating if an allocation occurred during the replacement
  1627. Example:
  1628. import "core:fmt"
  1629. import "core:strings"
  1630. replace_example :: proc() {
  1631. fmt.println(strings.replace("xyzxyz", "xyz", "abc", 2))
  1632. fmt.println(strings.replace("xyzxyz", "xyz", "abc", 1))
  1633. fmt.println(strings.replace("xyzxyz", "abc", "xyz", -1))
  1634. fmt.println(strings.replace("xyzxyz", "xy", "z", -1))
  1635. }
  1636. Output:
  1637. abcabc true
  1638. abcxyz true
  1639. xyzxyz false
  1640. zzzz true
  1641. */
  1642. replace :: proc(s, old, new: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1643. if old == new || n == 0 {
  1644. was_allocation = false
  1645. output = s
  1646. return
  1647. }
  1648. byte_count := n
  1649. if m := count(s, old); m == 0 {
  1650. was_allocation = false
  1651. output = s
  1652. return
  1653. } else if n < 0 || m < n {
  1654. byte_count = m
  1655. }
  1656. t := make([]byte, len(s) + byte_count*(len(new) - len(old)), allocator)
  1657. was_allocation = true
  1658. w := 0
  1659. start := 0
  1660. for i := 0; i < byte_count; i += 1 {
  1661. j := start
  1662. if len(old) == 0 {
  1663. if i > 0 {
  1664. _, width := utf8.decode_rune_in_string(s[start:])
  1665. j += width
  1666. }
  1667. } else {
  1668. j += index(s[start:], old)
  1669. }
  1670. w += copy(t[w:], s[start:j])
  1671. w += copy(t[w:], new)
  1672. start = j + len(old)
  1673. }
  1674. w += copy(t[w:], s[start:])
  1675. output = string(t[0:w])
  1676. return
  1677. }
  1678. /*
  1679. Removes the key string `n` times from the `s` string
  1680. *Allocates Using Provided Allocator*
  1681. Inputs:
  1682. - s: The input string
  1683. - key: The substring to be removed
  1684. - n: The number of instances to remove (if `n < 0`, no limit on the number of removes)
  1685. - allocator: (default: context.allocator)
  1686. Returns:
  1687. A tuple containing the modified string and a boolean indicating if an allocation occurred during the removal
  1688. Example:
  1689. import "core:fmt"
  1690. import "core:strings"
  1691. remove_example :: proc() {
  1692. fmt.println(strings.remove("abcabc", "abc", 1))
  1693. fmt.println(strings.remove("abcabc", "abc", -1))
  1694. fmt.println(strings.remove("abcabc", "a", -1))
  1695. fmt.println(strings.remove("abcabc", "x", -1))
  1696. }
  1697. Output:
  1698. abc true
  1699. true
  1700. bcbc true
  1701. abcabc false
  1702. */
  1703. remove :: proc(s, key: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1704. return replace(s, key, "", n, allocator)
  1705. }
  1706. /*
  1707. Removes all the `key` string instances from the `s` string
  1708. *Allocates Using Provided Allocator*
  1709. Inputs:
  1710. - s: The input string
  1711. - key: The substring to be removed
  1712. - allocator: (default: context.allocator)
  1713. Returns:
  1714. A tuple containing the modified string and a boolean indicating if an allocation occurred during the removal
  1715. Example:
  1716. import "core:fmt"
  1717. import "core:strings"
  1718. remove_all_example :: proc() {
  1719. fmt.println(strings.remove_all("abcabc", "abc"))
  1720. fmt.println(strings.remove_all("abcabc", "a"))
  1721. fmt.println(strings.remove_all("abcabc", "x"))
  1722. }
  1723. Output:
  1724. true
  1725. bcbc true
  1726. abcabc false
  1727. */
  1728. remove_all :: proc(s, key: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1729. return remove(s, key, -1, allocator)
  1730. }
  1731. // Returns true if is an ASCII space character ('\t', '\n', '\v', '\f', '\r', ' ')
  1732. @(private) _ascii_space := [256]bool{'\t' = true, '\n' = true, '\v' = true, '\f' = true, '\r' = true, ' ' = true}
  1733. // Returns true when the `r` rune is '\t', '\n', '\v', '\f', '\r' or ' '
  1734. is_ascii_space :: proc(r: rune) -> bool {
  1735. if r < utf8.RUNE_SELF {
  1736. return _ascii_space[u8(r)]
  1737. }
  1738. return false
  1739. }
  1740. // Returns true if the `r` rune is any ASCII or UTF-8 based whitespace character
  1741. is_space :: proc(r: rune) -> bool {
  1742. if r < 0x2000 {
  1743. switch r {
  1744. case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xa0, 0x1680:
  1745. return true
  1746. }
  1747. } else {
  1748. if r <= 0x200a {
  1749. return true
  1750. }
  1751. switch r {
  1752. case 0x2028, 0x2029, 0x202f, 0x205f, 0x3000:
  1753. return true
  1754. }
  1755. }
  1756. return false
  1757. }
  1758. // Returns true if the `r` rune is a null-byte (`0x0`)
  1759. is_null :: proc(r: rune) -> bool {
  1760. return r == 0x0000
  1761. }
  1762. /*
  1763. Find the index of the first rune `r` in string `s` for which procedure `p` returns the same as truth, or -1 if no such rune appears.
  1764. Inputs:
  1765. - s: The input string
  1766. - p: A procedure that takes a rune and returns a boolean
  1767. - truth: The boolean value to be matched (default: `true`)
  1768. Returns:
  1769. The index of the first matching rune, or -1 if no match was found
  1770. Example:
  1771. import "core:fmt"
  1772. import "core:strings"
  1773. index_proc_example :: proc() {
  1774. call :: proc(r: rune) -> bool {
  1775. return r == 'a'
  1776. }
  1777. fmt.println(strings.index_proc("abcabc", call))
  1778. fmt.println(strings.index_proc("cbacba", call))
  1779. fmt.println(strings.index_proc("cbacba", call, false))
  1780. fmt.println(strings.index_proc("abcabc", call, false))
  1781. fmt.println(strings.index_proc("xyz", call))
  1782. }
  1783. Output:
  1784. 0
  1785. 2
  1786. 0
  1787. 1
  1788. -1
  1789. */
  1790. index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  1791. for r, i in s {
  1792. if p(r) == truth {
  1793. return i
  1794. }
  1795. }
  1796. return -1
  1797. }
  1798. // Same as `index_proc`, but the procedure p takes a raw pointer for state
  1799. index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  1800. for r, i in s {
  1801. if p(state, r) == truth {
  1802. return i
  1803. }
  1804. }
  1805. return -1
  1806. }
  1807. // Finds the index of the *last* rune in the string s for which the procedure p returns the same value as truth
  1808. last_index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  1809. // TODO(bill): Probably use Rabin-Karp Search
  1810. for i := len(s); i > 0; {
  1811. r, size := utf8.decode_last_rune_in_string(s[:i])
  1812. i -= size
  1813. if p(r) == truth {
  1814. return i
  1815. }
  1816. }
  1817. return -1
  1818. }
  1819. // Same as `index_proc_with_state`, runs through the string in reverse
  1820. last_index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  1821. // TODO(bill): Probably use Rabin-Karp Search
  1822. for i := len(s); i > 0; {
  1823. r, size := utf8.decode_last_rune_in_string(s[:i])
  1824. i -= size
  1825. if p(state, r) == truth {
  1826. return i
  1827. }
  1828. }
  1829. return -1
  1830. }
  1831. /*
  1832. Trims the input string `s` from the left until the procedure `p` returns false
  1833. Inputs:
  1834. - s: The input string
  1835. - p: A procedure that takes a rune and returns a boolean
  1836. Returns:
  1837. The trimmed string as a slice of the original
  1838. Example:
  1839. import "core:fmt"
  1840. import "core:strings"
  1841. trim_left_proc_example :: proc() {
  1842. find :: proc(r: rune) -> bool {
  1843. return r == 'x'
  1844. }
  1845. fmt.println(strings.trim_left_proc("xxxxxxtesting", find))
  1846. }
  1847. Output:
  1848. testing
  1849. */
  1850. trim_left_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  1851. i := index_proc(s, p, false)
  1852. if i == -1 {
  1853. return ""
  1854. }
  1855. return s[i:]
  1856. }
  1857. /*
  1858. Trims the input string `s` from the left until the procedure `p` with state returns false
  1859. Inputs:
  1860. - s: The input string
  1861. - p: A procedure that takes a raw pointer and a rune and returns a boolean
  1862. - state: The raw pointer to be passed to the procedure `p`
  1863. Returns:
  1864. The trimmed string as a slice of the original
  1865. */
  1866. trim_left_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  1867. i := index_proc_with_state(s, p, state, false)
  1868. if i == -1 {
  1869. return ""
  1870. }
  1871. return s[i:]
  1872. }
  1873. /*
  1874. Trims the input string `s` from the right until the procedure `p` returns `false`
  1875. Inputs:
  1876. - s: The input string
  1877. - p: A procedure that takes a rune and returns a boolean
  1878. Returns:
  1879. The trimmed string as a slice of the original
  1880. Example:
  1881. import "core:fmt"
  1882. import "core:strings"
  1883. trim_right_proc_example :: proc() {
  1884. find :: proc(r: rune) -> bool {
  1885. return r != 't'
  1886. }
  1887. fmt.println(strings.trim_right_proc("testing", find))
  1888. }
  1889. Output:
  1890. test
  1891. */
  1892. trim_right_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  1893. i := last_index_proc(s, p, false)
  1894. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  1895. _, w := utf8.decode_rune_in_string(s[i:])
  1896. i += w
  1897. } else {
  1898. i += 1
  1899. }
  1900. return s[0:i]
  1901. }
  1902. /*
  1903. Trims the input string `s` from the right until the procedure `p` with state returns `false`
  1904. Inputs:
  1905. - s: The input string
  1906. - p: A procedure that takes a raw pointer and a rune and returns a boolean
  1907. - state: The raw pointer to be passed to the procedure `p`
  1908. Returns:
  1909. The trimmed string as a slice of the original, empty when no match
  1910. */
  1911. trim_right_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  1912. i := last_index_proc_with_state(s, p, state, false)
  1913. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  1914. _, w := utf8.decode_rune_in_string(s[i:])
  1915. i += w
  1916. } else {
  1917. i += 1
  1918. }
  1919. return s[0:i]
  1920. }
  1921. // Procedure for `trim_*_proc` variants, which has a string rawptr cast + rune comparison
  1922. is_in_cutset :: proc(state: rawptr, r: rune) -> bool {
  1923. if state == nil {
  1924. return false
  1925. }
  1926. cutset := (^string)(state)^
  1927. for c in cutset {
  1928. if r == c {
  1929. return true
  1930. }
  1931. }
  1932. return false
  1933. }
  1934. /*
  1935. Trims the cutset string from the `s` string
  1936. Inputs:
  1937. - s: The input string
  1938. - cutset: The set of characters to be trimmed from the left of the input string
  1939. Returns:
  1940. The trimmed string as a slice of the original
  1941. */
  1942. trim_left :: proc(s: string, cutset: string) -> string {
  1943. if s == "" || cutset == "" {
  1944. return s
  1945. }
  1946. state := cutset
  1947. return trim_left_proc_with_state(s, is_in_cutset, &state)
  1948. }
  1949. /*
  1950. Trims the cutset string from the `s` string from the right
  1951. Inputs:
  1952. - s: The input string
  1953. - cutset: The set of characters to be trimmed from the right of the input string
  1954. Returns:
  1955. The trimmed string as a slice of the original
  1956. */
  1957. trim_right :: proc(s: string, cutset: string) -> string {
  1958. if s == "" || cutset == "" {
  1959. return s
  1960. }
  1961. state := cutset
  1962. return trim_right_proc_with_state(s, is_in_cutset, &state)
  1963. }
  1964. /*
  1965. Trims the cutset string from the `s` string, both from left and right
  1966. Inputs:
  1967. - s: The input string
  1968. - cutset: The set of characters to be trimmed from both sides of the input string
  1969. Returns:
  1970. The trimmed string as a slice of the original
  1971. */
  1972. trim :: proc(s: string, cutset: string) -> string {
  1973. return trim_right(trim_left(s, cutset), cutset)
  1974. }
  1975. /*
  1976. Trims until a valid non-space rune from the left, "\t\txyz\t\t" -> "xyz\t\t"
  1977. Inputs:
  1978. - s: The input string
  1979. Returns:
  1980. The trimmed string as a slice of the original
  1981. */
  1982. trim_left_space :: proc(s: string) -> string {
  1983. return trim_left_proc(s, is_space)
  1984. }
  1985. /*
  1986. Trims from the right until a valid non-space rune, "\t\txyz\t\t" -> "\t\txyz"
  1987. Inputs:
  1988. - s: The input string
  1989. Returns:
  1990. The trimmed string as a slice of the original
  1991. */
  1992. trim_right_space :: proc(s: string) -> string {
  1993. return trim_right_proc(s, is_space)
  1994. }
  1995. /*
  1996. Trims from both sides until a valid non-space rune, "\t\txyz\t\t" -> "xyz"
  1997. Inputs:
  1998. - s: The input string
  1999. Returns:
  2000. The trimmed string as a slice of the original
  2001. */
  2002. trim_space :: proc(s: string) -> string {
  2003. return trim_right_space(trim_left_space(s))
  2004. }
  2005. /*
  2006. Trims null runes from the left, "\x00\x00testing\x00\x00" -> "testing\x00\x00"
  2007. Inputs:
  2008. - s: The input string
  2009. Returns:
  2010. The trimmed string as a slice of the original
  2011. */
  2012. trim_left_null :: proc(s: string) -> string {
  2013. return trim_left_proc(s, is_null)
  2014. }
  2015. /*
  2016. Trims null runes from the right, "\x00\x00testing\x00\x00" -> "\x00\x00testing"
  2017. Inputs:
  2018. - s: The input string
  2019. Returns:
  2020. The trimmed string as a slice of the original
  2021. */
  2022. trim_right_null :: proc(s: string) -> string {
  2023. return trim_right_proc(s, is_null)
  2024. }
  2025. /*
  2026. Trims null runes from both sides, "\x00\x00testing\x00\x00" -> "testing"
  2027. Inputs:
  2028. - s: The input string
  2029. Returns:
  2030. The trimmed string as a slice of the original
  2031. */
  2032. trim_null :: proc(s: string) -> string {
  2033. return trim_right_null(trim_left_null(s))
  2034. }
  2035. /*
  2036. Trims a `prefix` string from the start of the `s` string and returns the trimmed string
  2037. Inputs:
  2038. - s: The input string
  2039. - prefix: The prefix string to be removed
  2040. Returns:
  2041. The trimmed string as a slice of original, or the input string if no prefix was found
  2042. Example:
  2043. import "core:fmt"
  2044. import "core:strings"
  2045. trim_prefix_example :: proc() {
  2046. fmt.println(strings.trim_prefix("testing", "test"))
  2047. fmt.println(strings.trim_prefix("testing", "abc"))
  2048. }
  2049. Output:
  2050. ing
  2051. testing
  2052. */
  2053. trim_prefix :: proc(s, prefix: string) -> string {
  2054. if has_prefix(s, prefix) {
  2055. return s[len(prefix):]
  2056. }
  2057. return s
  2058. }
  2059. /*
  2060. Trims a `suffix` string from the end of the `s` string and returns the trimmed string
  2061. Inputs:
  2062. - s: The input string
  2063. - suffix: The suffix string to be removed
  2064. Returns:
  2065. The trimmed string as a slice of original, or the input string if no suffix was found
  2066. Example:
  2067. import "core:fmt"
  2068. import "core:strings"
  2069. trim_suffix_example :: proc() {
  2070. fmt.println(strings.trim_suffix("todo.txt", ".txt"))
  2071. fmt.println(strings.trim_suffix("todo.doc", ".txt"))
  2072. }
  2073. Output:
  2074. todo
  2075. todo.doc
  2076. */
  2077. trim_suffix :: proc(s, suffix: string) -> string {
  2078. if has_suffix(s, suffix) {
  2079. return s[:len(s)-len(suffix)]
  2080. }
  2081. return s
  2082. }
  2083. /*
  2084. Splits the input string `s` by all possible `substrs` and returns an allocated array of strings
  2085. *Allocates Using Provided Allocator*
  2086. Inputs:
  2087. - s: The input string
  2088. - substrs: An array of substrings used for splitting
  2089. - allocator: (default is context.allocator)
  2090. Returns:
  2091. An array of strings, or nil on empty substring or no matches
  2092. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  2093. Example:
  2094. import "core:fmt"
  2095. import "core:strings"
  2096. split_multi_example :: proc() {
  2097. splits := [?]string { "---", "~~~", ".", "_", "," }
  2098. res := strings.split_multi("testing,this.out_nice---done~~~last", splits[:])
  2099. fmt.println(res) // -> [testing, this, out, nice, done, last]
  2100. }
  2101. Output:
  2102. ["testing", "this", "out", "nice", "done", "last"]
  2103. */
  2104. split_multi :: proc(s: string, substrs: []string, allocator := context.allocator) -> []string #no_bounds_check {
  2105. if s == "" || len(substrs) <= 0 {
  2106. return nil
  2107. }
  2108. // disallow "" substr
  2109. for substr in substrs {
  2110. if len(substr) == 0 {
  2111. return nil
  2112. }
  2113. }
  2114. // calculate the needed len of `results`
  2115. n := 1
  2116. for it := s; len(it) > 0; {
  2117. i, w := index_multi(it, substrs)
  2118. if i < 0 {
  2119. break
  2120. }
  2121. n += 1
  2122. it = it[i+w:]
  2123. }
  2124. results := make([dynamic]string, 0, n, allocator)
  2125. {
  2126. it := s
  2127. for len(it) > 0 {
  2128. i, w := index_multi(it, substrs)
  2129. if i < 0 {
  2130. break
  2131. }
  2132. part := it[:i]
  2133. append(&results, part)
  2134. it = it[i+w:]
  2135. }
  2136. append(&results, it)
  2137. }
  2138. assert(len(results) == n)
  2139. return results[:]
  2140. }
  2141. /*
  2142. Splits the input string `s` by all possible `substrs` in an iterator fashion. The full string is returned if no match.
  2143. Inputs:
  2144. - it: A pointer to the input string
  2145. - substrs: An array of substrings used for splitting
  2146. Returns:
  2147. A tuple containing the split string and a boolean indicating success or failure
  2148. Example:
  2149. import "core:fmt"
  2150. import "core:strings"
  2151. split_multi_iterate_example :: proc() {
  2152. it := "testing,this.out_nice---done~~~last"
  2153. splits := [?]string { "---", "~~~", ".", "_", "," }
  2154. for str in strings.split_multi_iterate(&it, splits[:]) {
  2155. fmt.println(str)
  2156. }
  2157. }
  2158. Output:
  2159. testing
  2160. this
  2161. out
  2162. nice
  2163. done
  2164. last
  2165. */
  2166. split_multi_iterate :: proc(it: ^string, substrs: []string) -> (res: string, ok: bool) #no_bounds_check {
  2167. if it == nil || len(it) == 0 || len(substrs) <= 0 {
  2168. return
  2169. }
  2170. // disallow "" substr
  2171. for substr in substrs {
  2172. if len(substr) == 0 {
  2173. return
  2174. }
  2175. }
  2176. // calculate the needed len of `results`
  2177. i, w := index_multi(it^, substrs)
  2178. if i >= 0 {
  2179. res = it[:i]
  2180. it^ = it[i+w:]
  2181. } else {
  2182. // last value
  2183. res = it^
  2184. it^ = it[len(it):]
  2185. }
  2186. ok = true
  2187. return
  2188. }
  2189. /*
  2190. Replaces invalid UTF-8 characters in the input string with a specified replacement string. Adjacent invalid bytes are only replaced once.
  2191. *Allocates Using Provided Allocator*
  2192. Inputs:
  2193. - s: The input string
  2194. - replacement: The string used to replace invalid UTF-8 characters
  2195. - allocator: (default is context.allocator)
  2196. Returns:
  2197. A new string with invalid UTF-8 characters replaced
  2198. Example:
  2199. import "core:fmt"
  2200. import "core:strings"
  2201. scrub_example :: proc() {
  2202. text := "Hello\xC0\x80World"
  2203. fmt.println(strings.scrub(text, "?")) // -> "Hello?World"
  2204. }
  2205. Output:
  2206. Hello?
  2207. */
  2208. scrub :: proc(s: string, replacement: string, allocator := context.allocator) -> string {
  2209. str := s
  2210. b: Builder
  2211. builder_init(&b, 0, len(s), allocator)
  2212. has_error := false
  2213. cursor := 0
  2214. origin := str
  2215. for len(str) > 0 {
  2216. r, w := utf8.decode_rune_in_string(str)
  2217. if r == utf8.RUNE_ERROR {
  2218. if !has_error {
  2219. has_error = true
  2220. write_string(&b, origin[:cursor])
  2221. }
  2222. } else if has_error {
  2223. has_error = false
  2224. write_string(&b, replacement)
  2225. origin = origin[cursor:]
  2226. cursor = 0
  2227. }
  2228. cursor += w
  2229. str = str[w:]
  2230. }
  2231. return to_string(b)
  2232. }
  2233. /*
  2234. Reverses the input string `s`
  2235. *Allocates Using Provided Allocator*
  2236. Inputs:
  2237. - s: The input string
  2238. - allocator: (default is context.allocator)
  2239. Returns:
  2240. A reversed version of the input string
  2241. Example:
  2242. import "core:fmt"
  2243. import "core:strings"
  2244. reverse_example :: proc() {
  2245. a := "abcxyz"
  2246. b := strings.reverse(a)
  2247. fmt.println(a, b)
  2248. }
  2249. Output:
  2250. abcxyz zyxcba
  2251. */
  2252. reverse :: proc(s: string, allocator := context.allocator) -> string {
  2253. str := s
  2254. n := len(str)
  2255. buf := make([]byte, n)
  2256. i := n
  2257. for len(str) > 0 {
  2258. _, w := utf8.decode_rune_in_string(str)
  2259. i -= w
  2260. copy(buf[i:], str[:w])
  2261. str = str[w:]
  2262. }
  2263. return string(buf)
  2264. }
  2265. /*
  2266. Expands the input string by replacing tab characters with spaces to align to a specified tab size
  2267. *Allocates Using Provided Allocator*
  2268. Inputs:
  2269. - s: The input string
  2270. - tab_size: The number of spaces to use for each tab character
  2271. - allocator: (default is context.allocator)
  2272. Returns:
  2273. A new string with tab characters expanded to the specified tab size
  2274. WARNING: Panics if tab_size <= 0
  2275. Example:
  2276. import "core:fmt"
  2277. import "core:strings"
  2278. expand_tabs_example :: proc() {
  2279. text := "abc1\tabc2\tabc3"
  2280. fmt.println(strings.expand_tabs(text, 4))
  2281. }
  2282. Output:
  2283. abc1 abc2 abc3
  2284. */
  2285. expand_tabs :: proc(s: string, tab_size: int, allocator := context.allocator) -> string {
  2286. if tab_size <= 0 {
  2287. panic("tab size must be positive")
  2288. }
  2289. if s == "" {
  2290. return ""
  2291. }
  2292. b: Builder
  2293. builder_init(&b, allocator)
  2294. writer := to_writer(&b)
  2295. str := s
  2296. column: int
  2297. for len(str) > 0 {
  2298. r, w := utf8.decode_rune_in_string(str)
  2299. if r == '\t' {
  2300. expand := tab_size - column%tab_size
  2301. for i := 0; i < expand; i += 1 {
  2302. io.write_byte(writer, ' ')
  2303. }
  2304. column += expand
  2305. } else {
  2306. if r == '\n' {
  2307. column = 0
  2308. } else {
  2309. column += w
  2310. }
  2311. io.write_rune(writer, r)
  2312. }
  2313. str = str[w:]
  2314. }
  2315. return to_string(b)
  2316. }
  2317. /*
  2318. Splits the input string `str` by the separator `sep` string and returns 3 parts. The values are slices of the original string.
  2319. Inputs:
  2320. - str: The input string
  2321. - sep: The separator string
  2322. Returns:
  2323. A tuple with `head` (before the split), `match` (the separator), and `tail` (the end of the split) strings
  2324. Example:
  2325. import "core:fmt"
  2326. import "core:strings"
  2327. partition_example :: proc() {
  2328. text := "testing this out"
  2329. head, match, tail := strings.partition(text, " this ") // -> head: "testing", match: " this ", tail: "out"
  2330. fmt.println(head, match, tail)
  2331. head, match, tail = strings.partition(text, "hi") // -> head: "testing t", match: "hi", tail: "s out"
  2332. fmt.println(head, match, tail)
  2333. head, match, tail = strings.partition(text, "xyz") // -> head: "testing this out", match: "", tail: ""
  2334. fmt.println(head)
  2335. fmt.println(match == "")
  2336. fmt.println(tail == "")
  2337. }
  2338. Output:
  2339. testing this out
  2340. testing t hi s out
  2341. testing this out
  2342. true
  2343. true
  2344. */
  2345. partition :: proc(str, sep: string) -> (head, match, tail: string) {
  2346. i := index(str, sep)
  2347. if i == -1 {
  2348. head = str
  2349. return
  2350. }
  2351. head = str[:i]
  2352. match = str[i:i+len(sep)]
  2353. tail = str[i+len(sep):]
  2354. return
  2355. }
  2356. // Alias for centre_justify
  2357. center_justify :: centre_justify // NOTE(bill): Because Americans exist
  2358. /*
  2359. Centers the input string within a field of specified length by adding pad string on both sides, if its length is less than the target length.
  2360. *Allocates Using Provided Allocator*
  2361. Inputs:
  2362. - str: The input string
  2363. - length: The desired length of the centered string, in runes
  2364. - pad: The string used for padding on both sides
  2365. - allocator: (default is context.allocator)
  2366. Returns:
  2367. A new string centered within a field of the specified length
  2368. */
  2369. centre_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  2370. n := rune_count(str)
  2371. if n >= length || pad == "" {
  2372. return clone(str, allocator)
  2373. }
  2374. remains := length-n
  2375. pad_len := rune_count(pad)
  2376. b: Builder
  2377. builder_init(&b, allocator)
  2378. builder_grow(&b, len(str) + (remains/pad_len + 1)*len(pad))
  2379. w := to_writer(&b)
  2380. write_pad_string(w, pad, pad_len, remains/2)
  2381. io.write_string(w, str)
  2382. write_pad_string(w, pad, pad_len, (remains+1)/2)
  2383. return to_string(b)
  2384. }
  2385. /*
  2386. Left-justifies the input string within a field of specified length by adding pad string on the right side, if its length is less than the target length.
  2387. *Allocates Using Provided Allocator*
  2388. Inputs:
  2389. - str: The input string
  2390. - length: The desired length of the left-justified string
  2391. - pad: The string used for padding on the right side
  2392. - allocator: (default is context.allocator)
  2393. Returns:
  2394. A new string left-justified within a field of the specified length
  2395. */
  2396. left_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  2397. n := rune_count(str)
  2398. if n >= length || pad == "" {
  2399. return clone(str, allocator)
  2400. }
  2401. remains := length-n
  2402. pad_len := rune_count(pad)
  2403. b: Builder
  2404. builder_init(&b, allocator)
  2405. builder_grow(&b, len(str) + (remains/pad_len + 1)*len(pad))
  2406. w := to_writer(&b)
  2407. io.write_string(w, str)
  2408. write_pad_string(w, pad, pad_len, remains)
  2409. return to_string(b)
  2410. }
  2411. /*
  2412. Right-justifies the input string within a field of specified length by adding pad string on the left side, if its length is less than the target length.
  2413. *Allocates Using Provided Allocator*
  2414. Inputs:
  2415. - str: The input string
  2416. - length: The desired length of the right-justified string
  2417. - pad: The string used for padding on the left side
  2418. - allocator: (default is context.allocator)
  2419. Returns:
  2420. A new string right-justified within a field of the specified length
  2421. */
  2422. right_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  2423. n := rune_count(str)
  2424. if n >= length || pad == "" {
  2425. return clone(str, allocator)
  2426. }
  2427. remains := length-n
  2428. pad_len := rune_count(pad)
  2429. b: Builder
  2430. builder_init(&b, allocator)
  2431. builder_grow(&b, len(str) + (remains/pad_len + 1)*len(pad))
  2432. w := to_writer(&b)
  2433. write_pad_string(w, pad, pad_len, remains)
  2434. io.write_string(w, str)
  2435. return to_string(b)
  2436. }
  2437. /*
  2438. Writes a given pad string a specified number of times to an `io.Writer`
  2439. Inputs:
  2440. - w: The io.Writer to write the pad string to
  2441. - pad: The pad string to be written
  2442. - pad_len: The length of the pad string, in runes
  2443. - remains: The number of times to write the pad string, in runes
  2444. */
  2445. @private
  2446. write_pad_string :: proc(w: io.Writer, pad: string, pad_len, remains: int) {
  2447. repeats := remains / pad_len
  2448. for i := 0; i < repeats; i += 1 {
  2449. io.write_string(w, pad)
  2450. }
  2451. n := remains % pad_len
  2452. p := pad
  2453. for i := 0; i < n; i += 1 {
  2454. r, width := utf8.decode_rune_in_string(p)
  2455. io.write_rune(w, r)
  2456. p = p[width:]
  2457. }
  2458. }
  2459. /*
  2460. Splits a string into a slice of substrings at each instance of one or more consecutive white space characters, as defined by `unicode.is_space`
  2461. *Allocates Using Provided Allocator*
  2462. Inputs:
  2463. - s: The input string
  2464. - allocator: (default is context.allocator)
  2465. Returns:
  2466. A slice of substrings of the input string, or an empty slice if the input string only contains white space
  2467. */
  2468. fields :: proc(s: string, allocator := context.allocator) -> []string #no_bounds_check {
  2469. n := 0
  2470. was_space := 1
  2471. set_bits := u8(0)
  2472. // check to see
  2473. for i in 0..<len(s) {
  2474. r := s[i]
  2475. set_bits |= r
  2476. is_space := int(_ascii_space[r])
  2477. n += was_space & ~is_space
  2478. was_space = is_space
  2479. }
  2480. if set_bits >= utf8.RUNE_SELF {
  2481. return fields_proc(s, unicode.is_space, allocator)
  2482. }
  2483. if n == 0 {
  2484. return nil
  2485. }
  2486. a := make([]string, n, allocator)
  2487. na := 0
  2488. field_start := 0
  2489. i := 0
  2490. for i < len(s) && _ascii_space[s[i]] {
  2491. i += 1
  2492. }
  2493. field_start = i
  2494. for i < len(s) {
  2495. if !_ascii_space[s[i]] {
  2496. i += 1
  2497. continue
  2498. }
  2499. a[na] = s[field_start : i]
  2500. na += 1
  2501. i += 1
  2502. for i < len(s) && _ascii_space[s[i]] {
  2503. i += 1
  2504. }
  2505. field_start = i
  2506. }
  2507. if field_start < len(s) {
  2508. a[na] = s[field_start:]
  2509. }
  2510. return a
  2511. }
  2512. /*
  2513. Splits a string into a slice of substrings at each run of unicode code points `r` satisfying the predicate `f(r)`
  2514. *Allocates Using Provided Allocator*
  2515. Inputs:
  2516. - s: The input string
  2517. - f: A predicate function to determine the split points
  2518. - allocator: (default is context.allocator)
  2519. NOTE: fields_proc makes no guarantee about the order in which it calls `f(r)`, it assumes that `f` always returns the same value for a given `r`
  2520. Returns:
  2521. A slice of substrings of the input string, or an empty slice if all code points in the input string satisfy the predicate or if the input string is empty
  2522. */
  2523. fields_proc :: proc(s: string, f: proc(rune) -> bool, allocator := context.allocator) -> []string #no_bounds_check {
  2524. substrings := make([dynamic]string, 0, 32, allocator)
  2525. start, end := -1, -1
  2526. for r, offset in s {
  2527. end = offset
  2528. if f(r) {
  2529. if start >= 0 {
  2530. append(&substrings, s[start : end])
  2531. // -1 could be used, but just speed it up through bitwise not
  2532. // gotta love 2's complement
  2533. start = ~start
  2534. }
  2535. } else {
  2536. if start < 0 {
  2537. start = end
  2538. }
  2539. }
  2540. }
  2541. if start >= 0 {
  2542. append(&substrings, s[start : len(s)])
  2543. }
  2544. return substrings[:]
  2545. }
  2546. /*
  2547. Retrieves the first non-space substring from a mutable string reference and advances the reference. `s` is advanced from any space after the substring, or be an empty string if the substring was the remaining characters
  2548. Inputs:
  2549. - s: A mutable string reference to be iterated
  2550. Returns:
  2551. - field: The first non-space substring found
  2552. - ok: A boolean indicating if a non-space substring was found
  2553. */
  2554. fields_iterator :: proc(s: ^string) -> (field: string, ok: bool) {
  2555. start, end := -1, -1
  2556. for r, offset in s {
  2557. end = offset
  2558. if unicode.is_space(r) {
  2559. if start >= 0 {
  2560. field = s[start : end]
  2561. ok = true
  2562. s^ = s[end:]
  2563. return
  2564. }
  2565. } else {
  2566. if start < 0 {
  2567. start = end
  2568. }
  2569. }
  2570. }
  2571. // if either of these are true, the string did not contain any characters
  2572. if end < 0 || start < 0 {
  2573. return "", false
  2574. }
  2575. field = s[start:]
  2576. ok = true
  2577. s^ = s[len(s):]
  2578. return
  2579. }
  2580. /*
  2581. Computes the Levenshtein edit distance between two strings
  2582. *Allocates Using Provided Allocator (deletion occurs internal to proc)*
  2583. NOTE: Does not perform internal allocation if length of string `b`, in runes, is smaller than 64
  2584. Inputs:
  2585. - a, b: The two strings to compare
  2586. - allocator: (default is context.allocator)
  2587. Returns:
  2588. The Levenshtein edit distance between the two strings
  2589. NOTE: This implementation is a single-row-version of the Wagner–Fischer algorithm, based on C code by Martin Ettl.
  2590. */
  2591. levenshtein_distance :: proc(a, b: string, allocator := context.allocator) -> int {
  2592. LEVENSHTEIN_DEFAULT_COSTS: []int : {
  2593. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  2594. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
  2595. 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  2596. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
  2597. 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
  2598. 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  2599. 60, 61, 62, 63,
  2600. }
  2601. m, n := utf8.rune_count_in_string(a), utf8.rune_count_in_string(b)
  2602. if m == 0 {
  2603. return n
  2604. }
  2605. if n == 0 {
  2606. return m
  2607. }
  2608. costs: []int
  2609. if n + 1 > len(LEVENSHTEIN_DEFAULT_COSTS) {
  2610. costs = make([]int, n + 1, allocator)
  2611. for k in 0..=n {
  2612. costs[k] = k
  2613. }
  2614. } else {
  2615. costs = LEVENSHTEIN_DEFAULT_COSTS
  2616. }
  2617. defer if n + 1 > len(LEVENSHTEIN_DEFAULT_COSTS) {
  2618. delete(costs, allocator)
  2619. }
  2620. i: int
  2621. for c1 in a {
  2622. costs[0] = i + 1
  2623. corner := i
  2624. j: int
  2625. for c2 in b {
  2626. upper := costs[j + 1]
  2627. if c1 == c2 {
  2628. costs[j + 1] = corner
  2629. } else {
  2630. t := upper if upper < corner else corner
  2631. costs[j + 1] = (costs[j] if costs[j] < t else t) + 1
  2632. }
  2633. corner = upper
  2634. j += 1
  2635. }
  2636. i += 1
  2637. }
  2638. return costs[n]
  2639. }