strings.odin 74 KB

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