2
0

strings.odin 75 KB

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