strings.odin 75 KB

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