strings.odin 75 KB

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