strings.odin 25 KB

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