strings.odin 76 KB

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