strings.odin 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433
  1. // Procedures to manipulate UTF-8 encoded strings
  2. package strings
  3. import "base:intrinsics"
  4. import "core:bytes"
  5. import "core:io"
  6. import "core:mem"
  7. import "core:unicode"
  8. import "core:unicode/utf8"
  9. /*
  10. Clones a string
  11. *Allocates Using Provided Allocator*
  12. Inputs:
  13. - s: The string to be cloned
  14. - allocator: (default: context.allocator)
  15. - loc: The caller location for debugging purposes (default: #caller_location)
  16. Returns:
  17. - res: The cloned string
  18. - err: An optional allocator error if one occured, `nil` otherwise
  19. */
  20. clone :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  21. c := make([]byte, len(s), allocator, loc) or_return
  22. copy(c, s)
  23. return string(c[:len(s)]), nil
  24. }
  25. /*
  26. Clones a string safely (returns early with an allocation error on failure)
  27. *Allocates Using Provided Allocator*
  28. Inputs:
  29. - s: The string to be cloned
  30. - allocator: (default: context.allocator)
  31. - loc: The caller location for debugging purposes (default: #caller_location)
  32. Returns:
  33. - res: The cloned string
  34. - err: An allocator error if one occured, `nil` otherwise
  35. */
  36. @(deprecated="Prefer clone. It now returns an optional allocator error")
  37. clone_safe :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (res: string, err: mem.Allocator_Error) {
  38. return clone(s, allocator, loc)
  39. }
  40. /*
  41. Clones a string and appends a null-byte to make it a cstring
  42. *Allocates Using Provided Allocator*
  43. Inputs:
  44. - s: The string to be cloned
  45. - allocator: (default: context.allocator)
  46. - loc: The caller location for debugging purposes (default: #caller_location)
  47. Returns:
  48. - res: A cloned cstring with an appended null-byte
  49. - err: An optional allocator error if one occured, `nil` otherwise
  50. */
  51. clone_to_cstring :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (res: cstring, err: mem.Allocator_Error) #optional_allocator_error {
  52. c := make([]byte, len(s)+1, allocator, loc) or_return
  53. copy(c, s)
  54. c[len(s)] = 0
  55. return cstring(&c[0]), nil
  56. }
  57. /*
  58. Transmutes a raw pointer into a string. Non-allocating.
  59. Inputs:
  60. - ptr: A pointer to the start of the byte sequence
  61. - len: The length of the byte sequence
  62. NOTE: The created string is only valid as long as the pointer and length are valid.
  63. Returns:
  64. - res: A string created from the byte pointer and length
  65. */
  66. string_from_ptr :: proc(ptr: ^byte, len: int) -> (res: string) {
  67. return transmute(string)mem.Raw_String{ptr, len}
  68. }
  69. /*
  70. Transmutes a raw pointer (null-terminated) into a string. Non-allocating. Searches for a null-byte from `0..<len`, otherwise `len` will be the end size
  71. NOTE: The created string is only valid as long as the pointer and length are valid.
  72. The string is truncated at the first null-byte encountered.
  73. Inputs:
  74. - ptr: A pointer to the start of the null-terminated byte sequence
  75. - len: The length of the byte sequence
  76. Returns:
  77. - res: A string created from the null-terminated byte pointer and length
  78. */
  79. string_from_null_terminated_ptr :: proc "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. if sep == "" {
  813. res = s[:]
  814. ok = true
  815. s^ = s[len(s):]
  816. return
  817. }
  818. m := index(s^, sep)
  819. if m < 0 {
  820. // not found
  821. res = s[:]
  822. ok = res != ""
  823. s^ = s[len(s):]
  824. } else {
  825. res = s[:m+sep_save]
  826. ok = true
  827. s^ = s[m+len(sep):]
  828. }
  829. return
  830. }
  831. /*
  832. Splits the input string by the byte separator in an iterator fashion.
  833. Inputs:
  834. - s: Pointer to the input string, which is modified during the search.
  835. - sep: The byte separator to search for.
  836. Returns:
  837. - res: The resulting substring
  838. - ok: `true` if an iteration result was returned, `false` if the iterator has reached the end
  839. Example:
  840. import "core:fmt"
  841. import "core:strings"
  842. split_by_byte_iterator_example :: proc() {
  843. text := "a.b.c.d.e"
  844. for str in strings.split_by_byte_iterator(&text, '.') {
  845. fmt.println(str) // every loop -> a b c d e
  846. }
  847. }
  848. Output:
  849. a
  850. b
  851. c
  852. d
  853. e
  854. */
  855. split_by_byte_iterator :: proc(s: ^string, sep: u8) -> (res: string, ok: bool) {
  856. m := index_byte(s^, sep)
  857. if m < 0 {
  858. // not found
  859. res = s[:]
  860. ok = res != ""
  861. s^ = {}
  862. } else {
  863. res = s[:m]
  864. ok = true
  865. s^ = s[m+1:]
  866. }
  867. return
  868. }
  869. /*
  870. Splits the input string by the separator string in an iterator fashion.
  871. Inputs:
  872. - s: Pointer to the input string, which is modified during the search.
  873. - sep: The separator string to search for.
  874. Returns:
  875. - res: The resulting substring
  876. - ok: `true` if an iteration result was returned, `false` if the iterator has reached the end
  877. Example:
  878. import "core:fmt"
  879. import "core:strings"
  880. split_iterator_example :: proc() {
  881. text := "a.b.c.d.e"
  882. for str in strings.split_iterator(&text, ".") {
  883. fmt.println(str)
  884. }
  885. }
  886. Output:
  887. a
  888. b
  889. c
  890. d
  891. e
  892. */
  893. split_iterator :: proc(s: ^string, sep: string) -> (res: string, ok: bool) {
  894. return _split_iterator(s, sep, 0)
  895. }
  896. /*
  897. Splits the input string after every separator string in an iterator fashion.
  898. Inputs:
  899. - s: Pointer to the input string, which is modified during the search.
  900. - sep: The separator string to search for.
  901. Returns:
  902. - res: The resulting substring
  903. - ok: `true` if an iteration result was returned, `false` if the iterator has reached the end
  904. Example:
  905. import "core:fmt"
  906. import "core:strings"
  907. split_after_iterator_example :: proc() {
  908. text := "a.b.c.d.e"
  909. for str in strings.split_after_iterator(&text, ".") {
  910. fmt.println(str)
  911. }
  912. }
  913. Output:
  914. a.
  915. b.
  916. c.
  917. d.
  918. e
  919. */
  920. split_after_iterator :: proc(s: ^string, sep: string) -> (res: string, ok: bool) {
  921. return _split_iterator(s, sep, len(sep))
  922. }
  923. /*
  924. Trims the carriage return character from the end of the input string.
  925. *Used Internally - Private Function*
  926. Inputs:
  927. - s: The input string to trim.
  928. Returns:
  929. - res: The trimmed string as a slice of the original.
  930. */
  931. @(private)
  932. _trim_cr :: proc(s: string) -> (res: string) {
  933. n := len(s)
  934. if n > 0 {
  935. if s[n-1] == '\r' {
  936. return s[:n-1]
  937. }
  938. }
  939. return s
  940. }
  941. /*
  942. Splits the input string at every line break `\n`.
  943. *Allocates Using Provided Allocator*
  944. Inputs:
  945. - s: The input string to split.
  946. - allocator: (default is context.allocator)
  947. Returns:
  948. - res: The slice (allocated) of the split string (slices into original string)
  949. - err: An optional allocator error if one occured, `nil` otherwise
  950. Example:
  951. import "core:fmt"
  952. import "core:strings"
  953. split_lines_example :: proc() {
  954. a := "a\nb\nc\nd\ne"
  955. b := strings.split_lines(a)
  956. fmt.println(b)
  957. }
  958. Output:
  959. ["a", "b", "c", "d", "e"]
  960. */
  961. split_lines :: proc(s: string, allocator := context.allocator) -> (res: []string, err: mem.Allocator_Error) #optional_allocator_error {
  962. sep :: "\n"
  963. lines := _split(s, sep, 0, -1, allocator) or_return
  964. for &line in lines {
  965. line = _trim_cr(line)
  966. }
  967. return lines, nil
  968. }
  969. /*
  970. Splits the input string at every line break `\n` for `n` parts.
  971. *Allocates Using Provided Allocator*
  972. Inputs:
  973. - s: The input string to split.
  974. - n: The number of parts to split into.
  975. - allocator: (default is context.allocator)
  976. Returns:
  977. - res: The slice (allocated) of the split string (slices into original string)
  978. - err: An optional allocator error if one occured, `nil` otherwise
  979. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  980. Example:
  981. import "core:fmt"
  982. import "core:strings"
  983. split_lines_n_example :: proc() {
  984. a := "a\nb\nc\nd\ne"
  985. b := strings.split_lines_n(a, 3)
  986. fmt.println(b)
  987. }
  988. Output:
  989. ["a", "b", "c\nd\ne"]
  990. */
  991. split_lines_n :: proc(s: string, n: int, allocator := context.allocator) -> (res: []string, err: mem.Allocator_Error) #optional_allocator_error {
  992. sep :: "\n"
  993. lines := _split(s, sep, 0, n, allocator) or_return
  994. for &line in lines {
  995. line = _trim_cr(line)
  996. }
  997. return lines, nil
  998. }
  999. /*
  1000. Splits the input string at every line break `\n` leaving the `\n` in the resulting strings.
  1001. *Allocates Using Provided Allocator*
  1002. Inputs:
  1003. - s: The input string to split.
  1004. - allocator: (default is context.allocator)
  1005. Returns:
  1006. - res: The slice (allocated) of the split string (slices into original string), with `\n` included
  1007. - err: An optional allocator error if one occured, `nil` otherwise
  1008. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  1009. Example:
  1010. import "core:fmt"
  1011. import "core:strings"
  1012. split_lines_after_example :: proc() {
  1013. a := "a\nb\nc\nd\ne"
  1014. b := strings.split_lines_after(a)
  1015. fmt.println(b)
  1016. }
  1017. Output:
  1018. ["a\n", "b\n", "c\n", "d\n", "e"]
  1019. */
  1020. split_lines_after :: proc(s: string, allocator := context.allocator) -> (res: []string, err: mem.Allocator_Error) #optional_allocator_error {
  1021. sep :: "\n"
  1022. lines := _split(s, sep, len(sep), -1, allocator) or_return
  1023. for &line in lines {
  1024. line = _trim_cr(line)
  1025. }
  1026. return lines, nil
  1027. }
  1028. /*
  1029. Splits the input string at every line break `\n` leaving the `\n` in the resulting strings.
  1030. Only runs for n parts.
  1031. *Allocates Using Provided Allocator*
  1032. Inputs:
  1033. - s: The input string to split.
  1034. - n: The number of parts to split into.
  1035. - allocator: (default is context.allocator)
  1036. Returns:
  1037. - res: The slice (allocated) of the split string (slices into original string), with `\n` included
  1038. - err: An optional allocator error if one occured, `nil` otherwise
  1039. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  1040. Example:
  1041. import "core:fmt"
  1042. import "core:strings"
  1043. split_lines_after_n_example :: proc() {
  1044. a := "a\nb\nc\nd\ne"
  1045. b := strings.split_lines_after_n(a, 3)
  1046. fmt.println(b)
  1047. }
  1048. Output:
  1049. ["a\n", "b\n", "c\nd\ne"]
  1050. */
  1051. split_lines_after_n :: proc(s: string, n: int, allocator := context.allocator) -> (res: []string, err: mem.Allocator_Error) #optional_allocator_error {
  1052. sep :: "\n"
  1053. lines := _split(s, sep, len(sep), n, allocator) or_return
  1054. for &line in lines {
  1055. line = _trim_cr(line)
  1056. }
  1057. return lines, nil
  1058. }
  1059. /*
  1060. Splits the input string at every line break `\n`.
  1061. Returns the current split string every iteration until the string is consumed.
  1062. Inputs:
  1063. - s: Pointer to the input string, which is modified during the search.
  1064. Returns:
  1065. - line: The resulting substring
  1066. - ok: `true` if an iteration result was returned, `false` if the iterator has reached the end
  1067. Example:
  1068. import "core:fmt"
  1069. import "core:strings"
  1070. split_lines_iterator_example :: proc() {
  1071. text := "a\nb\nc\nd\ne"
  1072. for str in strings.split_lines_iterator(&text) {
  1073. fmt.print(str) // every loop -> a b c d e
  1074. }
  1075. fmt.print("\n")
  1076. }
  1077. Output:
  1078. abcde
  1079. */
  1080. split_lines_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  1081. sep :: "\n"
  1082. line = _split_iterator(s, sep, 0) or_return
  1083. return _trim_cr(line), true
  1084. }
  1085. /*
  1086. Splits the input string at every line break `\n`.
  1087. Returns the current split string with line breaks included every iteration until the string is consumed.
  1088. Inputs:
  1089. - s: Pointer to the input string, which is modified during the search.
  1090. Returns:
  1091. - line: The resulting substring with line breaks included
  1092. - ok: `true` if an iteration result was returned, `false` if the iterator has reached the end
  1093. Example:
  1094. import "core:fmt"
  1095. import "core:strings"
  1096. split_lines_after_iterator_example :: proc() {
  1097. text := "a\nb\nc\nd\ne\n"
  1098. for str in strings.split_lines_after_iterator(&text) {
  1099. fmt.print(str) // every loop -> a\n b\n c\n d\n e\n
  1100. }
  1101. }
  1102. Output:
  1103. a
  1104. b
  1105. c
  1106. d
  1107. e
  1108. */
  1109. split_lines_after_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  1110. sep :: "\n"
  1111. line = _split_iterator(s, sep, len(sep)) or_return
  1112. return _trim_cr(line), true
  1113. }
  1114. /*
  1115. Returns the byte offset of the first byte `c` in the string s it finds, -1 when not found.
  1116. NOTE: Can't find UTF-8 based runes.
  1117. Inputs:
  1118. - s: The input string to search in.
  1119. - c: The byte to search for.
  1120. Returns:
  1121. - res: The byte offset of the first occurrence of `c` in `s`, or -1 if not found.
  1122. Example:
  1123. import "core:fmt"
  1124. import "core:strings"
  1125. index_byte_example :: proc() {
  1126. fmt.println(strings.index_byte("test", 't'))
  1127. fmt.println(strings.index_byte("test", 'e'))
  1128. fmt.println(strings.index_byte("test", 'x'))
  1129. fmt.println(strings.index_byte("teäst", 'ä'))
  1130. }
  1131. Output:
  1132. 0
  1133. 1
  1134. -1
  1135. -1
  1136. */
  1137. index_byte :: proc "contextless" (s: string, c: byte) -> (res: int) {
  1138. return #force_inline bytes.index_byte(transmute([]u8)s, c)
  1139. }
  1140. /*
  1141. Returns the byte offset of the last byte `c` in the string `s`, -1 when not found.
  1142. Inputs:
  1143. - s: The input string to search in.
  1144. - c: The byte to search for.
  1145. Returns:
  1146. - res: The byte offset of the last occurrence of `c` in `s`, or -1 if not found.
  1147. NOTE: Can't find UTF-8 based runes.
  1148. Example:
  1149. import "core:fmt"
  1150. import "core:strings"
  1151. last_index_byte_example :: proc() {
  1152. fmt.println(strings.last_index_byte("test", 't'))
  1153. fmt.println(strings.last_index_byte("test", 'e'))
  1154. fmt.println(strings.last_index_byte("test", 'x'))
  1155. fmt.println(strings.last_index_byte("teäst", 'ä'))
  1156. }
  1157. Output:
  1158. 3
  1159. 1
  1160. -1
  1161. -1
  1162. */
  1163. last_index_byte :: proc "contextless" (s: string, c: byte) -> (res: int) {
  1164. return #force_inline bytes.last_index_byte(transmute([]u8)s, c)
  1165. }
  1166. /*
  1167. Returns the byte offset of the first rune `r` in the string `s` it finds, -1 when not found.
  1168. Invalid runes return -1
  1169. Inputs:
  1170. - s: The input string to search in.
  1171. - r: The rune to search for.
  1172. Returns:
  1173. - res: The byte offset of the first occurrence of `r` in `s`, or -1 if not found.
  1174. Example:
  1175. import "core:fmt"
  1176. import "core:strings"
  1177. index_rune_example :: proc() {
  1178. fmt.println(strings.index_rune("abcädef", 'x'))
  1179. fmt.println(strings.index_rune("abcädef", 'a'))
  1180. fmt.println(strings.index_rune("abcädef", 'b'))
  1181. fmt.println(strings.index_rune("abcädef", 'c'))
  1182. fmt.println(strings.index_rune("abcädef", 'ä'))
  1183. fmt.println(strings.index_rune("abcädef", 'd'))
  1184. fmt.println(strings.index_rune("abcädef", 'e'))
  1185. fmt.println(strings.index_rune("abcädef", 'f'))
  1186. }
  1187. Output:
  1188. -1
  1189. 0
  1190. 1
  1191. 2
  1192. 3
  1193. 5
  1194. 6
  1195. 7
  1196. */
  1197. index_rune :: proc(s: string, r: rune) -> (res: int) {
  1198. switch {
  1199. case u32(r) < utf8.RUNE_SELF:
  1200. return index_byte(s, byte(r))
  1201. case r == utf8.RUNE_ERROR:
  1202. for c, i in s {
  1203. if c == utf8.RUNE_ERROR {
  1204. return i
  1205. }
  1206. }
  1207. return -1
  1208. case !utf8.valid_rune(r):
  1209. return -1
  1210. }
  1211. b, w := utf8.encode_rune(r)
  1212. return index(s, string(b[:w]))
  1213. }
  1214. @private PRIME_RABIN_KARP :: 16777619
  1215. /*
  1216. Returns the byte offset of the string `substr` in the string `s`, -1 when not found.
  1217. Inputs:
  1218. - s: The input string to search in.
  1219. - substr: The substring to search for.
  1220. Returns:
  1221. - res: The byte offset of the first occurrence of `substr` in `s`, or -1 if not found.
  1222. Example:
  1223. import "core:fmt"
  1224. import "core:strings"
  1225. index_example :: proc() {
  1226. fmt.println(strings.index("test", "t"))
  1227. fmt.println(strings.index("test", "te"))
  1228. fmt.println(strings.index("test", "st"))
  1229. fmt.println(strings.index("test", "tt"))
  1230. }
  1231. Output:
  1232. 0
  1233. 0
  1234. 2
  1235. -1
  1236. */
  1237. index :: proc "contextless" (s, substr: string) -> (res: int) {
  1238. hash_str_rabin_karp :: proc "contextless" (s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  1239. for i := 0; i < len(s); i += 1 {
  1240. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  1241. }
  1242. sq := u32(PRIME_RABIN_KARP)
  1243. for i := len(s); i > 0; i >>= 1 {
  1244. if (i & 1) != 0 {
  1245. pow *= sq
  1246. }
  1247. sq *= sq
  1248. }
  1249. return
  1250. }
  1251. n := len(substr)
  1252. switch {
  1253. case n == 0:
  1254. return 0
  1255. case n == 1:
  1256. return index_byte(s, substr[0])
  1257. case n == len(s):
  1258. if s == substr {
  1259. return 0
  1260. }
  1261. return -1
  1262. case n > len(s):
  1263. return -1
  1264. }
  1265. hash, pow := hash_str_rabin_karp(substr)
  1266. h: u32
  1267. for i := 0; i < n; i += 1 {
  1268. h = h*PRIME_RABIN_KARP + u32(s[i])
  1269. }
  1270. if h == hash && s[:n] == substr {
  1271. return 0
  1272. }
  1273. for i := n; i < len(s); /**/ {
  1274. h *= PRIME_RABIN_KARP
  1275. h += u32(s[i])
  1276. h -= pow * u32(s[i-n])
  1277. i += 1
  1278. if h == hash && s[i-n:i] == substr {
  1279. return i - n
  1280. }
  1281. }
  1282. return -1
  1283. }
  1284. /*
  1285. Returns the last byte offset of the string `substr` in the string `s`, -1 when not found.
  1286. Inputs:
  1287. - s: The input string to search in.
  1288. - substr: The substring to search for.
  1289. Returns:
  1290. - res: The byte offset of the last occurrence of `substr` in `s`, or -1 if not found.
  1291. Example:
  1292. import "core:fmt"
  1293. import "core:strings"
  1294. last_index_example :: proc() {
  1295. fmt.println(strings.last_index("test", "t"))
  1296. fmt.println(strings.last_index("test", "te"))
  1297. fmt.println(strings.last_index("test", "st"))
  1298. fmt.println(strings.last_index("test", "tt"))
  1299. }
  1300. Output:
  1301. 3
  1302. 0
  1303. 2
  1304. -1
  1305. */
  1306. last_index :: proc(s, substr: string) -> (res: int) {
  1307. hash_str_rabin_karp_reverse :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  1308. for i := len(s) - 1; i >= 0; i -= 1 {
  1309. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  1310. }
  1311. sq := u32(PRIME_RABIN_KARP)
  1312. for i := len(s); i > 0; i >>= 1 {
  1313. if (i & 1) != 0 {
  1314. pow *= sq
  1315. }
  1316. sq *= sq
  1317. }
  1318. return
  1319. }
  1320. n := len(substr)
  1321. switch {
  1322. case n == 0:
  1323. return len(s)
  1324. case n == 1:
  1325. return last_index_byte(s, substr[0])
  1326. case n == len(s):
  1327. return 0 if substr == s else -1
  1328. case n > len(s):
  1329. return -1
  1330. }
  1331. hash, pow := hash_str_rabin_karp_reverse(substr)
  1332. last := len(s) - n
  1333. h: u32
  1334. for i := len(s)-1; i >= last; i -= 1 {
  1335. h = h*PRIME_RABIN_KARP + u32(s[i])
  1336. }
  1337. if h == hash && s[last:] == substr {
  1338. return last
  1339. }
  1340. for i := last-1; i >= 0; i -= 1 {
  1341. h *= PRIME_RABIN_KARP
  1342. h += u32(s[i])
  1343. h -= pow * u32(s[i+n])
  1344. if h == hash && s[i:i+n] == substr {
  1345. return i
  1346. }
  1347. }
  1348. return -1
  1349. }
  1350. /*
  1351. Returns the index of any first char of `chars` found in `s`, -1 if not found.
  1352. Inputs:
  1353. - s: The input string to search in.
  1354. - chars: The characters to look for
  1355. Returns:
  1356. - res: The index of the first character of `chars` found in `s`, or -1 if not found.
  1357. Example:
  1358. import "core:fmt"
  1359. import "core:strings"
  1360. index_any_example :: proc() {
  1361. fmt.println(strings.index_any("test", "s"))
  1362. fmt.println(strings.index_any("test", "se"))
  1363. fmt.println(strings.index_any("test", "et"))
  1364. fmt.println(strings.index_any("test", "set"))
  1365. fmt.println(strings.index_any("test", "x"))
  1366. }
  1367. Output:
  1368. 2
  1369. 1
  1370. 0
  1371. 0
  1372. -1
  1373. */
  1374. index_any :: proc(s, chars: string) -> (res: int) {
  1375. if chars == "" {
  1376. return -1
  1377. }
  1378. if len(chars) == 1 {
  1379. r := rune(chars[0])
  1380. if r >= utf8.RUNE_SELF {
  1381. r = utf8.RUNE_ERROR
  1382. }
  1383. return index_rune(s, r)
  1384. }
  1385. if len(s) > 8 {
  1386. if as, ok := ascii_set_make(chars); ok {
  1387. for i in 0..<len(s) {
  1388. if ascii_set_contains(as, s[i]) {
  1389. return i
  1390. }
  1391. }
  1392. return -1
  1393. }
  1394. }
  1395. for c, i in s {
  1396. if index_rune(chars, c) >= 0 {
  1397. return i
  1398. }
  1399. }
  1400. return -1
  1401. }
  1402. /*
  1403. Finds the last occurrence of any character in `chars` within `s`. Iterates in reverse.
  1404. Inputs:
  1405. - s: The string to search in
  1406. - chars: The characters to look for
  1407. Returns:
  1408. - res: The index of the last matching character, or -1 if not found
  1409. Example:
  1410. import "core:fmt"
  1411. import "core:strings"
  1412. last_index_any_example :: proc() {
  1413. fmt.println(strings.last_index_any("test", "s"))
  1414. fmt.println(strings.last_index_any("test", "se"))
  1415. fmt.println(strings.last_index_any("test", "et"))
  1416. fmt.println(strings.last_index_any("test", "set"))
  1417. fmt.println(strings.last_index_any("test", "x"))
  1418. }
  1419. Output:
  1420. 2
  1421. 2
  1422. 3
  1423. 3
  1424. -1
  1425. */
  1426. last_index_any :: proc(s, chars: string) -> (res: int) {
  1427. if chars == "" {
  1428. return -1
  1429. }
  1430. if len(s) == 1 {
  1431. r := rune(s[0])
  1432. if r >= utf8.RUNE_SELF {
  1433. r = utf8.RUNE_ERROR
  1434. }
  1435. i := index_rune(chars, r)
  1436. return i if i < 0 else 0
  1437. }
  1438. if len(s) > 8 {
  1439. if as, ok := ascii_set_make(chars); ok {
  1440. for i := len(s)-1; i >= 0; i -= 1 {
  1441. if ascii_set_contains(as, s[i]) {
  1442. return i
  1443. }
  1444. }
  1445. return -1
  1446. }
  1447. }
  1448. if len(chars) == 1 {
  1449. r := rune(chars[0])
  1450. if r >= utf8.RUNE_SELF {
  1451. r = utf8.RUNE_ERROR
  1452. }
  1453. for i := len(s); i > 0; /**/ {
  1454. c, w := utf8.decode_last_rune_in_string(s[:i])
  1455. i -= w
  1456. if c == r {
  1457. return i
  1458. }
  1459. }
  1460. return -1
  1461. }
  1462. for i := len(s); i > 0; /**/ {
  1463. r, w := utf8.decode_last_rune_in_string(s[:i])
  1464. i -= w
  1465. if index_rune(chars, r) >= 0 {
  1466. return i
  1467. }
  1468. }
  1469. return -1
  1470. }
  1471. /*
  1472. Finds the first occurrence of any substring in `substrs` within `s`
  1473. Inputs:
  1474. - s: The string to search in
  1475. - substrs: The substrings to look for
  1476. Returns:
  1477. - idx: the index of the first matching substring
  1478. - width: the length of the found substring
  1479. */
  1480. index_multi :: proc(s: string, substrs: []string) -> (idx: int, width: int) {
  1481. idx = -1
  1482. if s == "" || len(substrs) <= 0 {
  1483. return
  1484. }
  1485. // disallow "" substr
  1486. for substr in substrs {
  1487. if len(substr) == 0 {
  1488. return
  1489. }
  1490. }
  1491. lowest_index := len(s)
  1492. found := false
  1493. for substr in substrs {
  1494. haystack := s[:min(len(s), lowest_index + len(substr))]
  1495. if i := index(haystack, substr); i >= 0 {
  1496. if i < lowest_index {
  1497. lowest_index = i
  1498. width = len(substr)
  1499. found = true
  1500. }
  1501. }
  1502. }
  1503. if found {
  1504. idx = lowest_index
  1505. }
  1506. return
  1507. }
  1508. /*
  1509. Counts the number of non-overlapping occurrences of `substr` in `s`
  1510. Inputs:
  1511. - s: The string to search in
  1512. - substr: The substring to count
  1513. Returns:
  1514. - res: The number of occurrences of `substr` in `s`, returns the rune_count + 1 of the string `s` on empty `substr`
  1515. Example:
  1516. import "core:fmt"
  1517. import "core:strings"
  1518. count_example :: proc() {
  1519. fmt.println(strings.count("abbccc", "a"))
  1520. fmt.println(strings.count("abbccc", "b"))
  1521. fmt.println(strings.count("abbccc", "c"))
  1522. fmt.println(strings.count("abbccc", "ab"))
  1523. fmt.println(strings.count("abbccc", " "))
  1524. }
  1525. Output:
  1526. 1
  1527. 2
  1528. 3
  1529. 1
  1530. 0
  1531. */
  1532. count :: proc(s, substr: string) -> (res: int) {
  1533. if len(substr) == 0 { // special case
  1534. return rune_count(s) + 1
  1535. }
  1536. if len(substr) == 1 {
  1537. c := substr[0]
  1538. switch len(s) {
  1539. case 0:
  1540. return 0
  1541. case 1:
  1542. return int(s[0] == c)
  1543. }
  1544. n := 0
  1545. for i := 0; i < len(s); i += 1 {
  1546. if s[i] == c {
  1547. n += 1
  1548. }
  1549. }
  1550. return n
  1551. }
  1552. // TODO(bill): Use a non-brute for approach
  1553. n := 0
  1554. str := s
  1555. for {
  1556. i := index(str, substr)
  1557. if i == -1 {
  1558. return n
  1559. }
  1560. n += 1
  1561. str = str[i+len(substr):]
  1562. }
  1563. return n
  1564. }
  1565. /*
  1566. Repeats the string `s` `count` times, concatenating the result
  1567. *Allocates Using Provided Allocator*
  1568. Inputs:
  1569. - s: The string to repeat
  1570. - count: The number of times to repeat `s`
  1571. - allocator: (default is context.allocator)
  1572. Returns:
  1573. - res: The concatenated repeated string
  1574. - err: An optional allocator error if one occured, `nil` otherwise
  1575. WARNING: Panics if count < 0
  1576. Example:
  1577. import "core:fmt"
  1578. import "core:strings"
  1579. repeat_example :: proc() {
  1580. fmt.println(strings.repeat("abc", 2))
  1581. }
  1582. Output:
  1583. abcabc
  1584. */
  1585. repeat :: proc(s: string, count: int, allocator := context.allocator, loc := #caller_location) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  1586. if count < 0 {
  1587. panic("strings: negative repeat count")
  1588. } else if count > 0 && (len(s)*count)/count != len(s) {
  1589. panic("strings: repeat count will cause an overflow")
  1590. }
  1591. b := make([]byte, len(s)*count, allocator, loc) or_return
  1592. i := copy(b, s)
  1593. for i < len(b) { // 2^N trick to reduce the need to copy
  1594. copy(b[i:], b[:i])
  1595. i *= 2
  1596. }
  1597. return string(b), nil
  1598. }
  1599. /*
  1600. Replaces all occurrences of `old` in `s` with `new`
  1601. *Allocates Using Provided Allocator*
  1602. Inputs:
  1603. - s: The string to modify
  1604. - old: The substring to replace
  1605. - new: The substring to replace `old` with
  1606. - allocator: The allocator to use for the new string (default is context.allocator)
  1607. Returns:
  1608. - output: The modified string
  1609. - was_allocation: `true` if an allocation occurred during the replacement, `false` otherwise
  1610. Example:
  1611. import "core:fmt"
  1612. import "core:strings"
  1613. replace_all_example :: proc() {
  1614. fmt.println(strings.replace_all("xyzxyz", "xyz", "abc"))
  1615. fmt.println(strings.replace_all("xyzxyz", "abc", "xyz"))
  1616. fmt.println(strings.replace_all("xyzxyz", "xy", "z"))
  1617. }
  1618. Output:
  1619. abcabc true
  1620. xyzxyz false
  1621. zzzz true
  1622. */
  1623. replace_all :: proc(s, old, new: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1624. return replace(s, old, new, -1, allocator)
  1625. }
  1626. /*
  1627. Replaces n instances of old in the string s with the new string
  1628. *Allocates Using Provided Allocator*
  1629. Inputs:
  1630. - s: The input string
  1631. - old: The substring to be replaced
  1632. - new: The replacement string
  1633. - n: The number of instances to replace (if `n < 0`, no limit on the number of replacements)
  1634. - allocator: (default: context.allocator)
  1635. Returns:
  1636. - output: The modified string
  1637. - was_allocation: `true` if an allocation occurred during the replacement, `false` otherwise
  1638. Example:
  1639. import "core:fmt"
  1640. import "core:strings"
  1641. replace_example :: proc() {
  1642. fmt.println(strings.replace("xyzxyz", "xyz", "abc", 2))
  1643. fmt.println(strings.replace("xyzxyz", "xyz", "abc", 1))
  1644. fmt.println(strings.replace("xyzxyz", "abc", "xyz", -1))
  1645. fmt.println(strings.replace("xyzxyz", "xy", "z", -1))
  1646. }
  1647. Output:
  1648. abcabc true
  1649. abcxyz true
  1650. xyzxyz false
  1651. zzzz true
  1652. */
  1653. replace :: proc(s, old, new: string, n: int, allocator := context.allocator, loc := #caller_location) -> (output: string, was_allocation: bool) {
  1654. if old == new || n == 0 {
  1655. was_allocation = false
  1656. output = s
  1657. return
  1658. }
  1659. byte_count := n
  1660. if m := count(s, old); m == 0 {
  1661. was_allocation = false
  1662. output = s
  1663. return
  1664. } else if n < 0 || m < n {
  1665. byte_count = m
  1666. }
  1667. t, err := make([]byte, len(s) + byte_count*(len(new) - len(old)), allocator, loc)
  1668. if err != nil {
  1669. return
  1670. }
  1671. was_allocation = true
  1672. w := 0
  1673. start := 0
  1674. for i := 0; i < byte_count; i += 1 {
  1675. j := start
  1676. if len(old) == 0 {
  1677. if i > 0 {
  1678. _, width := utf8.decode_rune_in_string(s[start:])
  1679. j += width
  1680. }
  1681. } else {
  1682. j += index(s[start:], old)
  1683. }
  1684. w += copy(t[w:], s[start:j])
  1685. w += copy(t[w:], new)
  1686. start = j + len(old)
  1687. }
  1688. w += copy(t[w:], s[start:])
  1689. output = string(t[0:w])
  1690. return
  1691. }
  1692. /*
  1693. Removes the key string `n` times from the `s` string
  1694. *Allocates Using Provided Allocator*
  1695. Inputs:
  1696. - s: The input string
  1697. - key: The substring to be removed
  1698. - n: The number of instances to remove (if `n < 0`, no limit on the number of removes)
  1699. - allocator: (default: context.allocator)
  1700. Returns:
  1701. - output: The modified string
  1702. - was_allocation: `true` if an allocation occurred during the replacement, `false` otherwise
  1703. Example:
  1704. import "core:fmt"
  1705. import "core:strings"
  1706. remove_example :: proc() {
  1707. fmt.println(strings.remove("abcabc", "abc", 1))
  1708. fmt.println(strings.remove("abcabc", "abc", -1))
  1709. fmt.println(strings.remove("abcabc", "a", -1))
  1710. fmt.println(strings.remove("abcabc", "x", -1))
  1711. }
  1712. Output:
  1713. abc true
  1714. true
  1715. bcbc true
  1716. abcabc false
  1717. */
  1718. remove :: proc(s, key: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1719. return replace(s, key, "", n, allocator)
  1720. }
  1721. /*
  1722. Removes all the `key` string instances from the `s` string
  1723. *Allocates Using Provided Allocator*
  1724. Inputs:
  1725. - s: The input string
  1726. - key: The substring to be removed
  1727. - allocator: (default: context.allocator)
  1728. Returns:
  1729. - output: The modified string
  1730. - was_allocation: `true` if an allocation occurred during the replacement, `false` otherwise
  1731. Example:
  1732. import "core:fmt"
  1733. import "core:strings"
  1734. remove_all_example :: proc() {
  1735. fmt.println(strings.remove_all("abcabc", "abc"))
  1736. fmt.println(strings.remove_all("abcabc", "a"))
  1737. fmt.println(strings.remove_all("abcabc", "x"))
  1738. }
  1739. Output:
  1740. true
  1741. bcbc true
  1742. abcabc false
  1743. */
  1744. remove_all :: proc(s, key: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  1745. return remove(s, key, -1, allocator)
  1746. }
  1747. // Returns true if is an ASCII space character ('\t', '\n', '\v', '\f', '\r', ' ')
  1748. @(private) _ascii_space := [256]bool{'\t' = true, '\n' = true, '\v' = true, '\f' = true, '\r' = true, ' ' = true}
  1749. /*
  1750. Returns true when the `r` rune is an ASCII whitespace character.
  1751. Inputs:
  1752. - r: the rune to test
  1753. Returns:
  1754. -res: `true` if `r` is a whitespace character, `false` if otherwise
  1755. */
  1756. is_ascii_space :: proc(r: rune) -> (res: bool) {
  1757. if r < utf8.RUNE_SELF {
  1758. return _ascii_space[u8(r)]
  1759. }
  1760. return false
  1761. }
  1762. /*
  1763. Returns true when the `r` rune is an ASCII or UTF-8 whitespace character.
  1764. Inputs:
  1765. - r: the rune to test
  1766. Returns:
  1767. -res: `true` if `r` is a whitespace character, `false` if otherwise
  1768. */
  1769. is_space :: proc(r: rune) -> (res: bool) {
  1770. if r < 0x2000 {
  1771. switch r {
  1772. case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xa0, 0x1680:
  1773. return true
  1774. }
  1775. } else {
  1776. if r <= 0x200a {
  1777. return true
  1778. }
  1779. switch r {
  1780. case 0x2028, 0x2029, 0x202f, 0x205f, 0x3000:
  1781. return true
  1782. }
  1783. }
  1784. return false
  1785. }
  1786. /*
  1787. Returns true when the `r` rune is `0x0`
  1788. Inputs:
  1789. - r: the rune to test
  1790. Returns:
  1791. -res: `true` if `r` is `0x0`, `false` if otherwise
  1792. */
  1793. is_null :: proc(r: rune) -> (res: bool) {
  1794. return r == 0x0000
  1795. }
  1796. /*
  1797. 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.
  1798. Inputs:
  1799. - s: The input string
  1800. - p: A procedure that takes a rune and returns a boolean
  1801. - truth: The boolean value to be matched (default: `true`)
  1802. Returns:
  1803. - res: The index of the first matching rune, or -1 if no match was found
  1804. Example:
  1805. import "core:fmt"
  1806. import "core:strings"
  1807. index_proc_example :: proc() {
  1808. call :: proc(r: rune) -> bool {
  1809. return r == 'a'
  1810. }
  1811. fmt.println(strings.index_proc("abcabc", call))
  1812. fmt.println(strings.index_proc("cbacba", call))
  1813. fmt.println(strings.index_proc("cbacba", call, false))
  1814. fmt.println(strings.index_proc("abcabc", call, false))
  1815. fmt.println(strings.index_proc("xyz", call))
  1816. }
  1817. Output:
  1818. 0
  1819. 2
  1820. 0
  1821. 1
  1822. -1
  1823. */
  1824. index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> (res: int) {
  1825. for r, i in s {
  1826. if p(r) == truth {
  1827. return i
  1828. }
  1829. }
  1830. return -1
  1831. }
  1832. // Same as `index_proc`, but the procedure p takes a raw pointer for state
  1833. index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> (res: int) {
  1834. for r, i in s {
  1835. if p(state, r) == truth {
  1836. return i
  1837. }
  1838. }
  1839. return -1
  1840. }
  1841. // Finds the index of the *last* rune in the string s for which the procedure p returns the same value as truth
  1842. last_index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> (res: int) {
  1843. // TODO(bill): Probably use Rabin-Karp Search
  1844. for i := len(s); i > 0; {
  1845. r, size := utf8.decode_last_rune_in_string(s[:i])
  1846. i -= size
  1847. if p(r) == truth {
  1848. return i
  1849. }
  1850. }
  1851. return -1
  1852. }
  1853. // Same as `index_proc_with_state`, runs through the string in reverse
  1854. last_index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> (res: int) {
  1855. // TODO(bill): Probably use Rabin-Karp Search
  1856. for i := len(s); i > 0; {
  1857. r, size := utf8.decode_last_rune_in_string(s[:i])
  1858. i -= size
  1859. if p(state, r) == truth {
  1860. return i
  1861. }
  1862. }
  1863. return -1
  1864. }
  1865. /*
  1866. Trims the input string `s` from the left until the procedure `p` returns false
  1867. Inputs:
  1868. - s: The input string
  1869. - p: A procedure that takes a rune and returns a boolean
  1870. Returns:
  1871. - res: The trimmed string as a slice of the original
  1872. Example:
  1873. import "core:fmt"
  1874. import "core:strings"
  1875. trim_left_proc_example :: proc() {
  1876. find :: proc(r: rune) -> bool {
  1877. return r == 'x'
  1878. }
  1879. fmt.println(strings.trim_left_proc("xxxxxxtesting", find))
  1880. }
  1881. Output:
  1882. testing
  1883. */
  1884. trim_left_proc :: proc(s: string, p: proc(rune) -> bool) -> (res: string) {
  1885. i := index_proc(s, p, false)
  1886. if i == -1 {
  1887. return ""
  1888. }
  1889. return s[i:]
  1890. }
  1891. /*
  1892. Trims the input string `s` from the left until the procedure `p` with state returns false
  1893. Inputs:
  1894. - s: The input string
  1895. - p: A procedure that takes a raw pointer and a rune and returns a boolean
  1896. - state: The raw pointer to be passed to the procedure `p`
  1897. Returns:
  1898. - res: The trimmed string as a slice of the original
  1899. */
  1900. trim_left_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> (res: string) {
  1901. i := index_proc_with_state(s, p, state, false)
  1902. if i == -1 {
  1903. return ""
  1904. }
  1905. return s[i:]
  1906. }
  1907. /*
  1908. Trims the input string `s` from the right until the procedure `p` returns `false`
  1909. Inputs:
  1910. - s: The input string
  1911. - p: A procedure that takes a rune and returns a boolean
  1912. Returns:
  1913. - res: The trimmed string as a slice of the original
  1914. Example:
  1915. import "core:fmt"
  1916. import "core:strings"
  1917. trim_right_proc_example :: proc() {
  1918. find :: proc(r: rune) -> bool {
  1919. return r != 't'
  1920. }
  1921. fmt.println(strings.trim_right_proc("testing", find))
  1922. }
  1923. Output:
  1924. test
  1925. */
  1926. trim_right_proc :: proc(s: string, p: proc(rune) -> bool) -> (res: string) {
  1927. i := last_index_proc(s, p, false)
  1928. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  1929. _, w := utf8.decode_rune_in_string(s[i:])
  1930. i += w
  1931. } else {
  1932. i += 1
  1933. }
  1934. return s[0:i]
  1935. }
  1936. /*
  1937. Trims the input string `s` from the right until the procedure `p` with state returns `false`
  1938. Inputs:
  1939. - s: The input string
  1940. - p: A procedure that takes a raw pointer and a rune and returns a boolean
  1941. - state: The raw pointer to be passed to the procedure `p`
  1942. Returns:
  1943. - res: The trimmed string as a slice of the original, empty when no match
  1944. */
  1945. trim_right_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> (res: string) {
  1946. i := last_index_proc_with_state(s, p, state, false)
  1947. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  1948. _, w := utf8.decode_rune_in_string(s[i:])
  1949. i += w
  1950. } else {
  1951. i += 1
  1952. }
  1953. return s[0:i]
  1954. }
  1955. // Procedure for `trim_*_proc` variants, which has a string rawptr cast + rune comparison
  1956. is_in_cutset :: proc(state: rawptr, r: rune) -> (res: bool) {
  1957. cutset := (^string)(state)^
  1958. for c in cutset {
  1959. if r == c {
  1960. return true
  1961. }
  1962. }
  1963. return false
  1964. }
  1965. /*
  1966. Trims the cutset string from the `s` string
  1967. Inputs:
  1968. - s: The input string
  1969. - cutset: The set of characters to be trimmed from the left of the input string
  1970. Returns:
  1971. - res: The trimmed string as a slice of the original
  1972. */
  1973. trim_left :: proc(s: string, cutset: string) -> (res: string) {
  1974. if s == "" || cutset == "" {
  1975. return s
  1976. }
  1977. state := cutset
  1978. return trim_left_proc_with_state(s, is_in_cutset, &state)
  1979. }
  1980. /*
  1981. Trims the cutset string from the `s` string from the right
  1982. Inputs:
  1983. - s: The input string
  1984. - cutset: The set of characters to be trimmed from the right of the input string
  1985. Returns:
  1986. - res: The trimmed string as a slice of the original
  1987. */
  1988. trim_right :: proc(s: string, cutset: string) -> (res: string) {
  1989. if s == "" || cutset == "" {
  1990. return s
  1991. }
  1992. state := cutset
  1993. return trim_right_proc_with_state(s, is_in_cutset, &state)
  1994. }
  1995. /*
  1996. Trims the cutset string from the `s` string, both from left and right
  1997. Inputs:
  1998. - s: The input string
  1999. - cutset: The set of characters to be trimmed from both sides of the input string
  2000. Returns:
  2001. - res: The trimmed string as a slice of the original
  2002. */
  2003. trim :: proc(s: string, cutset: string) -> (res: string) {
  2004. return trim_right(trim_left(s, cutset), cutset)
  2005. }
  2006. /*
  2007. Trims until a valid non-space rune from the left, "\t\txyz\t\t" -> "xyz\t\t"
  2008. Inputs:
  2009. - s: The input string
  2010. Returns:
  2011. - res: The trimmed string as a slice of the original
  2012. */
  2013. trim_left_space :: proc(s: string) -> (res: string) {
  2014. return trim_left_proc(s, is_space)
  2015. }
  2016. /*
  2017. Trims from the right until a valid non-space rune, "\t\txyz\t\t" -> "\t\txyz"
  2018. Inputs:
  2019. - s: The input string
  2020. Returns:
  2021. - res: The trimmed string as a slice of the original
  2022. */
  2023. trim_right_space :: proc(s: string) -> (res: string) {
  2024. return trim_right_proc(s, is_space)
  2025. }
  2026. /*
  2027. Trims from both sides until a valid non-space rune, "\t\txyz\t\t" -> "xyz"
  2028. Inputs:
  2029. - s: The input string
  2030. Returns:
  2031. - res: The trimmed string as a slice of the original
  2032. */
  2033. trim_space :: proc(s: string) -> (res: string) {
  2034. return trim_right_space(trim_left_space(s))
  2035. }
  2036. /*
  2037. Trims null runes from the left, "\x00\x00testing\x00\x00" -> "testing\x00\x00"
  2038. Inputs:
  2039. - s: The input string
  2040. Returns:
  2041. - res: The trimmed string as a slice of the original
  2042. */
  2043. trim_left_null :: proc(s: string) -> (res: string) {
  2044. return trim_left_proc(s, is_null)
  2045. }
  2046. /*
  2047. Trims null runes from the right, "\x00\x00testing\x00\x00" -> "\x00\x00testing"
  2048. Inputs:
  2049. - s: The input string
  2050. Returns:
  2051. - res: The trimmed string as a slice of the original
  2052. */
  2053. trim_right_null :: proc(s: string) -> (res: string) {
  2054. return trim_right_proc(s, is_null)
  2055. }
  2056. /*
  2057. Trims null runes from both sides, "\x00\x00testing\x00\x00" -> "testing"
  2058. Inputs:
  2059. - s: The input string
  2060. Returns:
  2061. - res: The trimmed string as a slice of the original
  2062. */
  2063. trim_null :: proc(s: string) -> (res: string) {
  2064. return trim_right_null(trim_left_null(s))
  2065. }
  2066. /*
  2067. Trims a `prefix` string from the start of the `s` string and returns the trimmed string
  2068. Inputs:
  2069. - s: The input string
  2070. - prefix: The prefix string to be removed
  2071. Returns:
  2072. - res: The trimmed string as a slice of original, or the input string if no prefix was found
  2073. Example:
  2074. import "core:fmt"
  2075. import "core:strings"
  2076. trim_prefix_example :: proc() {
  2077. fmt.println(strings.trim_prefix("testing", "test"))
  2078. fmt.println(strings.trim_prefix("testing", "abc"))
  2079. }
  2080. Output:
  2081. ing
  2082. testing
  2083. */
  2084. trim_prefix :: proc(s, prefix: string) -> (res: string) {
  2085. if has_prefix(s, prefix) {
  2086. return s[len(prefix):]
  2087. }
  2088. return s
  2089. }
  2090. /*
  2091. Trims a `suffix` string from the end of the `s` string and returns the trimmed string
  2092. Inputs:
  2093. - s: The input string
  2094. - suffix: The suffix string to be removed
  2095. Returns:
  2096. - res: The trimmed string as a slice of original, or the input string if no suffix was found
  2097. Example:
  2098. import "core:fmt"
  2099. import "core:strings"
  2100. trim_suffix_example :: proc() {
  2101. fmt.println(strings.trim_suffix("todo.txt", ".txt"))
  2102. fmt.println(strings.trim_suffix("todo.doc", ".txt"))
  2103. }
  2104. Output:
  2105. todo
  2106. todo.doc
  2107. */
  2108. trim_suffix :: proc(s, suffix: string) -> (res: string) {
  2109. if has_suffix(s, suffix) {
  2110. return s[:len(s)-len(suffix)]
  2111. }
  2112. return s
  2113. }
  2114. /*
  2115. Splits the input string `s` by all possible `substrs` and returns an allocated array of strings
  2116. *Allocates Using Provided Allocator*
  2117. Inputs:
  2118. - s: The input string
  2119. - substrs: An array of substrings used for splitting
  2120. - allocator: (default is context.allocator)
  2121. Returns:
  2122. - res: An array of strings, or nil on empty substring or no matches
  2123. - err: An optional allocator error if one occured, `nil` otherwise
  2124. NOTE: Allocation occurs for the array, the splits are all views of the original string.
  2125. Example:
  2126. import "core:fmt"
  2127. import "core:strings"
  2128. split_multi_example :: proc() {
  2129. splits := [?]string { "---", "~~~", ".", "_", "," }
  2130. res := strings.split_multi("testing,this.out_nice---done~~~last", splits[:])
  2131. fmt.println(res) // -> [testing, this, out, nice, done, last]
  2132. }
  2133. Output:
  2134. ["testing", "this", "out", "nice", "done", "last"]
  2135. */
  2136. 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 {
  2137. if s == "" || len(substrs) <= 0 {
  2138. return nil, nil
  2139. }
  2140. // disallow "" substr
  2141. for substr in substrs {
  2142. if len(substr) == 0 {
  2143. return nil, nil
  2144. }
  2145. }
  2146. // calculate the needed len of `results`
  2147. n := 1
  2148. for it := s; len(it) > 0; {
  2149. i, w := index_multi(it, substrs)
  2150. if i < 0 {
  2151. break
  2152. }
  2153. n += 1
  2154. it = it[i+w:]
  2155. }
  2156. results := make([dynamic]string, 0, n, allocator, loc) or_return
  2157. {
  2158. it := s
  2159. for len(it) > 0 {
  2160. i, w := index_multi(it, substrs)
  2161. if i < 0 {
  2162. break
  2163. }
  2164. part := it[:i]
  2165. append(&results, part)
  2166. it = it[i+w:]
  2167. }
  2168. append(&results, it)
  2169. }
  2170. assert(len(results) == n)
  2171. return results[:], nil
  2172. }
  2173. /*
  2174. Splits the input string `s` by all possible `substrs` in an iterator fashion. The full string is returned if no match.
  2175. Inputs:
  2176. - it: A pointer to the input string
  2177. - substrs: An array of substrings used for splitting
  2178. Returns:
  2179. - res: The split string
  2180. - ok: `true` if an iteration result was returned, `false` if the iterator has reached the end
  2181. Example:
  2182. import "core:fmt"
  2183. import "core:strings"
  2184. split_multi_iterate_example :: proc() {
  2185. it := "testing,this.out_nice---done~~~last"
  2186. splits := [?]string { "---", "~~~", ".", "_", "," }
  2187. for str in strings.split_multi_iterate(&it, splits[:]) {
  2188. fmt.println(str)
  2189. }
  2190. }
  2191. Output:
  2192. testing
  2193. this
  2194. out
  2195. nice
  2196. done
  2197. last
  2198. */
  2199. split_multi_iterate :: proc(it: ^string, substrs: []string) -> (res: string, ok: bool) #no_bounds_check {
  2200. if len(it) == 0 || len(substrs) <= 0 {
  2201. return
  2202. }
  2203. // disallow "" substr
  2204. for substr in substrs {
  2205. if len(substr) == 0 {
  2206. return
  2207. }
  2208. }
  2209. // calculate the needed len of `results`
  2210. i, w := index_multi(it^, substrs)
  2211. if i >= 0 {
  2212. res = it[:i]
  2213. it^ = it[i+w:]
  2214. } else {
  2215. // last value
  2216. res = it^
  2217. it^ = it[len(it):]
  2218. }
  2219. ok = true
  2220. return
  2221. }
  2222. /*
  2223. Replaces invalid UTF-8 characters in the input string with a specified replacement string. Adjacent invalid bytes are only replaced once.
  2224. *Allocates Using Provided Allocator*
  2225. Inputs:
  2226. - s: The input string
  2227. - replacement: The string used to replace invalid UTF-8 characters
  2228. - allocator: (default is context.allocator)
  2229. Returns:
  2230. - res: A new string with invalid UTF-8 characters replaced
  2231. - err: An optional allocator error if one occured, `nil` otherwise
  2232. Example:
  2233. import "core:fmt"
  2234. import "core:strings"
  2235. scrub_example :: proc() {
  2236. text := "Hello\xC0\x80World"
  2237. fmt.println(strings.scrub(text, "?")) // -> "Hello?World"
  2238. }
  2239. Output:
  2240. Hello?
  2241. */
  2242. scrub :: proc(s: string, replacement: string, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  2243. str := s
  2244. b: Builder
  2245. builder_init(&b, 0, len(s), allocator) or_return
  2246. has_error := false
  2247. cursor := 0
  2248. origin := str
  2249. for len(str) > 0 {
  2250. r, w := utf8.decode_rune_in_string(str)
  2251. if r == utf8.RUNE_ERROR {
  2252. if !has_error {
  2253. has_error = true
  2254. write_string(&b, origin[:cursor])
  2255. }
  2256. } else if has_error {
  2257. has_error = false
  2258. write_string(&b, replacement)
  2259. origin = origin[cursor:]
  2260. cursor = 0
  2261. }
  2262. cursor += w
  2263. str = str[w:]
  2264. }
  2265. return to_string(b), nil
  2266. }
  2267. /*
  2268. Reverses the input string `s`
  2269. *Allocates Using Provided Allocator*
  2270. Inputs:
  2271. - s: The input string
  2272. - allocator: (default is context.allocator)
  2273. Returns:
  2274. - res: A reversed version of the input string
  2275. - err: An optional allocator error if one occured, `nil` otherwise
  2276. Example:
  2277. import "core:fmt"
  2278. import "core:strings"
  2279. reverse_example :: proc() {
  2280. a := "abcxyz"
  2281. b := strings.reverse(a)
  2282. fmt.println(a, b)
  2283. }
  2284. Output:
  2285. abcxyz zyxcba
  2286. */
  2287. reverse :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  2288. str := s
  2289. n := len(str)
  2290. buf := make([]byte, n, allocator, loc) or_return
  2291. i := n
  2292. for len(str) > 0 {
  2293. _, w := utf8.decode_rune_in_string(str)
  2294. i -= w
  2295. copy(buf[i:], str[:w])
  2296. str = str[w:]
  2297. }
  2298. return string(buf), nil
  2299. }
  2300. /*
  2301. Expands the input string by replacing tab characters with spaces to align to a specified tab size
  2302. *Allocates Using Provided Allocator*
  2303. Inputs:
  2304. - s: The input string
  2305. - tab_size: The number of spaces to use for each tab character
  2306. - allocator: (default is context.allocator)
  2307. Returns:
  2308. - res: A new string with tab characters expanded to the specified tab size
  2309. - err: An optional allocator error if one occured, `nil` otherwise
  2310. WARNING: Panics if tab_size <= 0
  2311. Example:
  2312. import "core:fmt"
  2313. import "core:strings"
  2314. expand_tabs_example :: proc() {
  2315. text := "abc1\tabc2\tabc3"
  2316. fmt.println(strings.expand_tabs(text, 4))
  2317. }
  2318. Output:
  2319. abc1 abc2 abc3
  2320. */
  2321. expand_tabs :: proc(s: string, tab_size: int, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  2322. if tab_size <= 0 {
  2323. panic("tab size must be positive")
  2324. }
  2325. if s == "" {
  2326. return "", nil
  2327. }
  2328. b: Builder
  2329. builder_init(&b, allocator) or_return
  2330. writer := to_writer(&b)
  2331. str := s
  2332. column: int
  2333. for len(str) > 0 {
  2334. r, w := utf8.decode_rune_in_string(str)
  2335. if r == '\t' {
  2336. expand := tab_size - column%tab_size
  2337. for i := 0; i < expand; i += 1 {
  2338. io.write_byte(writer, ' ')
  2339. }
  2340. column += expand
  2341. } else {
  2342. if r == '\n' {
  2343. column = 0
  2344. } else {
  2345. column += w
  2346. }
  2347. io.write_rune(writer, r)
  2348. }
  2349. str = str[w:]
  2350. }
  2351. return to_string(b), nil
  2352. }
  2353. /*
  2354. Splits the input string `str` by the separator `sep` string and returns 3 parts. The values are slices of the original string.
  2355. Inputs:
  2356. - str: The input string
  2357. - sep: The separator string
  2358. Returns:
  2359. - head: the string before the split
  2360. - match: the seperator string
  2361. - tail: the string after the split
  2362. Example:
  2363. import "core:fmt"
  2364. import "core:strings"
  2365. partition_example :: proc() {
  2366. text := "testing this out"
  2367. head, match, tail := strings.partition(text, " this ") // -> head: "testing", match: " this ", tail: "out"
  2368. fmt.println(head, match, tail)
  2369. head, match, tail = strings.partition(text, "hi") // -> head: "testing t", match: "hi", tail: "s out"
  2370. fmt.println(head, match, tail)
  2371. head, match, tail = strings.partition(text, "xyz") // -> head: "testing this out", match: "", tail: ""
  2372. fmt.println(head)
  2373. fmt.println(match == "")
  2374. fmt.println(tail == "")
  2375. }
  2376. Output:
  2377. testing this out
  2378. testing t hi s out
  2379. testing this out
  2380. true
  2381. true
  2382. */
  2383. partition :: proc(str, sep: string) -> (head, match, tail: string) {
  2384. i := index(str, sep)
  2385. if i == -1 {
  2386. head = str
  2387. return
  2388. }
  2389. head = str[:i]
  2390. match = str[i:i+len(sep)]
  2391. tail = str[i+len(sep):]
  2392. return
  2393. }
  2394. // Alias for centre_justify
  2395. center_justify :: centre_justify // NOTE(bill): Because Americans exist
  2396. /*
  2397. 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.
  2398. *Allocates Using Provided Allocator*
  2399. Inputs:
  2400. - str: The input string
  2401. - length: The desired length of the centered string, in runes
  2402. - pad: The string used for padding on both sides
  2403. - allocator: (default is context.allocator)
  2404. Returns:
  2405. - res: A new string centered within a field of the specified length
  2406. - err: An optional allocator error if one occured, `nil` otherwise
  2407. */
  2408. centre_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  2409. n := rune_count(str)
  2410. if n >= length || pad == "" {
  2411. return clone(str, allocator)
  2412. }
  2413. remains := length-n
  2414. pad_len := rune_count(pad)
  2415. b: Builder
  2416. builder_init(&b, 0, len(str) + (remains/pad_len + 1)*len(pad), allocator) or_return
  2417. w := to_writer(&b)
  2418. write_pad_string(w, pad, pad_len, remains/2)
  2419. io.write_string(w, str)
  2420. write_pad_string(w, pad, pad_len, (remains+1)/2)
  2421. return to_string(b), nil
  2422. }
  2423. /*
  2424. 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.
  2425. *Allocates Using Provided Allocator*
  2426. Inputs:
  2427. - str: The input string
  2428. - length: The desired length of the left-justified string
  2429. - pad: The string used for padding on the right side
  2430. - allocator: (default is context.allocator)
  2431. Returns:
  2432. - res: A new string left-justified within a field of the specified length
  2433. - err: An optional allocator error if one occured, `nil` otherwise
  2434. */
  2435. left_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  2436. n := rune_count(str)
  2437. if n >= length || pad == "" {
  2438. return clone(str, allocator)
  2439. }
  2440. remains := length-n
  2441. pad_len := rune_count(pad)
  2442. b: Builder
  2443. builder_init(&b, allocator)
  2444. builder_init(&b, 0, len(str) + (remains/pad_len + 1)*len(pad), allocator) or_return
  2445. w := to_writer(&b)
  2446. io.write_string(w, str)
  2447. write_pad_string(w, pad, pad_len, remains)
  2448. return to_string(b), nil
  2449. }
  2450. /*
  2451. 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.
  2452. *Allocates Using Provided Allocator*
  2453. Inputs:
  2454. - str: The input string
  2455. - length: The desired length of the right-justified string
  2456. - pad: The string used for padding on the left side
  2457. - allocator: (default is context.allocator)
  2458. Returns:
  2459. - res: A new string right-justified within a field of the specified length
  2460. - err: An optional allocator error if one occured, `nil` otherwise
  2461. */
  2462. right_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) #optional_allocator_error {
  2463. n := rune_count(str)
  2464. if n >= length || pad == "" {
  2465. return clone(str, allocator)
  2466. }
  2467. remains := length-n
  2468. pad_len := rune_count(pad)
  2469. b: Builder
  2470. builder_init(&b, allocator)
  2471. builder_init(&b, 0, len(str) + (remains/pad_len + 1)*len(pad), allocator) or_return
  2472. w := to_writer(&b)
  2473. write_pad_string(w, pad, pad_len, remains)
  2474. io.write_string(w, str)
  2475. return to_string(b), nil
  2476. }
  2477. /*
  2478. Writes a given pad string a specified number of times to an `io.Writer`
  2479. Inputs:
  2480. - w: The io.Writer to write the pad string to
  2481. - pad: The pad string to be written
  2482. - pad_len: The length of the pad string, in runes
  2483. - remains: The number of times to write the pad string, in runes
  2484. */
  2485. @private
  2486. write_pad_string :: proc(w: io.Writer, pad: string, pad_len, remains: int) {
  2487. repeats := remains / pad_len
  2488. for i := 0; i < repeats; i += 1 {
  2489. io.write_string(w, pad)
  2490. }
  2491. n := remains % pad_len
  2492. p := pad
  2493. for i := 0; i < n; i += 1 {
  2494. r, width := utf8.decode_rune_in_string(p)
  2495. io.write_rune(w, r)
  2496. p = p[width:]
  2497. }
  2498. }
  2499. /*
  2500. 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`
  2501. *Allocates Using Provided Allocator*
  2502. Inputs:
  2503. - s: The input string
  2504. - allocator: (default is context.allocator)
  2505. Returns:
  2506. - res: A slice of substrings of the input string, or an empty slice if the input string only contains white space
  2507. - err: An optional allocator error if one occured, `nil` otherwise
  2508. */
  2509. fields :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (res: []string, err: mem.Allocator_Error) #optional_allocator_error #no_bounds_check {
  2510. n := 0
  2511. was_space := 1
  2512. set_bits := u8(0)
  2513. // check to see
  2514. for i in 0..<len(s) {
  2515. r := s[i]
  2516. set_bits |= r
  2517. is_space := int(_ascii_space[r])
  2518. n += was_space & ~is_space
  2519. was_space = is_space
  2520. }
  2521. if set_bits >= utf8.RUNE_SELF {
  2522. return fields_proc(s, unicode.is_space, allocator)
  2523. }
  2524. if n == 0 {
  2525. return nil, nil
  2526. }
  2527. a := make([]string, n, allocator, loc) or_return
  2528. na := 0
  2529. field_start := 0
  2530. i := 0
  2531. for i < len(s) && _ascii_space[s[i]] {
  2532. i += 1
  2533. }
  2534. field_start = i
  2535. for i < len(s) {
  2536. if !_ascii_space[s[i]] {
  2537. i += 1
  2538. continue
  2539. }
  2540. a[na] = s[field_start : i]
  2541. na += 1
  2542. i += 1
  2543. for i < len(s) && _ascii_space[s[i]] {
  2544. i += 1
  2545. }
  2546. field_start = i
  2547. }
  2548. if field_start < len(s) {
  2549. a[na] = s[field_start:]
  2550. }
  2551. return a, nil
  2552. }
  2553. /*
  2554. Splits a string into a slice of substrings at each run of unicode code points `r` satisfying the predicate `f(r)`
  2555. *Allocates Using Provided Allocator*
  2556. Inputs:
  2557. - s: The input string
  2558. - f: A predicate function to determine the split points
  2559. - allocator: (default is context.allocator)
  2560. 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`
  2561. Returns:
  2562. - 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
  2563. - err: An optional allocator error if one occured, `nil` otherwise
  2564. */
  2565. 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 {
  2566. substrings := make([dynamic]string, 0, 32, allocator, loc) or_return
  2567. start, end := -1, -1
  2568. for r, offset in s {
  2569. end = offset
  2570. if f(r) {
  2571. if start >= 0 {
  2572. append(&substrings, s[start : end])
  2573. // -1 could be used, but just speed it up through bitwise not
  2574. // gotta love 2's complement
  2575. start = ~start
  2576. }
  2577. } else {
  2578. if start < 0 {
  2579. start = end
  2580. }
  2581. }
  2582. }
  2583. if start >= 0 {
  2584. append(&substrings, s[start : len(s)])
  2585. }
  2586. return substrings[:], nil
  2587. }
  2588. /*
  2589. 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
  2590. Inputs:
  2591. - s: A mutable string reference to be iterated
  2592. Returns:
  2593. - field: The first non-space substring found
  2594. - ok: A boolean indicating if a non-space substring was found
  2595. */
  2596. fields_iterator :: proc(s: ^string) -> (field: string, ok: bool) {
  2597. start, end := -1, -1
  2598. for r, offset in s {
  2599. end = offset
  2600. if unicode.is_space(r) {
  2601. if start >= 0 {
  2602. field = s[start : end]
  2603. ok = true
  2604. s^ = s[end:]
  2605. return
  2606. }
  2607. } else {
  2608. if start < 0 {
  2609. start = end
  2610. }
  2611. }
  2612. }
  2613. // if either of these are true, the string did not contain any characters
  2614. if end < 0 || start < 0 {
  2615. return "", false
  2616. }
  2617. field = s[start:]
  2618. ok = true
  2619. s^ = s[len(s):]
  2620. return
  2621. }
  2622. /*
  2623. Computes the Levenshtein edit distance between two strings
  2624. *Allocates Using Provided Allocator (deletion occurs internal to proc)*
  2625. NOTE: Does not perform internal allocation if length of string `b`, in runes, is smaller than 64
  2626. Inputs:
  2627. - a, b: The two strings to compare
  2628. - allocator: (default is context.allocator)
  2629. Returns:
  2630. - res: The Levenshtein edit distance between the two strings
  2631. - err: An optional allocator error if one occured, `nil` otherwise
  2632. NOTE: This implementation is a single-row-version of the Wagner–Fischer algorithm, based on C code by Martin Ettl.
  2633. */
  2634. levenshtein_distance :: proc(a, b: string, allocator := context.allocator, loc := #caller_location) -> (res: int, err: mem.Allocator_Error) #optional_allocator_error {
  2635. LEVENSHTEIN_DEFAULT_COSTS: []int : {
  2636. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  2637. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
  2638. 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  2639. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
  2640. 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
  2641. 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  2642. 60, 61, 62, 63,
  2643. }
  2644. m, n := utf8.rune_count_in_string(a), utf8.rune_count_in_string(b)
  2645. if m == 0 {
  2646. return n, nil
  2647. }
  2648. if n == 0 {
  2649. return m, nil
  2650. }
  2651. costs: []int
  2652. if n + 1 > len(LEVENSHTEIN_DEFAULT_COSTS) {
  2653. costs = make([]int, n + 1, allocator, loc) or_return
  2654. for k in 0..=n {
  2655. costs[k] = k
  2656. }
  2657. } else {
  2658. costs = LEVENSHTEIN_DEFAULT_COSTS
  2659. }
  2660. defer if n + 1 > len(LEVENSHTEIN_DEFAULT_COSTS) {
  2661. delete(costs, allocator)
  2662. }
  2663. i: int
  2664. for c1 in a {
  2665. costs[0] = i + 1
  2666. corner := i
  2667. j: int
  2668. for c2 in b {
  2669. upper := costs[j + 1]
  2670. if c1 == c2 {
  2671. costs[j + 1] = corner
  2672. } else {
  2673. t := upper if upper < corner else corner
  2674. costs[j + 1] = (costs[j] if costs[j] < t else t) + 1
  2675. }
  2676. corner = upper
  2677. j += 1
  2678. }
  2679. i += 1
  2680. }
  2681. return costs[n], nil
  2682. }
  2683. @(private)
  2684. internal_substring :: proc(s: string, rune_start: int, rune_end: int) -> (sub: string, ok: bool) {
  2685. sub = s
  2686. ok = true
  2687. rune_i: int
  2688. if rune_start > 0 {
  2689. ok = false
  2690. for _, i in sub {
  2691. if rune_start == rune_i {
  2692. ok = true
  2693. sub = sub[i:]
  2694. break
  2695. }
  2696. rune_i += 1
  2697. }
  2698. if !ok { return }
  2699. }
  2700. if rune_end >= rune_start {
  2701. ok = false
  2702. for _, i in sub {
  2703. if rune_end == rune_i {
  2704. ok = true
  2705. sub = sub[:i]
  2706. break
  2707. }
  2708. rune_i += 1
  2709. }
  2710. if rune_end == rune_i {
  2711. ok = true
  2712. }
  2713. }
  2714. return
  2715. }
  2716. /*
  2717. Returns a substring of `s` that starts at rune index `rune_start` and goes up to `rune_end`.
  2718. Think of it as slicing `s[rune_start:rune_end]` but rune-wise.
  2719. Inputs:
  2720. - s: the string to substring
  2721. - rune_start: the start (inclusive) rune
  2722. - rune_end: the end (exclusive) rune
  2723. Returns:
  2724. - sub: the substring
  2725. - ok: whether the rune indexes where in bounds of the original string
  2726. */
  2727. substring :: proc(s: string, rune_start: int, rune_end: int) -> (sub: string, ok: bool) {
  2728. if rune_start < 0 || rune_end < 0 || rune_end < rune_start {
  2729. return
  2730. }
  2731. return internal_substring(s, rune_start, rune_end)
  2732. }
  2733. /*
  2734. Returns a substring of `s` that starts at rune index `rune_start` and goes up to the end of the string.
  2735. Think of it as slicing `s[rune_start:]` but rune-wise.
  2736. Inputs:
  2737. - s: the string to substring
  2738. - rune_start: the start (inclusive) rune
  2739. Returns:
  2740. - sub: the substring
  2741. - ok: whether the rune indexes where in bounds of the original string
  2742. */
  2743. substring_from :: proc(s: string, rune_start: int) -> (sub: string, ok: bool) {
  2744. if rune_start < 0 {
  2745. return
  2746. }
  2747. return internal_substring(s, rune_start, -1)
  2748. }
  2749. /*
  2750. Returns a substring of `s` that goes up to rune index `rune_end`.
  2751. Think of it as slicing `s[:rune_end]` but rune-wise.
  2752. Inputs:
  2753. - s: the string to substring
  2754. - rune_end: the end (exclusive) rune
  2755. Returns:
  2756. - sub: the substring
  2757. - ok: whether the rune indexes where in bounds of the original string
  2758. */
  2759. substring_to :: proc(s: string, rune_end: int) -> (sub: string, ok: bool) {
  2760. if rune_end < 0 {
  2761. return
  2762. }
  2763. return internal_substring(s, -1, rune_end)
  2764. }