strings.odin 74 KB

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