strings.odin 44 KB

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