strings.odin 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. package strings
  2. import "core:io"
  3. import "core:mem"
  4. import "core:unicode"
  5. import "core:unicode/utf8"
  6. clone :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> string {
  7. c := make([]byte, len(s)+1, allocator, loc)
  8. copy(c, s)
  9. c[len(s)] = 0
  10. return string(c[:len(s)])
  11. }
  12. clone_to_cstring :: proc(s: string, allocator := context.allocator, loc := #caller_location) -> cstring {
  13. c := make([]byte, len(s)+1, allocator, loc)
  14. copy(c, s)
  15. c[len(s)] = 0
  16. return cstring(&c[0])
  17. }
  18. string_from_ptr :: proc(ptr: ^byte, len: int) -> string {
  19. return transmute(string)mem.Raw_String{ptr, len}
  20. }
  21. string_from_nul_terminated_ptr :: proc(ptr: ^byte, len: int) -> string {
  22. s := transmute(string)mem.Raw_String{ptr, len}
  23. s = truncate_to_byte(s, 0)
  24. return s
  25. }
  26. ptr_from_string :: proc(str: string) -> ^byte {
  27. d := transmute(mem.Raw_String)str
  28. return d.data
  29. }
  30. unsafe_string_to_cstring :: proc(str: string) -> cstring {
  31. d := transmute(mem.Raw_String)str
  32. return cstring(d.data)
  33. }
  34. truncate_to_byte :: proc(str: string, b: byte) -> string {
  35. n := index_byte(str, b)
  36. if n < 0 {
  37. n = len(str)
  38. }
  39. return str[:n]
  40. }
  41. truncate_to_rune :: proc(str: string, r: rune) -> string {
  42. n := index_rune(str, r)
  43. if n < 0 {
  44. n = len(str)
  45. }
  46. return str[:n]
  47. }
  48. clone_from_bytes :: proc(s: []byte, allocator := context.allocator, loc := #caller_location) -> string {
  49. c := make([]byte, len(s)+1, allocator, loc)
  50. copy(c, s)
  51. c[len(s)] = 0
  52. return string(c[:len(s)])
  53. }
  54. clone_from_cstring :: proc(s: cstring, allocator := context.allocator, loc := #caller_location) -> string {
  55. return clone(string(s), allocator, loc)
  56. }
  57. clone_from_ptr :: proc(ptr: ^byte, len: int, allocator := context.allocator, loc := #caller_location) -> string {
  58. s := string_from_ptr(ptr, len)
  59. return clone(s, allocator, loc)
  60. }
  61. clone_from :: proc{
  62. clone,
  63. clone_from_bytes,
  64. clone_from_cstring,
  65. clone_from_ptr,
  66. }
  67. clone_from_cstring_bounded :: proc(ptr: cstring, len: int, allocator := context.allocator, loc := #caller_location) -> string {
  68. s := string_from_ptr((^u8)(ptr), len)
  69. s = truncate_to_byte(s, 0)
  70. return clone(s, allocator, loc)
  71. }
  72. // Compares two strings, returning a value representing which one comes first lexiographically.
  73. // -1 for `a`; 1 for `b`, or 0 if they are equal.
  74. compare :: proc(lhs, rhs: string) -> int {
  75. return mem.compare(transmute([]byte)lhs, transmute([]byte)rhs)
  76. }
  77. contains_rune :: proc(s: string, r: rune) -> int {
  78. for c, offset in s {
  79. if c == r {
  80. return offset
  81. }
  82. }
  83. return -1
  84. }
  85. contains :: proc(s, substr: string) -> bool {
  86. return index(s, substr) >= 0
  87. }
  88. contains_any :: proc(s, chars: string) -> bool {
  89. return index_any(s, chars) >= 0
  90. }
  91. rune_count :: proc(s: string) -> int {
  92. return utf8.rune_count_in_string(s)
  93. }
  94. equal_fold :: proc(u, v: string) -> bool {
  95. s, t := u, v
  96. loop: for s != "" && t != "" {
  97. sr, tr: rune
  98. if s[0] < utf8.RUNE_SELF {
  99. sr, s = rune(s[0]), s[1:]
  100. } else {
  101. r, size := utf8.decode_rune_in_string(s)
  102. sr, s = r, s[size:]
  103. }
  104. if t[0] < utf8.RUNE_SELF {
  105. tr, t = rune(t[0]), t[1:]
  106. } else {
  107. r, size := utf8.decode_rune_in_string(t)
  108. tr, t = r, t[size:]
  109. }
  110. if tr == sr { // easy case
  111. continue loop
  112. }
  113. if tr < sr {
  114. tr, sr = sr, tr
  115. }
  116. if tr < utf8.RUNE_SELF {
  117. switch sr {
  118. case 'A'..='Z':
  119. if tr == (sr+'a')-'A' {
  120. continue loop
  121. }
  122. }
  123. return false
  124. }
  125. // TODO(bill): Unicode folding
  126. return false
  127. }
  128. return s == t
  129. }
  130. has_prefix :: proc(s, prefix: string) -> bool {
  131. return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
  132. }
  133. has_suffix :: proc(s, suffix: string) -> bool {
  134. return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
  135. }
  136. join :: proc(a: []string, sep: string, allocator := context.allocator) -> string {
  137. if len(a) == 0 {
  138. return ""
  139. }
  140. n := len(sep) * (len(a) - 1)
  141. for s in a {
  142. n += len(s)
  143. }
  144. b := make([]byte, n, allocator)
  145. i := copy(b, a[0])
  146. for s in a[1:] {
  147. i += copy(b[i:], sep)
  148. i += copy(b[i:], s)
  149. }
  150. return string(b)
  151. }
  152. concatenate :: proc(a: []string, allocator := context.allocator) -> string {
  153. if len(a) == 0 {
  154. return ""
  155. }
  156. n := 0
  157. for s in a {
  158. n += len(s)
  159. }
  160. b := make([]byte, n, allocator)
  161. i := 0
  162. for s in a {
  163. i += copy(b[i:], s)
  164. }
  165. return string(b)
  166. }
  167. /*
  168. `rune_offset` and `rune_length` are in runes, not bytes.
  169. If `rune_length` <= 0, then it'll return the remainder of the string starting with `rune_offset`.
  170. */
  171. cut :: proc(s: string, rune_offset := int(0), rune_length := int(0), allocator := context.allocator) -> (res: string) {
  172. s := s; rune_length := rune_length
  173. l := utf8.rune_count_in_string(s)
  174. if rune_offset >= l { return "" }
  175. if rune_offset == 0 && rune_length <= 0 {
  176. return clone(s, allocator)
  177. }
  178. if rune_length == 0 { rune_length = l }
  179. bytes_needed := min(rune_length * 4, len(s))
  180. buf := make([]u8, bytes_needed, allocator)
  181. byte_offset := 0
  182. for i := 0; i < l; i += 1 {
  183. _, w := utf8.decode_rune_in_string(s)
  184. if i >= rune_offset {
  185. for j := 0; j < w; j += 1 {
  186. buf[byte_offset+j] = s[j]
  187. }
  188. byte_offset += w
  189. }
  190. if rune_length > 0 {
  191. if i == rune_offset + rune_length - 1 { break }
  192. }
  193. s = s[w:]
  194. }
  195. return string(buf[:byte_offset])
  196. }
  197. @private
  198. _split :: proc(s_, sep: string, sep_save, n_: int, allocator := context.allocator) -> []string {
  199. s, n := s_, n_
  200. if n == 0 {
  201. return nil
  202. }
  203. if sep == "" {
  204. l := utf8.rune_count_in_string(s)
  205. if n < 0 || n > l {
  206. n = l
  207. }
  208. res := make([dynamic]string, n, allocator)
  209. for i := 0; i < n-1; i += 1 {
  210. _, w := utf8.decode_rune_in_string(s)
  211. res[i] = s[:w]
  212. s = s[w:]
  213. }
  214. if n > 0 {
  215. res[n-1] = s
  216. }
  217. return res[:]
  218. }
  219. if n < 0 {
  220. n = count(s, sep) + 1
  221. }
  222. res := make([dynamic]string, n, allocator)
  223. n -= 1
  224. i := 0
  225. for ; i < n; i += 1 {
  226. m := index(s, sep)
  227. if m < 0 {
  228. break
  229. }
  230. res[i] = s[:m+sep_save]
  231. s = s[m+len(sep):]
  232. }
  233. res[i] = s
  234. return res[:i+1]
  235. }
  236. split :: proc(s, sep: string, allocator := context.allocator) -> []string {
  237. return _split(s, sep, 0, -1, allocator)
  238. }
  239. split_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  240. return _split(s, sep, 0, n, allocator)
  241. }
  242. split_after :: proc(s, sep: string, allocator := context.allocator) -> []string {
  243. return _split(s, sep, len(sep), -1, allocator)
  244. }
  245. split_after_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  246. return _split(s, sep, len(sep), n, allocator)
  247. }
  248. @private
  249. _split_iterator :: proc(s: ^string, sep: string, sep_save, n: int) -> (res: string, ok: bool) {
  250. s, n := s, n
  251. if n == 0 {
  252. return
  253. }
  254. if sep == "" {
  255. res = s[:]
  256. ok = true
  257. s^ = s[len(s):]
  258. return
  259. }
  260. if n < 0 {
  261. n = count(s^, sep) + 1
  262. }
  263. n -= 1
  264. i := 0
  265. for ; i < n; i += 1 {
  266. m := index(s^, sep)
  267. if m < 0 {
  268. break
  269. }
  270. res = s[:m+sep_save]
  271. ok = true
  272. s^ = s[m+len(sep):]
  273. return
  274. }
  275. res = s[:]
  276. ok = res != ""
  277. s^ = s[len(s):]
  278. return
  279. }
  280. split_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  281. return _split_iterator(s, sep, 0, -1)
  282. }
  283. split_n_iterator :: proc(s: ^string, sep: string, n: int) -> (string, bool) {
  284. return _split_iterator(s, sep, 0, n)
  285. }
  286. split_after_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  287. return _split_iterator(s, sep, len(sep), -1)
  288. }
  289. split_after_n_iterator :: proc(s: ^string, sep: string, n: int) -> (string, bool) {
  290. return _split_iterator(s, sep, len(sep), n)
  291. }
  292. index_byte :: proc(s: string, c: byte) -> int {
  293. for i := 0; i < len(s); i += 1 {
  294. if s[i] == c {
  295. return i
  296. }
  297. }
  298. return -1
  299. }
  300. // Returns -1 if c is not present
  301. last_index_byte :: proc(s: string, c: byte) -> int {
  302. for i := len(s)-1; i >= 0; i -= 1 {
  303. if s[i] == c {
  304. return i
  305. }
  306. }
  307. return -1
  308. }
  309. @private PRIME_RABIN_KARP :: 16777619
  310. index :: proc(s, substr: string) -> int {
  311. hash_str_rabin_karp :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  312. for i := 0; i < len(s); i += 1 {
  313. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  314. }
  315. sq := u32(PRIME_RABIN_KARP)
  316. for i := len(s); i > 0; i >>= 1 {
  317. if (i & 1) != 0 {
  318. pow *= sq
  319. }
  320. sq *= sq
  321. }
  322. return
  323. }
  324. n := len(substr)
  325. switch {
  326. case n == 0:
  327. return 0
  328. case n == 1:
  329. return index_byte(s, substr[0])
  330. case n == len(s):
  331. if s == substr {
  332. return 0
  333. }
  334. return -1
  335. case n > len(s):
  336. return -1
  337. }
  338. hash, pow := hash_str_rabin_karp(substr)
  339. h: u32
  340. for i := 0; i < n; i += 1 {
  341. h = h*PRIME_RABIN_KARP + u32(s[i])
  342. }
  343. if h == hash && s[:n] == substr {
  344. return 0
  345. }
  346. for i := n; i < len(s); /**/ {
  347. h *= PRIME_RABIN_KARP
  348. h += u32(s[i])
  349. h -= pow * u32(s[i-n])
  350. i += 1
  351. if h == hash && s[i-n:i] == substr {
  352. return i - n
  353. }
  354. }
  355. return -1
  356. }
  357. last_index :: proc(s, substr: string) -> int {
  358. hash_str_rabin_karp_reverse :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  359. for i := len(s) - 1; i >= 0; i -= 1 {
  360. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  361. }
  362. sq := u32(PRIME_RABIN_KARP)
  363. for i := len(s); i > 0; i >>= 1 {
  364. if (i & 1) != 0 {
  365. pow *= sq
  366. }
  367. sq *= sq
  368. }
  369. return
  370. }
  371. n := len(substr)
  372. switch {
  373. case n == 0:
  374. return len(s)
  375. case n == 1:
  376. return last_index_byte(s, substr[0])
  377. case n == len(s):
  378. return 0 if substr == s else -1
  379. case n > len(s):
  380. return -1
  381. }
  382. hash, pow := hash_str_rabin_karp_reverse(substr)
  383. last := len(s) - n
  384. h: u32
  385. for i := len(s)-1; i >= last; i -= 1 {
  386. h = h*PRIME_RABIN_KARP + u32(s[i])
  387. }
  388. if h == hash && s[last:] == substr {
  389. return last
  390. }
  391. for i := last-1; i >= 0; i -= 1 {
  392. h *= PRIME_RABIN_KARP
  393. h += u32(s[i])
  394. h -= pow * u32(s[i+n])
  395. if h == hash && s[i:i+n] == substr {
  396. return i
  397. }
  398. }
  399. return -1
  400. }
  401. // index_any returns the index of the first char of `chars` found in `s`. -1 if not found.
  402. index_any :: proc(s, chars: string) -> int {
  403. if chars == "" {
  404. return -1
  405. }
  406. if len(chars) == 1 {
  407. r := rune(chars[0])
  408. if r >= utf8.RUNE_SELF {
  409. r = utf8.RUNE_ERROR
  410. }
  411. return index_rune(s, r)
  412. }
  413. if len(s) > 8 {
  414. if as, ok := ascii_set_make(chars); ok {
  415. for i in 0..<len(s) {
  416. if ascii_set_contains(as, s[i]) {
  417. return i
  418. }
  419. }
  420. return -1
  421. }
  422. }
  423. for c in chars {
  424. if i := index_rune(s, c); i >= 0 {
  425. return i
  426. }
  427. }
  428. return -1
  429. }
  430. last_index_any :: proc(s, chars: string) -> int {
  431. if chars == "" {
  432. return -1
  433. }
  434. if len(s) == 1 {
  435. r := rune(s[0])
  436. if r >= utf8.RUNE_SELF {
  437. r = utf8.RUNE_ERROR
  438. }
  439. return index_rune(chars, r)
  440. }
  441. if len(s) > 8 {
  442. if as, ok := ascii_set_make(chars); ok {
  443. for i := len(s)-1; i >= 0; i -= 1 {
  444. if ascii_set_contains(as, s[i]) {
  445. return i
  446. }
  447. }
  448. return -1
  449. }
  450. }
  451. if len(chars) == 1 {
  452. r := rune(chars[0])
  453. if r >= utf8.RUNE_SELF {
  454. r = utf8.RUNE_ERROR
  455. }
  456. for i := len(s); i > 0; /**/ {
  457. c, w := utf8.decode_last_rune_in_string(s[:i])
  458. i -= w
  459. if c == r {
  460. return i
  461. }
  462. }
  463. return -1
  464. }
  465. for i := len(s); i > 0; /**/ {
  466. r, w := utf8.decode_last_rune_in_string(s[:i])
  467. i -= w
  468. if index_rune(chars, r) >= 0 {
  469. return i
  470. }
  471. }
  472. return -1
  473. }
  474. count :: proc(s, substr: string) -> int {
  475. if len(substr) == 0 { // special case
  476. return rune_count(s) + 1
  477. }
  478. if len(substr) == 1 {
  479. c := substr[0]
  480. switch len(s) {
  481. case 0:
  482. return 0
  483. case 1:
  484. return int(s[0] == c)
  485. }
  486. n := 0
  487. for i := 0; i < len(s); i += 1 {
  488. if s[i] == c {
  489. n += 1
  490. }
  491. }
  492. return n
  493. }
  494. // TODO(bill): Use a non-brute for approach
  495. n := 0
  496. str := s
  497. for {
  498. i := index(str, substr)
  499. if i == -1 {
  500. return n
  501. }
  502. n += 1
  503. str = str[i+len(substr):]
  504. }
  505. return n
  506. }
  507. repeat :: proc(s: string, count: int, allocator := context.allocator) -> string {
  508. if count < 0 {
  509. panic("strings: negative repeat count")
  510. } else if count > 0 && (len(s)*count)/count != len(s) {
  511. panic("strings: repeat count will cause an overflow")
  512. }
  513. b := make([]byte, len(s)*count, allocator)
  514. i := copy(b, s)
  515. for i < len(b) { // 2^N trick to reduce the need to copy
  516. copy(b[i:], b[:i])
  517. i *= 2
  518. }
  519. return string(b)
  520. }
  521. replace_all :: proc(s, old, new: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  522. return replace(s, old, new, -1, allocator)
  523. }
  524. // if n < 0, no limit on the number of replacements
  525. replace :: proc(s, old, new: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  526. if old == new || n == 0 {
  527. was_allocation = false
  528. output = s
  529. return
  530. }
  531. byte_count := n
  532. if m := count(s, old); m == 0 {
  533. was_allocation = false
  534. output = s
  535. return
  536. } else if n < 0 || m < n {
  537. byte_count = m
  538. }
  539. t := make([]byte, len(s) + byte_count*(len(new) - len(old)), allocator)
  540. was_allocation = true
  541. w := 0
  542. start := 0
  543. for i := 0; i < byte_count; i += 1 {
  544. j := start
  545. if len(old) == 0 {
  546. if i > 0 {
  547. _, width := utf8.decode_rune_in_string(s[start:])
  548. j += width
  549. }
  550. } else {
  551. j += index(s[start:], old)
  552. }
  553. w += copy(t[w:], s[start:j])
  554. w += copy(t[w:], new)
  555. start = j + len(old)
  556. }
  557. w += copy(t[w:], s[start:])
  558. output = string(t[0:w])
  559. return
  560. }
  561. remove :: proc(s, key: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  562. return replace(s, key, "", n, allocator)
  563. }
  564. remove_all :: proc(s, key: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  565. return remove(s, key, -1, allocator)
  566. }
  567. @(private) _ascii_space := [256]bool{'\t' = true, '\n' = true, '\v' = true, '\f' = true, '\r' = true, ' ' = true}
  568. is_ascii_space :: proc(r: rune) -> bool {
  569. if r < utf8.RUNE_SELF {
  570. return _ascii_space[u8(r)]
  571. }
  572. return false
  573. }
  574. is_space :: proc(r: rune) -> bool {
  575. if r < 0x2000 {
  576. switch r {
  577. case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xa0, 0x1680:
  578. return true
  579. }
  580. } else {
  581. if r <= 0x200a {
  582. return true
  583. }
  584. switch r {
  585. case 0x2028, 0x2029, 0x202f, 0x205f, 0x3000:
  586. return true
  587. }
  588. }
  589. return false
  590. }
  591. is_null :: proc(r: rune) -> bool {
  592. return r == 0x0000
  593. }
  594. index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  595. for r, i in s {
  596. if p(r) == truth {
  597. return i
  598. }
  599. }
  600. return -1
  601. }
  602. index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  603. for r, i in s {
  604. if p(state, r) == truth {
  605. return i
  606. }
  607. }
  608. return -1
  609. }
  610. last_index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  611. // TODO(bill): Probably use Rabin-Karp Search
  612. for i := len(s); i > 0; {
  613. r, size := utf8.decode_last_rune_in_string(s[:i])
  614. i -= size
  615. if p(r) == truth {
  616. return i
  617. }
  618. }
  619. return -1
  620. }
  621. last_index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  622. // TODO(bill): Probably use Rabin-Karp Search
  623. for i := len(s); i > 0; {
  624. r, size := utf8.decode_last_rune_in_string(s[:i])
  625. i -= size
  626. if p(state, r) == truth {
  627. return i
  628. }
  629. }
  630. return -1
  631. }
  632. trim_left_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  633. i := index_proc(s, p, false)
  634. if i == -1 {
  635. return ""
  636. }
  637. return s[i:]
  638. }
  639. index_rune :: proc(s: string, r: rune) -> int {
  640. switch {
  641. case 0 <= r && r < utf8.RUNE_SELF:
  642. return index_byte(s, byte(r))
  643. case r == utf8.RUNE_ERROR:
  644. for c, i in s {
  645. if c == utf8.RUNE_ERROR {
  646. return i
  647. }
  648. }
  649. return -1
  650. case !utf8.valid_rune(r):
  651. return -1
  652. }
  653. b, w := utf8.encode_rune(r)
  654. return index(s, string(b[:w]))
  655. }
  656. trim_left_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  657. i := index_proc_with_state(s, p, state, false)
  658. if i == -1 {
  659. return ""
  660. }
  661. return s[i:]
  662. }
  663. trim_right_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  664. i := last_index_proc(s, p, false)
  665. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  666. _, w := utf8.decode_rune_in_string(s[i:])
  667. i += w
  668. } else {
  669. i += 1
  670. }
  671. return s[0:i]
  672. }
  673. trim_right_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  674. i := last_index_proc_with_state(s, p, state, false)
  675. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  676. _, w := utf8.decode_rune_in_string(s[i:])
  677. i += w
  678. } else {
  679. i += 1
  680. }
  681. return s[0:i]
  682. }
  683. is_in_cutset :: proc(state: rawptr, r: rune) -> bool {
  684. if state == nil {
  685. return false
  686. }
  687. cutset := (^string)(state)^
  688. for c in cutset {
  689. if r == c {
  690. return true
  691. }
  692. }
  693. return false
  694. }
  695. trim_left :: proc(s: string, cutset: string) -> string {
  696. if s == "" || cutset == "" {
  697. return s
  698. }
  699. state := cutset
  700. return trim_left_proc_with_state(s, is_in_cutset, &state)
  701. }
  702. trim_right :: proc(s: string, cutset: string) -> string {
  703. if s == "" || cutset == "" {
  704. return s
  705. }
  706. state := cutset
  707. return trim_right_proc_with_state(s, is_in_cutset, &state)
  708. }
  709. trim :: proc(s: string, cutset: string) -> string {
  710. return trim_right(trim_left(s, cutset), cutset)
  711. }
  712. trim_left_space :: proc(s: string) -> string {
  713. return trim_left_proc(s, is_space)
  714. }
  715. trim_right_space :: proc(s: string) -> string {
  716. return trim_right_proc(s, is_space)
  717. }
  718. trim_space :: proc(s: string) -> string {
  719. return trim_right_space(trim_left_space(s))
  720. }
  721. trim_left_null :: proc(s: string) -> string {
  722. return trim_left_proc(s, is_null)
  723. }
  724. trim_right_null :: proc(s: string) -> string {
  725. return trim_right_proc(s, is_null)
  726. }
  727. trim_null :: proc(s: string) -> string {
  728. return trim_right_null(trim_left_null(s))
  729. }
  730. trim_prefix :: proc(s, prefix: string) -> string {
  731. if has_prefix(s, prefix) {
  732. return s[len(prefix):]
  733. }
  734. return s
  735. }
  736. trim_suffix :: proc(s, suffix: string) -> string {
  737. if has_suffix(s, suffix) {
  738. return s[:len(s)-len(suffix)]
  739. }
  740. return s
  741. }
  742. split_multi :: proc(s: string, substrs: []string, skip_empty := false, allocator := context.allocator) -> []string #no_bounds_check {
  743. if s == "" || len(substrs) <= 0 {
  744. return nil
  745. }
  746. sublen := len(substrs[0])
  747. for substr in substrs[1:] {
  748. sublen = min(sublen, len(substr))
  749. }
  750. shared := len(s) - sublen
  751. if shared <= 0 {
  752. return nil
  753. }
  754. // number, index, last
  755. n, i, l := 0, 0, 0
  756. // count results
  757. first_pass: for i <= shared {
  758. for substr in substrs {
  759. if s[i:i+sublen] == substr {
  760. if !skip_empty || i - l > 0 {
  761. n += 1
  762. }
  763. i += sublen
  764. l = i
  765. continue first_pass
  766. }
  767. }
  768. _, skip := utf8.decode_rune_in_string(s[i:])
  769. i += skip
  770. }
  771. if !skip_empty || len(s) - l > 0 {
  772. n += 1
  773. }
  774. if n < 1 {
  775. // no results
  776. return nil
  777. }
  778. buf := make([]string, n, allocator)
  779. n, i, l = 0, 0, 0
  780. // slice results
  781. second_pass: for i <= shared {
  782. for substr in substrs {
  783. if s[i:i+sublen] == substr {
  784. if !skip_empty || i - l > 0 {
  785. buf[n] = s[l:i]
  786. n += 1
  787. }
  788. i += sublen
  789. l = i
  790. continue second_pass
  791. }
  792. }
  793. _, skip := utf8.decode_rune_in_string(s[i:])
  794. i += skip
  795. }
  796. if !skip_empty || len(s) - l > 0 {
  797. buf[n] = s[l:]
  798. }
  799. return buf
  800. }
  801. split_multi_iterator :: proc(s: ^string, substrs: []string, skip_empty := false) -> (string, bool) #no_bounds_check {
  802. if s == nil || s^ == "" || len(substrs) <= 0 {
  803. return "", false
  804. }
  805. sublen := len(substrs[0])
  806. for substr in substrs[1:] {
  807. sublen = min(sublen, len(substr))
  808. }
  809. shared := len(s) - sublen
  810. if shared <= 0 {
  811. return "", false
  812. }
  813. // index, last
  814. i, l := 0, 0
  815. loop: for i <= shared {
  816. for substr in substrs {
  817. if s[i:i+sublen] == substr {
  818. if !skip_empty || i - l > 0 {
  819. res := s[l:i]
  820. s^ = s[i:]
  821. return res, true
  822. }
  823. i += sublen
  824. l = i
  825. continue loop
  826. }
  827. }
  828. _, skip := utf8.decode_rune_in_string(s[i:])
  829. i += skip
  830. }
  831. if !skip_empty || len(s) - l > 0 {
  832. res := s[l:]
  833. s^ = s[len(s):]
  834. return res, true
  835. }
  836. return "", false
  837. }
  838. // scrub scruvs invalid utf-8 characters and replaces them with the replacement string
  839. // Adjacent invalid bytes are only replaced once
  840. scrub :: proc(s: string, replacement: string, allocator := context.allocator) -> string {
  841. str := s
  842. b: Builder
  843. init_builder(&b, 0, len(s), allocator)
  844. has_error := false
  845. cursor := 0
  846. origin := str
  847. for len(str) > 0 {
  848. r, w := utf8.decode_rune_in_string(str)
  849. if r == utf8.RUNE_ERROR {
  850. if !has_error {
  851. has_error = true
  852. write_string(&b, origin[:cursor])
  853. }
  854. } else if has_error {
  855. has_error = false
  856. write_string(&b, replacement)
  857. origin = origin[cursor:]
  858. cursor = 0
  859. }
  860. cursor += w
  861. str = str[w:]
  862. }
  863. return to_string(b)
  864. }
  865. reverse :: proc(s: string, allocator := context.allocator) -> string {
  866. str := s
  867. n := len(str)
  868. buf := make([]byte, n)
  869. i := n
  870. for len(str) > 0 {
  871. _, w := utf8.decode_rune_in_string(str)
  872. i -= w
  873. copy(buf[i:], str[:w])
  874. str = str[w:]
  875. }
  876. return string(buf)
  877. }
  878. expand_tabs :: proc(s: string, tab_size: int, allocator := context.allocator) -> string {
  879. if tab_size <= 0 {
  880. panic("tab size must be positive")
  881. }
  882. if s == "" {
  883. return ""
  884. }
  885. b: Builder
  886. init_builder(&b, allocator)
  887. writer := to_writer(&b)
  888. str := s
  889. column: int
  890. for len(str) > 0 {
  891. r, w := utf8.decode_rune_in_string(str)
  892. if r == '\t' {
  893. expand := tab_size - column%tab_size
  894. for i := 0; i < expand; i += 1 {
  895. io.write_byte(writer, ' ')
  896. }
  897. column += expand
  898. } else {
  899. if r == '\n' {
  900. column = 0
  901. } else {
  902. column += w
  903. }
  904. io.write_rune(writer, r)
  905. }
  906. str = str[w:]
  907. }
  908. return to_string(b)
  909. }
  910. partition :: proc(str, sep: string) -> (head, match, tail: string) {
  911. i := index(str, sep)
  912. if i == -1 {
  913. head = str
  914. return
  915. }
  916. head = str[:i]
  917. match = str[i:i+len(sep)]
  918. tail = str[i+len(sep):]
  919. return
  920. }
  921. center_justify :: centre_justify // NOTE(bill): Because Americans exist
  922. // centre_justify returns a string with a pad string at boths sides if the str's rune length is smaller than length
  923. centre_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  924. n := rune_count(str)
  925. if n >= length || pad == "" {
  926. return clone(str, allocator)
  927. }
  928. remains := length-1
  929. pad_len := rune_count(pad)
  930. b: Builder
  931. init_builder(&b, allocator)
  932. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  933. w := to_writer(&b)
  934. write_pad_string(w, pad, pad_len, remains/2)
  935. io.write_string(w, str)
  936. write_pad_string(w, pad, pad_len, (remains+1)/2)
  937. return to_string(b)
  938. }
  939. // left_justify returns a string with a pad string at left side if the str's rune length is smaller than length
  940. left_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  941. n := rune_count(str)
  942. if n >= length || pad == "" {
  943. return clone(str, allocator)
  944. }
  945. remains := length-1
  946. pad_len := rune_count(pad)
  947. b: Builder
  948. init_builder(&b, allocator)
  949. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  950. w := to_writer(&b)
  951. io.write_string(w, str)
  952. write_pad_string(w, pad, pad_len, remains)
  953. return to_string(b)
  954. }
  955. // right_justify returns a string with a pad string at right side if the str's rune length is smaller than length
  956. right_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  957. n := rune_count(str)
  958. if n >= length || pad == "" {
  959. return clone(str, allocator)
  960. }
  961. remains := length-1
  962. pad_len := rune_count(pad)
  963. b: Builder
  964. init_builder(&b, allocator)
  965. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  966. w := to_writer(&b)
  967. write_pad_string(w, pad, pad_len, remains)
  968. io.write_string(w, str)
  969. return to_string(b)
  970. }
  971. @private
  972. write_pad_string :: proc(w: io.Writer, pad: string, pad_len, remains: int) {
  973. repeats := remains / pad_len
  974. for i := 0; i < repeats; i += 1 {
  975. io.write_string(w, pad)
  976. }
  977. n := remains % pad_len
  978. p := pad
  979. for i := 0; i < n; i += 1 {
  980. r, width := utf8.decode_rune_in_string(p)
  981. io.write_rune(w, r)
  982. p = p[width:]
  983. }
  984. }
  985. // fields splits the string s around each instance of one or more consecutive white space character, defined by unicode.is_space
  986. // returning a slice of substrings of s or an empty slice if s only contains white space
  987. fields :: proc(s: string, allocator := context.allocator) -> []string #no_bounds_check {
  988. n := 0
  989. was_space := 1
  990. set_bits := u8(0)
  991. // check to see
  992. for i in 0..<len(s) {
  993. r := s[i]
  994. set_bits |= r
  995. is_space := int(_ascii_space[r])
  996. n += was_space & ~is_space
  997. was_space = is_space
  998. }
  999. if set_bits >= utf8.RUNE_SELF {
  1000. return fields_proc(s, unicode.is_space, allocator)
  1001. }
  1002. if n == 0 {
  1003. return nil
  1004. }
  1005. a := make([]string, n, allocator)
  1006. na := 0
  1007. field_start := 0
  1008. i := 0
  1009. for i < len(s) && _ascii_space[s[i]] {
  1010. i += 1
  1011. }
  1012. field_start = i
  1013. for i < len(s) {
  1014. if !_ascii_space[s[i]] {
  1015. i += 1
  1016. continue
  1017. }
  1018. a[na] = s[field_start : i]
  1019. na += 1
  1020. i += 1
  1021. for i < len(s) && _ascii_space[s[i]] {
  1022. i += 1
  1023. }
  1024. field_start = i
  1025. }
  1026. if field_start < len(s) {
  1027. a[na] = s[field_start:]
  1028. }
  1029. return a
  1030. }
  1031. // fields_proc splits the string s at each run of unicode code points `ch` satisfying f(ch)
  1032. // returns a slice of substrings of s
  1033. // If all code points in s satisfy f(ch) or string is empty, an empty slice is returned
  1034. //
  1035. // fields_proc makes no guarantee about the order in which it calls f(ch)
  1036. // it assumes that `f` always returns the same value for a given ch
  1037. fields_proc :: proc(s: string, f: proc(rune) -> bool, allocator := context.allocator) -> []string #no_bounds_check {
  1038. substrings := make([dynamic]string, 0, 32, allocator)
  1039. start, end := -1, -1
  1040. for r, offset in s {
  1041. end = offset
  1042. if f(r) {
  1043. if start >= 0 {
  1044. append(&substrings, s[start : end])
  1045. // -1 could be used, but just speed it up through bitwise not
  1046. // gotta love 2's complement
  1047. start = ~start
  1048. }
  1049. } else {
  1050. if start < 0 {
  1051. start = end
  1052. }
  1053. }
  1054. }
  1055. if start >= 0 {
  1056. append(&substrings, s[start : end])
  1057. }
  1058. return substrings[:]
  1059. }