strings.odin 74 KB

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