strings.odin 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. // simple procedures to manipulate UTF-8 encoded strings
  2. package strings
  3. import "core:io"
  4. import "core:mem"
  5. import "core:slice"
  6. import "core:unicode"
  7. import "core:unicode/utf8"
  8. // returns a clone of the string `s` allocated using the `allocator`
  9. clone :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> string {
  10. c := make([]byte, len(s), allocator, loc)
  11. copy(c, s)
  12. return string(c[:len(s)])
  13. }
  14. // returns a clone of the string `s` allocated using the `allocator`
  15. clone_safe :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> (str: string, err: mem.Allocator_Error) {
  16. c := make([]byte, len(s), allocator, loc) or_return
  17. copy(c, s)
  18. return string(c[:len(s)]), nil
  19. }
  20. // returns a clone of the string `s` allocated using the `allocator` as a cstring
  21. // a nul byte is appended to the clone, to make the cstring safe
  22. clone_to_cstring :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> cstring {
  23. c := make([]byte, len(s)+1, allocator, loc)
  24. copy(c, s)
  25. c[len(s)] = 0
  26. return cstring(&c[0])
  27. }
  28. // returns a string from a byte pointer `ptr` and byte length `len`
  29. // the string is valid as long as the parameters stay alive
  30. string_from_ptr :: proc(ptr: ^byte, len: int) -> string {
  31. return transmute(string)mem.Raw_String{ptr, len}
  32. }
  33. // returns a string from a byte pointer `ptr and byte length `len`
  34. // searches for a nul byte from 0..<len, otherwhise `len` will be the end size
  35. string_from_nul_terminated_ptr :: proc(ptr: ^byte, len: int) -> string {
  36. s := transmute(string)mem.Raw_String{ptr, len}
  37. s = truncate_to_byte(s, 0)
  38. return s
  39. }
  40. // returns the raw ^byte start of the string `str`
  41. ptr_from_string :: proc(str: string) -> ^byte {
  42. d := transmute(mem.Raw_String)str
  43. return d.data
  44. }
  45. // returns the transmute of string `str` to a cstring
  46. // not safe since the origin string may not contain a nul byte
  47. unsafe_string_to_cstring :: proc(str: string) -> cstring {
  48. d := transmute(mem.Raw_String)str
  49. return cstring(d.data)
  50. }
  51. // returns a string truncated to the first time it finds the byte `b`
  52. // uses the `len` of the string `str` when it couldn't find the input
  53. truncate_to_byte :: proc(str: string, b: byte) -> string {
  54. n := index_byte(str, b)
  55. if n < 0 {
  56. n = len(str)
  57. }
  58. return str[:n]
  59. }
  60. // returns a string truncated to the first time it finds the rune `r`
  61. // uses the `len` of the string `str` when it couldn't find the input
  62. truncate_to_rune :: proc(str: string, r: rune) -> string {
  63. n := index_rune(str, r)
  64. if n < 0 {
  65. n = len(str)
  66. }
  67. return str[:n]
  68. }
  69. // returns a cloned string of the byte array `s` using the `allocator`
  70. // appends a leading nul byte
  71. clone_from_bytes :: proc(s: []byte, allocator := context.allocator, loc := #caller_location) -> string {
  72. c := make([]byte, len(s)+1, allocator, loc)
  73. copy(c, s)
  74. c[len(s)] = 0
  75. return string(c[:len(s)])
  76. }
  77. // returns a clone of the cstring `s` using the `allocator` as a string
  78. clone_from_cstring :: proc(s: cstring, allocator := context.allocator, loc := #caller_location) -> string {
  79. return clone(string(s), allocator, loc)
  80. }
  81. // returns a cloned string from the pointer `ptr` and a byte length `len` using the `allocator`
  82. // same to `string_from_ptr` but allocates
  83. clone_from_ptr :: proc(ptr: ^byte, len: int, allocator := context.allocator, loc := #caller_location) -> string {
  84. s := string_from_ptr(ptr, len)
  85. return clone(s, allocator, loc)
  86. }
  87. // overload to clone from a `string`, `[]byte`, `cstring` or a `^byte + length` to a string
  88. clone_from :: proc{
  89. clone,
  90. clone_from_bytes,
  91. clone_from_cstring,
  92. clone_from_ptr,
  93. }
  94. // returns a cloned string from the cstring `ptr` and a byte length `len` using the `allocator`
  95. // truncates till the first nul byte it finds or the byte len
  96. clone_from_cstring_bounded :: proc(ptr: cstring, len: int, allocator := context.allocator, loc := #caller_location) -> string {
  97. s := string_from_ptr((^u8)(ptr), len)
  98. s = truncate_to_byte(s, 0)
  99. return clone(s, allocator, loc)
  100. }
  101. // Compares two strings, returning a value representing which one comes first lexiographically.
  102. // -1 for `lhs`; 1 for `rhs`, or 0 if they are equal.
  103. compare :: proc(lhs, rhs: string) -> int {
  104. return mem.compare(transmute([]byte)lhs, transmute([]byte)rhs)
  105. }
  106. // returns the byte offset of the rune `r` in the string `s`, -1 when not found
  107. contains_rune :: proc(s: string, r: rune) -> int {
  108. for c, offset in s {
  109. if c == r {
  110. return offset
  111. }
  112. }
  113. return -1
  114. }
  115. /*
  116. returns true when the string `substr` is contained inside the string `s`
  117. strings.contains("testing", "test") -> true
  118. strings.contains("testing", "ing") -> true
  119. strings.contains("testing", "text") -> false
  120. */
  121. contains :: proc(s, substr: string) -> bool {
  122. return index(s, substr) >= 0
  123. }
  124. /*
  125. returns true when the string `s` contains any of the characters inside the string `chars`
  126. strings.contains_any("test", "test") -> true
  127. strings.contains_any("test", "ts") -> true
  128. strings.contains_any("test", "et") -> true
  129. strings.contains_any("test", "a") -> false
  130. */
  131. contains_any :: proc(s, chars: string) -> bool {
  132. return index_any(s, chars) >= 0
  133. }
  134. /*
  135. returns the utf8 rune count of the string `s`
  136. strings.rune_count("test") -> 4
  137. strings.rune_count("testö") -> 5, where len("testö") -> 6
  138. */
  139. rune_count :: proc(s: string) -> int {
  140. return utf8.rune_count_in_string(s)
  141. }
  142. /*
  143. returns wether the strings `u` and `v` are the same alpha characters
  144. works with utf8 string content and ignores different casings
  145. strings.equal_fold("test", "test") -> true
  146. strings.equal_fold("Test", "test") -> true
  147. strings.equal_fold("Test", "tEsT") -> true
  148. strings.equal_fold("test", "tes") -> false
  149. */
  150. equal_fold :: proc(u, v: string) -> bool {
  151. s, t := u, v
  152. loop: for s != "" && t != "" {
  153. sr, tr: rune
  154. if s[0] < utf8.RUNE_SELF {
  155. sr, s = rune(s[0]), s[1:]
  156. } else {
  157. r, size := utf8.decode_rune_in_string(s)
  158. sr, s = r, s[size:]
  159. }
  160. if t[0] < utf8.RUNE_SELF {
  161. tr, t = rune(t[0]), t[1:]
  162. } else {
  163. r, size := utf8.decode_rune_in_string(t)
  164. tr, t = r, t[size:]
  165. }
  166. if tr == sr { // easy case
  167. continue loop
  168. }
  169. if tr < sr {
  170. tr, sr = sr, tr
  171. }
  172. if tr < utf8.RUNE_SELF {
  173. switch sr {
  174. case 'A'..='Z':
  175. if tr == (sr+'a')-'A' {
  176. continue loop
  177. }
  178. }
  179. return false
  180. }
  181. // TODO(bill): Unicode folding
  182. return false
  183. }
  184. return s == t
  185. }
  186. /*
  187. return true when the string `prefix` is contained at the start of the string `s`
  188. strings.has_prefix("testing", "test") -> true
  189. strings.has_prefix("testing", "te") -> true
  190. strings.has_prefix("telephone", "te") -> true
  191. strings.has_prefix("testing", "est") -> false
  192. */
  193. has_prefix :: proc(s, prefix: string) -> bool {
  194. return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
  195. }
  196. /*
  197. returns true when the string `suffix` is contained at the end of the string `s`
  198. good example to use this is for file extensions
  199. strings.has_suffix("todo.txt", ".txt") -> true
  200. strings.has_suffix("todo.doc", ".txt") -> false
  201. strings.has_suffix("todo.doc.txt", ".txt") -> true
  202. */
  203. has_suffix :: proc(s, suffix: string) -> bool {
  204. return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
  205. }
  206. /*
  207. returns a combined string from the slice of strings `a` seperated with the `sep` string
  208. allocates the string using the `allocator`
  209. a := [?]string { "a", "b", "c" }
  210. b := strings.join(a[:], " ") -> "a b c"
  211. c := strings.join(a[:], "-") -> "a-b-c"
  212. d := strings.join(a[:], "...") -> "a...b...c"
  213. */
  214. join :: proc(a: []string, sep: string, allocator := context.allocator) -> string {
  215. if len(a) == 0 {
  216. return ""
  217. }
  218. n := len(sep) * (len(a) - 1)
  219. for s in a {
  220. n += len(s)
  221. }
  222. b := make([]byte, n, allocator)
  223. i := copy(b, a[0])
  224. for s in a[1:] {
  225. i += copy(b[i:], sep)
  226. i += copy(b[i:], s)
  227. }
  228. return string(b)
  229. }
  230. join_safe :: proc(a: []string, sep: string, allocator := context.allocator) -> (str: string, err: mem.Allocator_Error) {
  231. if len(a) == 0 {
  232. return "", nil
  233. }
  234. n := len(sep) * (len(a) - 1)
  235. for s in a {
  236. n += len(s)
  237. }
  238. b := make([]byte, n, allocator) or_return
  239. i := copy(b, a[0])
  240. for s in a[1:] {
  241. i += copy(b[i:], sep)
  242. i += copy(b[i:], s)
  243. }
  244. return string(b), nil
  245. }
  246. /*
  247. returns a combined string from the slice of strings `a` without a seperator
  248. allocates the string using the `allocator`
  249. a := [?]string { "a", "b", "c" }
  250. b := strings.concatenate(a[:]) -> "abc"
  251. */
  252. concatenate :: proc(a: []string, allocator := context.allocator) -> string {
  253. if len(a) == 0 {
  254. return ""
  255. }
  256. n := 0
  257. for s in a {
  258. n += len(s)
  259. }
  260. b := make([]byte, n, allocator)
  261. i := 0
  262. for s in a {
  263. i += copy(b[i:], s)
  264. }
  265. return string(b)
  266. }
  267. concatenate_safe :: proc(a: []string, allocator := context.allocator) -> (res: string, err: mem.Allocator_Error) {
  268. if len(a) == 0 {
  269. return "", nil
  270. }
  271. n := 0
  272. for s in a {
  273. n += len(s)
  274. }
  275. b := make([]byte, n, allocator) or_return
  276. i := 0
  277. for s in a {
  278. i += copy(b[i:], s)
  279. }
  280. return string(b), nil
  281. }
  282. /*
  283. `rune_offset` and `rune_length` are in runes, not bytes.
  284. If `rune_length` <= 0, then it'll return the remainder of the string starting at `rune_offset`.
  285. strings.cut("some example text", 0, 4) -> "some"
  286. strings.cut("some example text", 2, 2) -> "me"
  287. strings.cut("some example text", 5, 7) -> "example"
  288. */
  289. cut :: proc(s: string, rune_offset := int(0), rune_length := int(0), allocator := context.allocator) -> (res: string) {
  290. s := s; rune_length := rune_length
  291. context.allocator = allocator
  292. // If we signal that we want the entire remainder (length <= 0) *and*
  293. // the offset is zero, then we can early out by cloning the input
  294. if rune_offset == 0 && rune_length <= 0 {
  295. return clone(s)
  296. }
  297. // We need to know if we have enough runes to cover offset + length.
  298. rune_count := utf8.rune_count_in_string(s)
  299. // We're asking for a substring starting after the end of the input string.
  300. // That's just an empty string.
  301. if rune_offset >= rune_count {
  302. return ""
  303. }
  304. // If we don't specify the length of the substring, use the remainder.
  305. if rune_length <= 0 {
  306. rune_length = rune_count - rune_offset
  307. }
  308. // We don't yet know how many bytes we need exactly.
  309. // But we do know it's bounded by the number of runes * 4 bytes,
  310. // and can be no more than the size of the input string.
  311. bytes_needed := min(rune_length * 4, len(s))
  312. buf := make([]u8, bytes_needed)
  313. byte_offset := 0
  314. for i := 0; i < rune_count; i += 1 {
  315. _, w := utf8.decode_rune_in_string(s)
  316. // If the rune is part of the substring, copy it to the output buffer.
  317. if i >= rune_offset {
  318. for j := 0; j < w; j += 1 {
  319. buf[byte_offset+j] = s[j]
  320. }
  321. byte_offset += w
  322. }
  323. // We're done if we reach the end of the input string, *or*
  324. // if we've reached a specified length in runes.
  325. if rune_length > 0 {
  326. if i == rune_offset + rune_length - 1 { break }
  327. }
  328. s = s[w:]
  329. }
  330. return string(buf[:byte_offset])
  331. }
  332. @private
  333. _split :: proc(s_, sep: string, sep_save, n_: int, allocator := context.allocator) -> []string {
  334. s, n := s_, n_
  335. if n == 0 {
  336. return nil
  337. }
  338. if sep == "" {
  339. l := utf8.rune_count_in_string(s)
  340. if n < 0 || n > l {
  341. n = l
  342. }
  343. res := make([dynamic]string, n, allocator)
  344. for i := 0; i < n-1; i += 1 {
  345. _, w := utf8.decode_rune_in_string(s)
  346. res[i] = s[:w]
  347. s = s[w:]
  348. }
  349. if n > 0 {
  350. res[n-1] = s
  351. }
  352. return res[:]
  353. }
  354. if n < 0 {
  355. n = count(s, sep) + 1
  356. }
  357. res := make([dynamic]string, n, allocator)
  358. n -= 1
  359. i := 0
  360. for ; i < n; i += 1 {
  361. m := index(s, sep)
  362. if m < 0 {
  363. break
  364. }
  365. res[i] = s[:m+sep_save]
  366. s = s[m+len(sep):]
  367. }
  368. res[i] = s
  369. return res[:i+1]
  370. }
  371. /*
  372. Splits a string into parts, based on a separator.
  373. Returned strings are substrings of 's'.
  374. ```
  375. s := "aaa.bbb.ccc.ddd.eee" // 5 parts
  376. ss := split(s, ".")
  377. fmt.println(ss) // [aaa, bbb, ccc, ddd, eee]
  378. ```
  379. */
  380. split :: proc(s, sep: string, allocator := context.allocator) -> []string {
  381. return _split(s, sep, 0, -1, allocator)
  382. }
  383. /*
  384. Splits a string into a total of 'n' parts, based on a separator.
  385. Returns fewer parts if there wasn't enough occurrences of the separator.
  386. Returned strings are substrings of 's'.
  387. ```
  388. s := "aaa.bbb.ccc.ddd.eee" // 5 parts present
  389. ss := split_n(s, ".", 3) // total of 3 wanted
  390. fmt.println(ss) // [aaa, bbb, ccc.ddd.eee]
  391. ```
  392. */
  393. split_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  394. return _split(s, sep, 0, n, allocator)
  395. }
  396. /*
  397. splits the string `s` after the seperator string `sep` appears
  398. returns the slice of split strings allocated using `allocator`
  399. a := "aaa.bbb.ccc.ddd.eee"
  400. aa := strings.split_after(a, ".")
  401. fmt.eprintln(aa) // [aaa., bbb., ccc., ddd., eee]
  402. */
  403. split_after :: proc(s, sep: string, allocator := context.allocator) -> []string {
  404. return _split(s, sep, len(sep), -1, allocator)
  405. }
  406. /*
  407. splits the string `s` after the seperator string `sep` appears into a total of `n` parts
  408. returns the slice of split strings allocated using `allocator`
  409. a := "aaa.bbb.ccc.ddd.eee"
  410. aa := strings.split_after(a, ".")
  411. fmt.eprintln(aa) // [aaa., bbb., ccc., ddd., eee]
  412. */
  413. split_after_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  414. return _split(s, sep, len(sep), n, allocator)
  415. }
  416. @private
  417. _split_iterator :: proc(s: ^string, sep: string, sep_save: int) -> (res: string, ok: bool) {
  418. // stop once the string is empty or nil
  419. if s == nil || len(s^) == 0 {
  420. return
  421. }
  422. if sep == "" {
  423. res = s[:]
  424. ok = true
  425. s^ = s[len(s):]
  426. return
  427. }
  428. m := index(s^, sep)
  429. if m < 0 {
  430. // not found
  431. res = s[:]
  432. ok = res != ""
  433. s^ = s[len(s):]
  434. } else {
  435. res = s[:m+sep_save]
  436. ok = true
  437. s^ = s[m+len(sep):]
  438. }
  439. return
  440. }
  441. /*
  442. split the ^string `s` by the byte seperator `sep` in an iterator fashion
  443. consumes the original string till the end, leaving the string `s` with len == 0
  444. text := "a.b.c.d.e"
  445. for str in strings.split_by_byte_iterator(&text, '.') {
  446. fmt.eprintln(str) // every loop -> a b c d e
  447. }
  448. */
  449. split_by_byte_iterator :: proc(s: ^string, sep: u8) -> (res: string, ok: bool) {
  450. m := index_byte(s^, sep)
  451. if m < 0 {
  452. // not found
  453. res = s[:]
  454. ok = res != ""
  455. s^ = {}
  456. } else {
  457. res = s[:m]
  458. ok = true
  459. s^ = s[m+1:]
  460. }
  461. return
  462. }
  463. /*
  464. split the ^string `s` by the seperator string `sep` in an iterator fashion
  465. consumes the original string till the end
  466. text := "a.b.c.d.e"
  467. for str in strings.split_iterator(&text, ".") {
  468. fmt.eprintln(str) // every loop -> a b c d e
  469. }
  470. */
  471. split_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  472. return _split_iterator(s, sep, 0)
  473. }
  474. /*
  475. split the ^string `s` after every seperator string `sep` in an iterator fashion
  476. consumes the original string till the end
  477. text := "a.b.c.d.e"
  478. for str in strings.split_after_iterator(&text, ".") {
  479. fmt.eprintln(str) // every loop -> a. b. c. d. e
  480. }
  481. */
  482. split_after_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  483. return _split_iterator(s, sep, len(sep))
  484. }
  485. @(private)
  486. _trim_cr :: proc(s: string) -> string {
  487. n := len(s)
  488. if n > 0 {
  489. if s[n-1] == '\r' {
  490. return s[:n-1]
  491. }
  492. }
  493. return s
  494. }
  495. /*
  496. split the string `s` at every line break '\n'
  497. return an allocated slice of strings
  498. a := "a\nb\nc\nd\ne"
  499. b := strings.split_lines(a)
  500. fmt.eprintln(b) // [a, b, c, d, e]
  501. */
  502. split_lines :: proc(s: string, allocator := context.allocator) -> []string {
  503. sep :: "\n"
  504. lines := _split(s, sep, 0, -1, allocator)
  505. for line in &lines {
  506. line = _trim_cr(line)
  507. }
  508. return lines
  509. }
  510. /*
  511. split the string `s` at every line break '\n' for `n` parts
  512. return an allocated slice of strings
  513. a := "a\nb\nc\nd\ne"
  514. b := strings.split_lines_n(a, 3)
  515. fmt.eprintln(b) // [a, b, c, d\ne\n]
  516. */
  517. split_lines_n :: proc(s: string, n: int, allocator := context.allocator) -> []string {
  518. sep :: "\n"
  519. lines := _split(s, sep, 0, n, allocator)
  520. for line in &lines {
  521. line = _trim_cr(line)
  522. }
  523. return lines
  524. }
  525. /*
  526. split the string `s` at every line break '\n' leaving the '\n' in the resulting strings
  527. return an allocated slice of strings
  528. a := "a\nb\nc\nd\ne"
  529. b := strings.split_lines_after(a)
  530. fmt.eprintln(b) // [a\n, b\n, c\n, d\n, e\n]
  531. */
  532. split_lines_after :: proc(s: string, allocator := context.allocator) -> []string {
  533. sep :: "\n"
  534. lines := _split(s, sep, len(sep), -1, allocator)
  535. for line in &lines {
  536. line = _trim_cr(line)
  537. }
  538. return lines
  539. }
  540. /*
  541. split the string `s` at every line break '\n' leaving the '\n' in the resulting strings
  542. only runs for `n` parts
  543. return an allocated slice of strings
  544. a := "a\nb\nc\nd\ne"
  545. b := strings.split_lines_after_n(a, 3)
  546. fmt.eprintln(b) // [a\n, b\n, c\n, d\ne\n]
  547. */
  548. split_lines_after_n :: proc(s: string, n: int, allocator := context.allocator) -> []string {
  549. sep :: "\n"
  550. lines := _split(s, sep, len(sep), n, allocator)
  551. for line in &lines {
  552. line = _trim_cr(line)
  553. }
  554. return lines
  555. }
  556. /*
  557. split the string `s` at every line break '\n'
  558. returns the current split string every iteration till the string is consumed
  559. text := "a\nb\nc\nd\ne"
  560. for str in strings.split_lines_iterator(&text) {
  561. fmt.eprintln(text) // every loop -> a b c d e
  562. }
  563. */
  564. split_lines_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  565. sep :: "\n"
  566. line = _split_iterator(s, sep, 0) or_return
  567. return _trim_cr(line), true
  568. }
  569. /*
  570. split the string `s` at every line break '\n'
  571. returns the current split string every iteration till the string is consumed
  572. text := "a\nb\nc\nd\ne"
  573. for str in strings.split_lines_after_iterator(&text) {
  574. fmt.eprintln(text) // every loop -> a\n b\n c\n d\n e\n
  575. }
  576. */
  577. split_lines_after_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  578. sep :: "\n"
  579. line = _split_iterator(s, sep, len(sep)) or_return
  580. return _trim_cr(line), true
  581. }
  582. /*
  583. returns the byte offset of the first byte `c` in the string `s` it finds, -1 when not found
  584. can't find utf8 based runes
  585. strings.index_byte("test", 't') -> 0
  586. strings.index_byte("test", 'e') -> 1
  587. strings.index_byte("test", 'x') -> -1
  588. strings.index_byte("teäst", 'ä') -> -1
  589. */
  590. index_byte :: proc(s: string, c: byte) -> int {
  591. for i := 0; i < len(s); i += 1 {
  592. if s[i] == c {
  593. return i
  594. }
  595. }
  596. return -1
  597. }
  598. /*
  599. returns the byte offset of the last byte `c` in the string `s` it finds, -1 when not found
  600. can't find utf8 based runes
  601. strings.index_byte("test", 't') -> 3
  602. strings.index_byte("test", 'e') -> 1
  603. strings.index_byte("test", 'x') -> -1
  604. strings.index_byte("teäst", 'ä') -> -1
  605. */
  606. last_index_byte :: proc(s: string, c: byte) -> int {
  607. for i := len(s)-1; i >= 0; i -= 1 {
  608. if s[i] == c {
  609. return i
  610. }
  611. }
  612. return -1
  613. }
  614. /*
  615. returns the byte offset of the first rune `r` in the string `s` it finds, -1 when not found
  616. avoids invalid runes
  617. strings.index_rune("abcädef", 'x') -> -1
  618. strings.index_rune("abcädef", 'a') -> 0
  619. strings.index_rune("abcädef", 'b') -> 1
  620. strings.index_rune("abcädef", 'c') -> 2
  621. strings.index_rune("abcädef", 'ä') -> 3
  622. strings.index_rune("abcädef", 'd') -> 5
  623. strings.index_rune("abcädef", 'e') -> 6
  624. strings.index_rune("abcädef", 'f') -> 7
  625. */
  626. index_rune :: proc(s: string, r: rune) -> int {
  627. switch {
  628. case 0 <= r && r < utf8.RUNE_SELF:
  629. return index_byte(s, byte(r))
  630. case r == utf8.RUNE_ERROR:
  631. for c, i in s {
  632. if c == utf8.RUNE_ERROR {
  633. return i
  634. }
  635. }
  636. return -1
  637. case !utf8.valid_rune(r):
  638. return -1
  639. }
  640. b, w := utf8.encode_rune(r)
  641. return index(s, string(b[:w]))
  642. }
  643. @private PRIME_RABIN_KARP :: 16777619
  644. /*
  645. returns the byte offset of the string `substr` in the string `s`, -1 when not found
  646. strings.index("test", "t") -> 0
  647. strings.index("test", "te") -> 0
  648. strings.index("test", "st") -> 2
  649. strings.index("test", "tt") -> -1
  650. */
  651. index :: proc(s, substr: string) -> int {
  652. hash_str_rabin_karp :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  653. for i := 0; i < len(s); i += 1 {
  654. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  655. }
  656. sq := u32(PRIME_RABIN_KARP)
  657. for i := len(s); i > 0; i >>= 1 {
  658. if (i & 1) != 0 {
  659. pow *= sq
  660. }
  661. sq *= sq
  662. }
  663. return
  664. }
  665. n := len(substr)
  666. switch {
  667. case n == 0:
  668. return 0
  669. case n == 1:
  670. return index_byte(s, substr[0])
  671. case n == len(s):
  672. if s == substr {
  673. return 0
  674. }
  675. return -1
  676. case n > len(s):
  677. return -1
  678. }
  679. hash, pow := hash_str_rabin_karp(substr)
  680. h: u32
  681. for i := 0; i < n; i += 1 {
  682. h = h*PRIME_RABIN_KARP + u32(s[i])
  683. }
  684. if h == hash && s[:n] == substr {
  685. return 0
  686. }
  687. for i := n; i < len(s); /**/ {
  688. h *= PRIME_RABIN_KARP
  689. h += u32(s[i])
  690. h -= pow * u32(s[i-n])
  691. i += 1
  692. if h == hash && s[i-n:i] == substr {
  693. return i - n
  694. }
  695. }
  696. return -1
  697. }
  698. /*
  699. returns the last byte offset of the string `substr` in the string `s`, -1 when not found
  700. strings.index("test", "t") -> 3
  701. strings.index("test", "te") -> 0
  702. strings.index("test", "st") -> 2
  703. strings.index("test", "tt") -> -1
  704. */
  705. last_index :: proc(s, substr: string) -> int {
  706. hash_str_rabin_karp_reverse :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  707. for i := len(s) - 1; i >= 0; i -= 1 {
  708. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  709. }
  710. sq := u32(PRIME_RABIN_KARP)
  711. for i := len(s); i > 0; i >>= 1 {
  712. if (i & 1) != 0 {
  713. pow *= sq
  714. }
  715. sq *= sq
  716. }
  717. return
  718. }
  719. n := len(substr)
  720. switch {
  721. case n == 0:
  722. return len(s)
  723. case n == 1:
  724. return last_index_byte(s, substr[0])
  725. case n == len(s):
  726. return 0 if substr == s else -1
  727. case n > len(s):
  728. return -1
  729. }
  730. hash, pow := hash_str_rabin_karp_reverse(substr)
  731. last := len(s) - n
  732. h: u32
  733. for i := len(s)-1; i >= last; i -= 1 {
  734. h = h*PRIME_RABIN_KARP + u32(s[i])
  735. }
  736. if h == hash && s[last:] == substr {
  737. return last
  738. }
  739. for i := last-1; i >= 0; i -= 1 {
  740. h *= PRIME_RABIN_KARP
  741. h += u32(s[i])
  742. h -= pow * u32(s[i+n])
  743. if h == hash && s[i:i+n] == substr {
  744. return i
  745. }
  746. }
  747. return -1
  748. }
  749. /*
  750. returns the index of any first char of `chars` found in `s`, -1 if not found
  751. strings.index_any("test", "s") -> 2
  752. strings.index_any("test", "se") -> 1
  753. strings.index_any("test", "et") -> 0
  754. strings.index_any("test", "set") -> 0
  755. strings.index_any("test", "x") -> -1
  756. */
  757. index_any :: proc(s, chars: string) -> int {
  758. if chars == "" {
  759. return -1
  760. }
  761. if len(chars) == 1 {
  762. r := rune(chars[0])
  763. if r >= utf8.RUNE_SELF {
  764. r = utf8.RUNE_ERROR
  765. }
  766. return index_rune(s, r)
  767. }
  768. if len(s) > 8 {
  769. if as, ok := ascii_set_make(chars); ok {
  770. for i in 0..<len(s) {
  771. if ascii_set_contains(as, s[i]) {
  772. return i
  773. }
  774. }
  775. return -1
  776. }
  777. }
  778. for c, i in s {
  779. if index_rune(chars, c) >= 0 {
  780. return i
  781. }
  782. }
  783. return -1
  784. }
  785. /*
  786. returns the index of any first char of `chars` found in `s`, -1 if not found
  787. iterates the string in reverse
  788. strings.index_any("test", "s") -> 2
  789. strings.index_any("test", "se") -> 2
  790. strings.index_any("test", "et") -> 1
  791. strings.index_any("test", "set") -> 3
  792. strings.index_any("test", "x") -> -1
  793. */
  794. last_index_any :: proc(s, chars: string) -> int {
  795. if chars == "" {
  796. return -1
  797. }
  798. if len(s) == 1 {
  799. r := rune(s[0])
  800. if r >= utf8.RUNE_SELF {
  801. r = utf8.RUNE_ERROR
  802. }
  803. return index_rune(chars, r)
  804. }
  805. if len(s) > 8 {
  806. if as, ok := ascii_set_make(chars); ok {
  807. for i := len(s)-1; i >= 0; i -= 1 {
  808. if ascii_set_contains(as, s[i]) {
  809. return i
  810. }
  811. }
  812. return -1
  813. }
  814. }
  815. if len(chars) == 1 {
  816. r := rune(chars[0])
  817. if r >= utf8.RUNE_SELF {
  818. r = utf8.RUNE_ERROR
  819. }
  820. for i := len(s); i > 0; /**/ {
  821. c, w := utf8.decode_last_rune_in_string(s[:i])
  822. i -= w
  823. if c == r {
  824. return i
  825. }
  826. }
  827. return -1
  828. }
  829. for i := len(s); i > 0; /**/ {
  830. r, w := utf8.decode_last_rune_in_string(s[:i])
  831. i -= w
  832. if index_rune(chars, r) >= 0 {
  833. return i
  834. }
  835. }
  836. return -1
  837. }
  838. /*
  839. returns the count of the string `substr` found in the string `s`
  840. returns the rune_count + 1 of the string `s` on empty `substr`
  841. strings.count("abbccc", "a") -> 1
  842. strings.count("abbccc", "b") -> 2
  843. strings.count("abbccc", "c") -> 3
  844. strings.count("abbccc", "ab") -> 1
  845. strings.count("abbccc", " ") -> 0
  846. */
  847. count :: proc(s, substr: string) -> int {
  848. if len(substr) == 0 { // special case
  849. return rune_count(s) + 1
  850. }
  851. if len(substr) == 1 {
  852. c := substr[0]
  853. switch len(s) {
  854. case 0:
  855. return 0
  856. case 1:
  857. return int(s[0] == c)
  858. }
  859. n := 0
  860. for i := 0; i < len(s); i += 1 {
  861. if s[i] == c {
  862. n += 1
  863. }
  864. }
  865. return n
  866. }
  867. // TODO(bill): Use a non-brute for approach
  868. n := 0
  869. str := s
  870. for {
  871. i := index(str, substr)
  872. if i == -1 {
  873. return n
  874. }
  875. n += 1
  876. str = str[i+len(substr):]
  877. }
  878. return n
  879. }
  880. /*
  881. repeats the string `s` multiple `count` times and returns the allocated string
  882. panics when `count` is below 0
  883. strings.repeat("abc", 2) -> "abcabc"
  884. */
  885. repeat :: proc(s: string, count: int, allocator := context.allocator) -> string {
  886. if count < 0 {
  887. panic("strings: negative repeat count")
  888. } else if count > 0 && (len(s)*count)/count != len(s) {
  889. panic("strings: repeat count will cause an overflow")
  890. }
  891. b := make([]byte, len(s)*count, allocator)
  892. i := copy(b, s)
  893. for i < len(b) { // 2^N trick to reduce the need to copy
  894. copy(b[i:], b[:i])
  895. i *= 2
  896. }
  897. return string(b)
  898. }
  899. /*
  900. replaces all instances of `old` in the string `s` with the `new` string
  901. returns the `output` string and true when an a allocation through a replace happened
  902. strings.replace_all("xyzxyz", "xyz", "abc") -> "abcabc", true
  903. strings.replace_all("xyzxyz", "abc", "xyz") -> "xyzxyz", false
  904. strings.replace_all("xyzxyz", "xy", "z") -> "zzzz", true
  905. */
  906. replace_all :: proc(s, old, new: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  907. return replace(s, old, new, -1, allocator)
  908. }
  909. /*
  910. replaces `n` instances of `old` in the string `s` with the `new` string
  911. if n < 0, no limit on the number of replacements
  912. returns the `output` string and true when an a allocation through a replace happened
  913. strings.replace("xyzxyz", "xyz", "abc", 2) -> "abcabc", true
  914. strings.replace("xyzxyz", "xyz", "abc", 1) -> "abcxyz", true
  915. strings.replace("xyzxyz", "abc", "xyz", -1) -> "xyzxyz", false
  916. strings.replace("xyzxyz", "xy", "z", -1) -> "zzzz", true
  917. */
  918. replace :: proc(s, old, new: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  919. if old == new || n == 0 {
  920. was_allocation = false
  921. output = s
  922. return
  923. }
  924. byte_count := n
  925. if m := count(s, old); m == 0 {
  926. was_allocation = false
  927. output = s
  928. return
  929. } else if n < 0 || m < n {
  930. byte_count = m
  931. }
  932. t := make([]byte, len(s) + byte_count*(len(new) - len(old)), allocator)
  933. was_allocation = true
  934. w := 0
  935. start := 0
  936. for i := 0; i < byte_count; i += 1 {
  937. j := start
  938. if len(old) == 0 {
  939. if i > 0 {
  940. _, width := utf8.decode_rune_in_string(s[start:])
  941. j += width
  942. }
  943. } else {
  944. j += index(s[start:], old)
  945. }
  946. w += copy(t[w:], s[start:j])
  947. w += copy(t[w:], new)
  948. start = j + len(old)
  949. }
  950. w += copy(t[w:], s[start:])
  951. output = string(t[0:w])
  952. return
  953. }
  954. /*
  955. removes the `key` string `n` times from the `s` string
  956. if n < 0, no limit on the number of removes
  957. returns the `output` string and true when an a allocation through a remove happened
  958. strings.remove("abcabc", "abc", 1) -> "abc", true
  959. strings.remove("abcabc", "abc", -1) -> "", true
  960. strings.remove("abcabc", "a", -1) -> "bcbc", true
  961. strings.remove("abcabc", "x", -1) -> "abcabc", false
  962. */
  963. remove :: proc(s, key: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  964. return replace(s, key, "", n, allocator)
  965. }
  966. /*
  967. removes all the `key` string instanes from the `s` string
  968. returns the `output` string and true when an a allocation through a remove happened
  969. strings.remove("abcabc", "abc") -> "", true
  970. strings.remove("abcabc", "a") -> "bcbc", true
  971. strings.remove("abcabc", "x") -> "abcabc", false
  972. */
  973. remove_all :: proc(s, key: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  974. return remove(s, key, -1, allocator)
  975. }
  976. @(private) _ascii_space := [256]bool{'\t' = true, '\n' = true, '\v' = true, '\f' = true, '\r' = true, ' ' = true}
  977. // return true when the `r` rune is '\t', '\n', '\v', '\f', '\r' or ' '
  978. is_ascii_space :: proc(r: rune) -> bool {
  979. if r < utf8.RUNE_SELF {
  980. return _ascii_space[u8(r)]
  981. }
  982. return false
  983. }
  984. // returns true when the `r` rune is any asci or utf8 based whitespace
  985. is_space :: proc(r: rune) -> bool {
  986. if r < 0x2000 {
  987. switch r {
  988. case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xa0, 0x1680:
  989. return true
  990. }
  991. } else {
  992. if r <= 0x200a {
  993. return true
  994. }
  995. switch r {
  996. case 0x2028, 0x2029, 0x202f, 0x205f, 0x3000:
  997. return true
  998. }
  999. }
  1000. return false
  1001. }
  1002. // returns true when the `r` rune is a nul byte
  1003. is_null :: proc(r: rune) -> bool {
  1004. return r == 0x0000
  1005. }
  1006. /*
  1007. runs trough the `s` string linearly and watches wether the `p` procedure matches the `truth` bool
  1008. returns the rune offset or -1 when no match was found
  1009. call :: proc(r: rune) -> bool {
  1010. return r == 'a'
  1011. }
  1012. strings.index_proc("abcabc", call) -> 0
  1013. strings.index_proc("cbacba", call) -> 2
  1014. strings.index_proc("cbacba", call, false) -> 0
  1015. strings.index_proc("abcabc", call, false) -> 1
  1016. strings.index_proc("xyz", call) -> -1
  1017. */
  1018. index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  1019. for r, i in s {
  1020. if p(r) == truth {
  1021. return i
  1022. }
  1023. }
  1024. return -1
  1025. }
  1026. // same as `index_proc` but with a `p` procedure taking a rawptr for state
  1027. index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  1028. for r, i in s {
  1029. if p(state, r) == truth {
  1030. return i
  1031. }
  1032. }
  1033. return -1
  1034. }
  1035. // same as `index_proc` but runs through the string in reverse
  1036. last_index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  1037. // TODO(bill): Probably use Rabin-Karp Search
  1038. for i := len(s); i > 0; {
  1039. r, size := utf8.decode_last_rune_in_string(s[:i])
  1040. i -= size
  1041. if p(r) == truth {
  1042. return i
  1043. }
  1044. }
  1045. return -1
  1046. }
  1047. // same as `index_proc_with_state` but runs through the string in reverse
  1048. last_index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  1049. // TODO(bill): Probably use Rabin-Karp Search
  1050. for i := len(s); i > 0; {
  1051. r, size := utf8.decode_last_rune_in_string(s[:i])
  1052. i -= size
  1053. if p(state, r) == truth {
  1054. return i
  1055. }
  1056. }
  1057. return -1
  1058. }
  1059. /*
  1060. trims the input string `s` until the procedure `p` returns false
  1061. does not allocate - only returns a cut variant of the input string
  1062. returns an empty string when no match was found at all
  1063. find :: proc(r: rune) -> bool {
  1064. return r != 'i'
  1065. }
  1066. strings.trim_left_proc("testing", find) -> "ing"
  1067. */
  1068. trim_left_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  1069. i := index_proc(s, p, false)
  1070. if i == -1 {
  1071. return ""
  1072. }
  1073. return s[i:]
  1074. }
  1075. /*
  1076. trims the input string `s` until the procedure `p` with state returns false
  1077. returns an empty string when no match was found at all
  1078. */
  1079. trim_left_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  1080. i := index_proc_with_state(s, p, state, false)
  1081. if i == -1 {
  1082. return ""
  1083. }
  1084. return s[i:]
  1085. }
  1086. /*
  1087. trims the input string `s` from the right until the procedure `p` returns false
  1088. does not allocate - only returns a cut variant of the input string
  1089. returns an empty string when no match was found at all
  1090. find :: proc(r: rune) -> bool {
  1091. return r != 't'
  1092. }
  1093. strings.trim_left_proc("testing", find) -> "test"
  1094. */
  1095. trim_right_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  1096. i := last_index_proc(s, p, false)
  1097. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  1098. _, w := utf8.decode_rune_in_string(s[i:])
  1099. i += w
  1100. } else {
  1101. i += 1
  1102. }
  1103. return s[0:i]
  1104. }
  1105. /*
  1106. trims the input string `s` from the right until the procedure `p` with state returns false
  1107. returns an empty string when no match was found at all
  1108. */
  1109. trim_right_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  1110. i := last_index_proc_with_state(s, p, state, false)
  1111. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  1112. _, w := utf8.decode_rune_in_string(s[i:])
  1113. i += w
  1114. } else {
  1115. i += 1
  1116. }
  1117. return s[0:i]
  1118. }
  1119. // procedure for `trim_*_proc` variants, which has a string rawptr cast + rune comparison
  1120. is_in_cutset :: proc(state: rawptr, r: rune) -> bool {
  1121. if state == nil {
  1122. return false
  1123. }
  1124. cutset := (^string)(state)^
  1125. for c in cutset {
  1126. if r == c {
  1127. return true
  1128. }
  1129. }
  1130. return false
  1131. }
  1132. // trims the `cutset` string from the `s` string
  1133. trim_left :: proc(s: string, cutset: string) -> string {
  1134. if s == "" || cutset == "" {
  1135. return s
  1136. }
  1137. state := cutset
  1138. return trim_left_proc_with_state(s, is_in_cutset, &state)
  1139. }
  1140. // trims the `cutset` string from the `s` string from the right
  1141. trim_right :: proc(s: string, cutset: string) -> string {
  1142. if s == "" || cutset == "" {
  1143. return s
  1144. }
  1145. state := cutset
  1146. return trim_right_proc_with_state(s, is_in_cutset, &state)
  1147. }
  1148. // trims the `cutset` string from the `s` string, both from left and right
  1149. trim :: proc(s: string, cutset: string) -> string {
  1150. return trim_right(trim_left(s, cutset), cutset)
  1151. }
  1152. // trims until a valid non space rune: "\t\txyz\t\t" -> "xyz\t\t"
  1153. trim_left_space :: proc(s: string) -> string {
  1154. return trim_left_proc(s, is_space)
  1155. }
  1156. // trims from the right until a valid non space rune: "\t\txyz\t\t" -> "\t\txyz"
  1157. trim_right_space :: proc(s: string) -> string {
  1158. return trim_right_proc(s, is_space)
  1159. }
  1160. // trims from both sides until a valid non space rune: "\t\txyz\t\t" -> "xyz"
  1161. trim_space :: proc(s: string) -> string {
  1162. return trim_right_space(trim_left_space(s))
  1163. }
  1164. // trims nul runes from the left: "\x00\x00testing\x00\x00" -> "testing\x00\x00"
  1165. trim_left_null :: proc(s: string) -> string {
  1166. return trim_left_proc(s, is_null)
  1167. }
  1168. // trims nul runes from the right: "\x00\x00testing\x00\x00" -> "\x00\x00testing"
  1169. trim_right_null :: proc(s: string) -> string {
  1170. return trim_right_proc(s, is_null)
  1171. }
  1172. // trims nul runes from both sides: "\x00\x00testing\x00\x00" -> "testing"
  1173. trim_null :: proc(s: string) -> string {
  1174. return trim_right_null(trim_left_null(s))
  1175. }
  1176. /*
  1177. trims a `prefix` string from the start of the `s` string and returns the trimmed string
  1178. returns the input string `s` when no prefix was found
  1179. strings.trim_prefix("testing", "test") -> "ing"
  1180. strings.trim_prefix("testing", "abc") -> "testing"
  1181. */
  1182. trim_prefix :: proc(s, prefix: string) -> string {
  1183. if has_prefix(s, prefix) {
  1184. return s[len(prefix):]
  1185. }
  1186. return s
  1187. }
  1188. /*
  1189. trims a `suffix` string from the end of the `s` string and returns the trimmed string
  1190. returns the input string `s` when no suffix was found
  1191. strings.trim_suffix("todo.txt", ".txt") -> "todo"
  1192. strings.trim_suffix("todo.doc", ".txt") -> "todo.doc"
  1193. */
  1194. trim_suffix :: proc(s, suffix: string) -> string {
  1195. if has_suffix(s, suffix) {
  1196. return s[:len(s)-len(suffix)]
  1197. }
  1198. return s
  1199. }
  1200. /*
  1201. splits the input string `s` by all possible `substrs` []string
  1202. returns the allocated []string, nil on any empty substring or no matches
  1203. splits := [?]string { "---", "~~~", ".", "_", "," }
  1204. res := strings.split_multi("testing,this.out_nice---done~~~last", splits[:])
  1205. fmt.eprintln(res) // -> [testing, this, out, nice, done, last]
  1206. */
  1207. split_multi :: proc(s: string, substrs: []string, allocator := context.allocator) -> (buf: []string) #no_bounds_check {
  1208. if s == "" || len(substrs) <= 0 {
  1209. return
  1210. }
  1211. // disallow "" substr
  1212. for substr in substrs {
  1213. if len(substr) == 0 {
  1214. return
  1215. }
  1216. }
  1217. // TODO maybe remove duplicate substrs
  1218. // sort substrings by string size, largest to smallest
  1219. temp_substrs := slice.clone(substrs, context.temp_allocator)
  1220. slice.sort_by(temp_substrs, proc(a, b: string) -> bool {
  1221. return len(a) > len(b)
  1222. })
  1223. substrings_found: int
  1224. temp := s
  1225. // count substr results found in string
  1226. first_pass: for len(temp) > 0 {
  1227. for substr in temp_substrs {
  1228. size := len(substr)
  1229. // check range and compare string to substr
  1230. if size <= len(temp) && temp[:size] == substr {
  1231. substrings_found += 1
  1232. temp = temp[size:]
  1233. continue first_pass
  1234. }
  1235. }
  1236. // step through string
  1237. _, skip := utf8.decode_rune_in_string(temp[:])
  1238. temp = temp[skip:]
  1239. }
  1240. // skip when no results
  1241. if substrings_found < 1 {
  1242. return
  1243. }
  1244. buf = make([]string, substrings_found + 1, allocator)
  1245. buf_index: int
  1246. temp = s
  1247. temp_old := temp
  1248. // gather results in the same fashion
  1249. second_pass: for len(temp) > 0 {
  1250. for substr in temp_substrs {
  1251. size := len(substr)
  1252. // check range and compare string to substr
  1253. if size <= len(temp) && temp[:size] == substr {
  1254. buf[buf_index] = temp_old[:len(temp_old) - len(temp)]
  1255. buf_index += 1
  1256. temp = temp[size:]
  1257. temp_old = temp
  1258. continue second_pass
  1259. }
  1260. }
  1261. // step through string
  1262. _, skip := utf8.decode_rune_in_string(temp[:])
  1263. temp = temp[skip:]
  1264. }
  1265. buf[buf_index] = temp_old[:]
  1266. return buf
  1267. }
  1268. // state for the split multi iterator
  1269. Split_Multi :: struct {
  1270. temp: string,
  1271. temp_old: string,
  1272. substrs: []string,
  1273. }
  1274. // returns split multi state with sorted `substrs`
  1275. split_multi_init :: proc(s: string, substrs: []string) -> Split_Multi {
  1276. // sort substrings, largest to smallest
  1277. temp_substrs := slice.clone(substrs, context.temp_allocator)
  1278. slice.sort_by(temp_substrs, proc(a, b: string) -> bool {
  1279. return len(a) > len(b)
  1280. })
  1281. return {
  1282. temp = s,
  1283. temp_old = s,
  1284. substrs = temp_substrs,
  1285. }
  1286. }
  1287. /*
  1288. splits the input string `s` by all possible `substrs` []string in an iterator fashion
  1289. returns the split string every iteration, the full string on no match
  1290. splits := [?]string { "---", "~~~", ".", "_", "," }
  1291. state := strings.split_multi_init("testing,this.out_nice---done~~~last", splits[:])
  1292. for str in strings.split_multi_iterate(&state) {
  1293. fmt.eprintln(str) // every iteration -> [testing, this, out, nice, done, last]
  1294. }
  1295. */
  1296. split_multi_iterate :: proc(using sm: ^Split_Multi) -> (res: string, ok: bool) #no_bounds_check {
  1297. pass: for len(temp) > 0 {
  1298. for substr in substrs {
  1299. size := len(substr)
  1300. // check range and compare string to substr
  1301. if size <= len(temp) && temp[:size] == substr {
  1302. res = temp_old[:len(temp_old) - len(temp)]
  1303. temp = temp[size:]
  1304. temp_old = temp
  1305. ok = true
  1306. return
  1307. }
  1308. }
  1309. // step through string
  1310. _, skip := utf8.decode_rune_in_string(temp[:])
  1311. temp = temp[skip:]
  1312. }
  1313. // allow last iteration
  1314. if temp_old != "" {
  1315. res = temp_old[:]
  1316. ok = true
  1317. temp_old = ""
  1318. }
  1319. return
  1320. }
  1321. // scrub scruvs invalid utf-8 characters and replaces them with the replacement string
  1322. // Adjacent invalid bytes are only replaced once
  1323. scrub :: proc(s: string, replacement: string, allocator := context.allocator) -> string {
  1324. str := s
  1325. b: Builder
  1326. init_builder(&b, 0, len(s), allocator)
  1327. has_error := false
  1328. cursor := 0
  1329. origin := str
  1330. for len(str) > 0 {
  1331. r, w := utf8.decode_rune_in_string(str)
  1332. if r == utf8.RUNE_ERROR {
  1333. if !has_error {
  1334. has_error = true
  1335. write_string(&b, origin[:cursor])
  1336. }
  1337. } else if has_error {
  1338. has_error = false
  1339. write_string(&b, replacement)
  1340. origin = origin[cursor:]
  1341. cursor = 0
  1342. }
  1343. cursor += w
  1344. str = str[w:]
  1345. }
  1346. return to_string(b)
  1347. }
  1348. /*
  1349. returns a reversed version of the `s` string
  1350. a := "abcxyz"
  1351. b := strings.reverse(a)
  1352. fmt.eprintln(a, b) // abcxyz zyxcba
  1353. */
  1354. reverse :: proc(s: string, allocator := context.allocator) -> string {
  1355. str := s
  1356. n := len(str)
  1357. buf := make([]byte, n)
  1358. i := n
  1359. for len(str) > 0 {
  1360. _, w := utf8.decode_rune_in_string(str)
  1361. i -= w
  1362. copy(buf[i:], str[:w])
  1363. str = str[w:]
  1364. }
  1365. return string(buf)
  1366. }
  1367. /*
  1368. expands the string to a grid spaced by `tab_size` whenever a `\t` character appears
  1369. returns the tabbed string, panics on tab_size <= 0
  1370. strings.expand_tabs("abc1\tabc2\tabc3", 4) -> abc1 abc2 abc3
  1371. strings.expand_tabs("abc1\tabc2\tabc3", 5) -> abc1 abc2 abc3
  1372. strings.expand_tabs("abc1\tabc2\tabc3", 6) -> abc1 abc2 abc3
  1373. */
  1374. expand_tabs :: proc(s: string, tab_size: int, allocator := context.allocator) -> string {
  1375. if tab_size <= 0 {
  1376. panic("tab size must be positive")
  1377. }
  1378. if s == "" {
  1379. return ""
  1380. }
  1381. b: Builder
  1382. init_builder(&b, allocator)
  1383. writer := to_writer(&b)
  1384. str := s
  1385. column: int
  1386. for len(str) > 0 {
  1387. r, w := utf8.decode_rune_in_string(str)
  1388. if r == '\t' {
  1389. expand := tab_size - column%tab_size
  1390. for i := 0; i < expand; i += 1 {
  1391. io.write_byte(writer, ' ')
  1392. }
  1393. column += expand
  1394. } else {
  1395. if r == '\n' {
  1396. column = 0
  1397. } else {
  1398. column += w
  1399. }
  1400. io.write_rune(writer, r)
  1401. }
  1402. str = str[w:]
  1403. }
  1404. return to_string(b)
  1405. }
  1406. /*
  1407. splits the `str` string by the seperator `sep` string and returns 3 parts
  1408. `head`: before the split, `match`: the seperator, `tail`: the end of the split
  1409. returns the input string when the `sep` was not found
  1410. text := "testing this out"
  1411. strings.partition(text, " this ") -> head: "testing", match: " this ", tail: "out"
  1412. strings.partition(text, "hi") -> head: "testing t", match: "hi", tail: "s out"
  1413. strings.partition(text, "xyz") -> head: "testing this out", match: "", tail: ""
  1414. */
  1415. partition :: proc(str, sep: string) -> (head, match, tail: string) {
  1416. i := index(str, sep)
  1417. if i == -1 {
  1418. head = str
  1419. return
  1420. }
  1421. head = str[:i]
  1422. match = str[i:i+len(sep)]
  1423. tail = str[i+len(sep):]
  1424. return
  1425. }
  1426. center_justify :: centre_justify // NOTE(bill): Because Americans exist
  1427. // centre_justify returns a string with a pad string at boths sides if the str's rune length is smaller than length
  1428. centre_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  1429. n := rune_count(str)
  1430. if n >= length || pad == "" {
  1431. return clone(str, allocator)
  1432. }
  1433. remains := length-1
  1434. pad_len := rune_count(pad)
  1435. b: Builder
  1436. init_builder(&b, allocator)
  1437. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  1438. w := to_writer(&b)
  1439. write_pad_string(w, pad, pad_len, remains/2)
  1440. io.write_string(w, str)
  1441. write_pad_string(w, pad, pad_len, (remains+1)/2)
  1442. return to_string(b)
  1443. }
  1444. // left_justify returns a string with a pad string at left side if the str's rune length is smaller than length
  1445. left_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  1446. n := rune_count(str)
  1447. if n >= length || pad == "" {
  1448. return clone(str, allocator)
  1449. }
  1450. remains := length-1
  1451. pad_len := rune_count(pad)
  1452. b: Builder
  1453. init_builder(&b, allocator)
  1454. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  1455. w := to_writer(&b)
  1456. io.write_string(w, str)
  1457. write_pad_string(w, pad, pad_len, remains)
  1458. return to_string(b)
  1459. }
  1460. // right_justify returns a string with a pad string at right side if the str's rune length is smaller than length
  1461. right_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  1462. n := rune_count(str)
  1463. if n >= length || pad == "" {
  1464. return clone(str, allocator)
  1465. }
  1466. remains := length-1
  1467. pad_len := rune_count(pad)
  1468. b: Builder
  1469. init_builder(&b, allocator)
  1470. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  1471. w := to_writer(&b)
  1472. write_pad_string(w, pad, pad_len, remains)
  1473. io.write_string(w, str)
  1474. return to_string(b)
  1475. }
  1476. @private
  1477. write_pad_string :: proc(w: io.Writer, pad: string, pad_len, remains: int) {
  1478. repeats := remains / pad_len
  1479. for i := 0; i < repeats; i += 1 {
  1480. io.write_string(w, pad)
  1481. }
  1482. n := remains % pad_len
  1483. p := pad
  1484. for i := 0; i < n; i += 1 {
  1485. r, width := utf8.decode_rune_in_string(p)
  1486. io.write_rune(w, r)
  1487. p = p[width:]
  1488. }
  1489. }
  1490. // fields splits the string s around each instance of one or more consecutive white space character, defined by unicode.is_space
  1491. // returning a slice of substrings of s or an empty slice if s only contains white space
  1492. fields :: proc(s: string, allocator := context.allocator) -> []string #no_bounds_check {
  1493. n := 0
  1494. was_space := 1
  1495. set_bits := u8(0)
  1496. // check to see
  1497. for i in 0..<len(s) {
  1498. r := s[i]
  1499. set_bits |= r
  1500. is_space := int(_ascii_space[r])
  1501. n += was_space & ~is_space
  1502. was_space = is_space
  1503. }
  1504. if set_bits >= utf8.RUNE_SELF {
  1505. return fields_proc(s, unicode.is_space, allocator)
  1506. }
  1507. if n == 0 {
  1508. return nil
  1509. }
  1510. a := make([]string, n, allocator)
  1511. na := 0
  1512. field_start := 0
  1513. i := 0
  1514. for i < len(s) && _ascii_space[s[i]] {
  1515. i += 1
  1516. }
  1517. field_start = i
  1518. for i < len(s) {
  1519. if !_ascii_space[s[i]] {
  1520. i += 1
  1521. continue
  1522. }
  1523. a[na] = s[field_start : i]
  1524. na += 1
  1525. i += 1
  1526. for i < len(s) && _ascii_space[s[i]] {
  1527. i += 1
  1528. }
  1529. field_start = i
  1530. }
  1531. if field_start < len(s) {
  1532. a[na] = s[field_start:]
  1533. }
  1534. return a
  1535. }
  1536. // fields_proc splits the string s at each run of unicode code points `ch` satisfying f(ch)
  1537. // returns a slice of substrings of s
  1538. // If all code points in s satisfy f(ch) or string is empty, an empty slice is returned
  1539. //
  1540. // fields_proc makes no guarantee about the order in which it calls f(ch)
  1541. // it assumes that `f` always returns the same value for a given ch
  1542. fields_proc :: proc(s: string, f: proc(rune) -> bool, allocator := context.allocator) -> []string #no_bounds_check {
  1543. substrings := make([dynamic]string, 0, 32, allocator)
  1544. start, end := -1, -1
  1545. for r, offset in s {
  1546. end = offset
  1547. if f(r) {
  1548. if start >= 0 {
  1549. append(&substrings, s[start : end])
  1550. // -1 could be used, but just speed it up through bitwise not
  1551. // gotta love 2's complement
  1552. start = ~start
  1553. }
  1554. } else {
  1555. if start < 0 {
  1556. start = end
  1557. }
  1558. }
  1559. }
  1560. if start >= 0 {
  1561. append(&substrings, s[start : len(s)])
  1562. }
  1563. return substrings[:]
  1564. }
  1565. // `fields_iterator` returns the first run of characters in `s` that does not contain white space, defined by `unicode.is_space`
  1566. // `s` will then start from any space after the substring, or be an empty string if the substring was the remaining characters
  1567. fields_iterator :: proc(s: ^string) -> (field: string, ok: bool) {
  1568. start, end := -1, -1
  1569. for r, offset in s {
  1570. end = offset
  1571. if unicode.is_space(r) {
  1572. if start >= 0 {
  1573. field = s[start : end]
  1574. ok = true
  1575. s^ = s[end:]
  1576. return
  1577. }
  1578. } else {
  1579. if start < 0 {
  1580. start = end
  1581. }
  1582. }
  1583. }
  1584. // if either of these are true, the string did not contain any characters
  1585. if end < 0 || start < 0 {
  1586. return "", false
  1587. }
  1588. field = s[start:]
  1589. ok = true
  1590. s^ = s[len(s):]
  1591. return
  1592. }
  1593. // `levenshtein_distance` returns the Levenshtein edit distance between 2 strings.
  1594. // This is a single-row-version of the Wagner–Fischer algorithm, based on C code by Martin Ettl.
  1595. // Note: allocator isn't used if the length of string b in runes is smaller than 64.
  1596. levenshtein_distance :: proc(a, b: string, allocator := context.allocator) -> int {
  1597. LEVENSHTEIN_DEFAULT_COSTS: []int : {
  1598. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  1599. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
  1600. 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  1601. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
  1602. 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
  1603. 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  1604. 60, 61, 62, 63,
  1605. }
  1606. m, n := utf8.rune_count_in_string(a), utf8.rune_count_in_string(b)
  1607. if m == 0 {
  1608. return n
  1609. }
  1610. if n == 0 {
  1611. return m
  1612. }
  1613. costs: []int
  1614. if n + 1 > len(LEVENSHTEIN_DEFAULT_COSTS) {
  1615. costs = make([]int, n + 1, allocator)
  1616. for k in 0..=n {
  1617. costs[k] = k
  1618. }
  1619. } else {
  1620. costs = LEVENSHTEIN_DEFAULT_COSTS
  1621. }
  1622. defer if n + 1 > len(LEVENSHTEIN_DEFAULT_COSTS) {
  1623. delete(costs, allocator)
  1624. }
  1625. i: int
  1626. for c1 in a {
  1627. costs[0] = i + 1
  1628. corner := i
  1629. j: int
  1630. for c2 in b {
  1631. upper := costs[j + 1]
  1632. if c1 == c2 {
  1633. costs[j + 1] = corner
  1634. } else {
  1635. t := upper if upper < corner else corner
  1636. costs[j + 1] = (costs[j] if costs[j] < t else t) + 1
  1637. }
  1638. corner = upper
  1639. j += 1
  1640. }
  1641. i += 1
  1642. }
  1643. return costs[n]
  1644. }