strings.odin 76 KB

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