strings.odin 74 KB

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