strings.odin 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  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. /*
  236. Splits a string into parts, based on a separator.
  237. Returned strings are substrings of 's'.
  238. ```
  239. s := "aaa.bbb.ccc.ddd.eee" // 5 parts
  240. ss := split(s, ".")
  241. fmt.println(ss) // [aaa, bbb, ccc, ddd, eee]
  242. ```
  243. */
  244. split :: proc(s, sep: string, allocator := context.allocator) -> []string {
  245. return _split(s, sep, 0, -1, allocator)
  246. }
  247. /*
  248. Splits a string into a total of 'n' parts, based on a separator.
  249. Returns fewer parts if there wasn't enough occurrences of the separator.
  250. Returned strings are substrings of 's'.
  251. ```
  252. s := "aaa.bbb.ccc.ddd.eee" // 5 parts present
  253. ss := split_n(s, ".", 3) // total of 3 wanted
  254. fmt.println(ss) // [aaa, bbb, ccc.ddd.eee]
  255. ```
  256. */
  257. split_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  258. return _split(s, sep, 0, n, allocator)
  259. }
  260. split_after :: proc(s, sep: string, allocator := context.allocator) -> []string {
  261. return _split(s, sep, len(sep), -1, allocator)
  262. }
  263. split_after_n :: proc(s, sep: string, n: int, allocator := context.allocator) -> []string {
  264. return _split(s, sep, len(sep), n, allocator)
  265. }
  266. @private
  267. _split_iterator :: proc(s: ^string, sep: string, sep_save: int) -> (res: string, ok: bool) {
  268. if sep == "" {
  269. res = s[:]
  270. ok = true
  271. s^ = s[len(s):]
  272. return
  273. }
  274. m := index(s^, sep)
  275. if m < 0 {
  276. // not found
  277. res = s[:]
  278. ok = res != ""
  279. s^ = s[len(s):]
  280. } else {
  281. res = s[:m+sep_save]
  282. ok = true
  283. s^ = s[m+len(sep):]
  284. }
  285. return
  286. }
  287. split_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  288. return _split_iterator(s, sep, 0)
  289. }
  290. split_after_iterator :: proc(s: ^string, sep: string) -> (string, bool) {
  291. return _split_iterator(s, sep, len(sep))
  292. }
  293. @(private)
  294. _trim_cr :: proc(s: string) -> string {
  295. n := len(s)
  296. if n > 0 {
  297. if s[n-1] == '\r' {
  298. return s[:n-1]
  299. }
  300. }
  301. return s
  302. }
  303. split_lines :: proc(s: string, allocator := context.allocator) -> []string {
  304. sep :: "\n"
  305. lines := _split(s, sep, 0, -1, allocator)
  306. for line in &lines {
  307. line = _trim_cr(line)
  308. }
  309. return lines
  310. }
  311. split_lines_n :: proc(s: string, n: int, allocator := context.allocator) -> []string {
  312. sep :: "\n"
  313. lines := _split(s, sep, 0, n, allocator)
  314. for line in &lines {
  315. line = _trim_cr(line)
  316. }
  317. return lines
  318. }
  319. split_lines_after :: proc(s: string, allocator := context.allocator) -> []string {
  320. sep :: "\n"
  321. lines := _split(s, sep, len(sep), -1, allocator)
  322. for line in &lines {
  323. line = _trim_cr(line)
  324. }
  325. return lines
  326. }
  327. split_lines_after_n :: proc(s: string, n: int, allocator := context.allocator) -> []string {
  328. sep :: "\n"
  329. lines := _split(s, sep, len(sep), n, allocator)
  330. for line in &lines {
  331. line = _trim_cr(line)
  332. }
  333. return lines
  334. }
  335. split_lines_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  336. sep :: "\n"
  337. line = _split_iterator(s, sep, 0) or_return
  338. return _trim_cr(line), true
  339. }
  340. split_lines_after_iterator :: proc(s: ^string) -> (line: string, ok: bool) {
  341. sep :: "\n"
  342. line = _split_iterator(s, sep, len(sep)) or_return
  343. return _trim_cr(line), true
  344. }
  345. index_byte :: proc(s: string, c: byte) -> int {
  346. for i := 0; i < len(s); i += 1 {
  347. if s[i] == c {
  348. return i
  349. }
  350. }
  351. return -1
  352. }
  353. // Returns -1 if c is not present
  354. last_index_byte :: proc(s: string, c: byte) -> int {
  355. for i := len(s)-1; i >= 0; i -= 1 {
  356. if s[i] == c {
  357. return i
  358. }
  359. }
  360. return -1
  361. }
  362. @private PRIME_RABIN_KARP :: 16777619
  363. index :: proc(s, substr: string) -> int {
  364. hash_str_rabin_karp :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  365. for i := 0; i < len(s); i += 1 {
  366. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  367. }
  368. sq := u32(PRIME_RABIN_KARP)
  369. for i := len(s); i > 0; i >>= 1 {
  370. if (i & 1) != 0 {
  371. pow *= sq
  372. }
  373. sq *= sq
  374. }
  375. return
  376. }
  377. n := len(substr)
  378. switch {
  379. case n == 0:
  380. return 0
  381. case n == 1:
  382. return index_byte(s, substr[0])
  383. case n == len(s):
  384. if s == substr {
  385. return 0
  386. }
  387. return -1
  388. case n > len(s):
  389. return -1
  390. }
  391. hash, pow := hash_str_rabin_karp(substr)
  392. h: u32
  393. for i := 0; i < n; i += 1 {
  394. h = h*PRIME_RABIN_KARP + u32(s[i])
  395. }
  396. if h == hash && s[:n] == substr {
  397. return 0
  398. }
  399. for i := n; i < len(s); /**/ {
  400. h *= PRIME_RABIN_KARP
  401. h += u32(s[i])
  402. h -= pow * u32(s[i-n])
  403. i += 1
  404. if h == hash && s[i-n:i] == substr {
  405. return i - n
  406. }
  407. }
  408. return -1
  409. }
  410. last_index :: proc(s, substr: string) -> int {
  411. hash_str_rabin_karp_reverse :: proc(s: string) -> (hash: u32 = 0, pow: u32 = 1) {
  412. for i := len(s) - 1; i >= 0; i -= 1 {
  413. hash = hash*PRIME_RABIN_KARP + u32(s[i])
  414. }
  415. sq := u32(PRIME_RABIN_KARP)
  416. for i := len(s); i > 0; i >>= 1 {
  417. if (i & 1) != 0 {
  418. pow *= sq
  419. }
  420. sq *= sq
  421. }
  422. return
  423. }
  424. n := len(substr)
  425. switch {
  426. case n == 0:
  427. return len(s)
  428. case n == 1:
  429. return last_index_byte(s, substr[0])
  430. case n == len(s):
  431. return 0 if substr == s else -1
  432. case n > len(s):
  433. return -1
  434. }
  435. hash, pow := hash_str_rabin_karp_reverse(substr)
  436. last := len(s) - n
  437. h: u32
  438. for i := len(s)-1; i >= last; i -= 1 {
  439. h = h*PRIME_RABIN_KARP + u32(s[i])
  440. }
  441. if h == hash && s[last:] == substr {
  442. return last
  443. }
  444. for i := last-1; i >= 0; i -= 1 {
  445. h *= PRIME_RABIN_KARP
  446. h += u32(s[i])
  447. h -= pow * u32(s[i+n])
  448. if h == hash && s[i:i+n] == substr {
  449. return i
  450. }
  451. }
  452. return -1
  453. }
  454. // index_any returns the index of the first char of `chars` found in `s`. -1 if not found.
  455. index_any :: proc(s, chars: string) -> int {
  456. if chars == "" {
  457. return -1
  458. }
  459. if len(chars) == 1 {
  460. r := rune(chars[0])
  461. if r >= utf8.RUNE_SELF {
  462. r = utf8.RUNE_ERROR
  463. }
  464. return index_rune(s, r)
  465. }
  466. if len(s) > 8 {
  467. if as, ok := ascii_set_make(chars); ok {
  468. for i in 0..<len(s) {
  469. if ascii_set_contains(as, s[i]) {
  470. return i
  471. }
  472. }
  473. return -1
  474. }
  475. }
  476. for c, i in s {
  477. if index_rune(chars, c) >= 0 {
  478. return i
  479. }
  480. }
  481. return -1
  482. }
  483. last_index_any :: proc(s, chars: string) -> int {
  484. if chars == "" {
  485. return -1
  486. }
  487. if len(s) == 1 {
  488. r := rune(s[0])
  489. if r >= utf8.RUNE_SELF {
  490. r = utf8.RUNE_ERROR
  491. }
  492. return index_rune(chars, r)
  493. }
  494. if len(s) > 8 {
  495. if as, ok := ascii_set_make(chars); ok {
  496. for i := len(s)-1; i >= 0; i -= 1 {
  497. if ascii_set_contains(as, s[i]) {
  498. return i
  499. }
  500. }
  501. return -1
  502. }
  503. }
  504. if len(chars) == 1 {
  505. r := rune(chars[0])
  506. if r >= utf8.RUNE_SELF {
  507. r = utf8.RUNE_ERROR
  508. }
  509. for i := len(s); i > 0; /**/ {
  510. c, w := utf8.decode_last_rune_in_string(s[:i])
  511. i -= w
  512. if c == r {
  513. return i
  514. }
  515. }
  516. return -1
  517. }
  518. for i := len(s); i > 0; /**/ {
  519. r, w := utf8.decode_last_rune_in_string(s[:i])
  520. i -= w
  521. if index_rune(chars, r) >= 0 {
  522. return i
  523. }
  524. }
  525. return -1
  526. }
  527. count :: proc(s, substr: string) -> int {
  528. if len(substr) == 0 { // special case
  529. return rune_count(s) + 1
  530. }
  531. if len(substr) == 1 {
  532. c := substr[0]
  533. switch len(s) {
  534. case 0:
  535. return 0
  536. case 1:
  537. return int(s[0] == c)
  538. }
  539. n := 0
  540. for i := 0; i < len(s); i += 1 {
  541. if s[i] == c {
  542. n += 1
  543. }
  544. }
  545. return n
  546. }
  547. // TODO(bill): Use a non-brute for approach
  548. n := 0
  549. str := s
  550. for {
  551. i := index(str, substr)
  552. if i == -1 {
  553. return n
  554. }
  555. n += 1
  556. str = str[i+len(substr):]
  557. }
  558. return n
  559. }
  560. repeat :: proc(s: string, count: int, allocator := context.allocator) -> string {
  561. if count < 0 {
  562. panic("strings: negative repeat count")
  563. } else if count > 0 && (len(s)*count)/count != len(s) {
  564. panic("strings: repeat count will cause an overflow")
  565. }
  566. b := make([]byte, len(s)*count, allocator)
  567. i := copy(b, s)
  568. for i < len(b) { // 2^N trick to reduce the need to copy
  569. copy(b[i:], b[:i])
  570. i *= 2
  571. }
  572. return string(b)
  573. }
  574. replace_all :: proc(s, old, new: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  575. return replace(s, old, new, -1, allocator)
  576. }
  577. // if n < 0, no limit on the number of replacements
  578. replace :: proc(s, old, new: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  579. if old == new || n == 0 {
  580. was_allocation = false
  581. output = s
  582. return
  583. }
  584. byte_count := n
  585. if m := count(s, old); m == 0 {
  586. was_allocation = false
  587. output = s
  588. return
  589. } else if n < 0 || m < n {
  590. byte_count = m
  591. }
  592. t := make([]byte, len(s) + byte_count*(len(new) - len(old)), allocator)
  593. was_allocation = true
  594. w := 0
  595. start := 0
  596. for i := 0; i < byte_count; i += 1 {
  597. j := start
  598. if len(old) == 0 {
  599. if i > 0 {
  600. _, width := utf8.decode_rune_in_string(s[start:])
  601. j += width
  602. }
  603. } else {
  604. j += index(s[start:], old)
  605. }
  606. w += copy(t[w:], s[start:j])
  607. w += copy(t[w:], new)
  608. start = j + len(old)
  609. }
  610. w += copy(t[w:], s[start:])
  611. output = string(t[0:w])
  612. return
  613. }
  614. remove :: proc(s, key: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  615. return replace(s, key, "", n, allocator)
  616. }
  617. remove_all :: proc(s, key: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
  618. return remove(s, key, -1, allocator)
  619. }
  620. @(private) _ascii_space := [256]bool{'\t' = true, '\n' = true, '\v' = true, '\f' = true, '\r' = true, ' ' = true}
  621. is_ascii_space :: proc(r: rune) -> bool {
  622. if r < utf8.RUNE_SELF {
  623. return _ascii_space[u8(r)]
  624. }
  625. return false
  626. }
  627. is_space :: proc(r: rune) -> bool {
  628. if r < 0x2000 {
  629. switch r {
  630. case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xa0, 0x1680:
  631. return true
  632. }
  633. } else {
  634. if r <= 0x200a {
  635. return true
  636. }
  637. switch r {
  638. case 0x2028, 0x2029, 0x202f, 0x205f, 0x3000:
  639. return true
  640. }
  641. }
  642. return false
  643. }
  644. is_null :: proc(r: rune) -> bool {
  645. return r == 0x0000
  646. }
  647. index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  648. for r, i in s {
  649. if p(r) == truth {
  650. return i
  651. }
  652. }
  653. return -1
  654. }
  655. index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  656. for r, i in s {
  657. if p(state, r) == truth {
  658. return i
  659. }
  660. }
  661. return -1
  662. }
  663. last_index_proc :: proc(s: string, p: proc(rune) -> bool, truth := true) -> int {
  664. // TODO(bill): Probably use Rabin-Karp Search
  665. for i := len(s); i > 0; {
  666. r, size := utf8.decode_last_rune_in_string(s[:i])
  667. i -= size
  668. if p(r) == truth {
  669. return i
  670. }
  671. }
  672. return -1
  673. }
  674. last_index_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr, truth := true) -> int {
  675. // TODO(bill): Probably use Rabin-Karp Search
  676. for i := len(s); i > 0; {
  677. r, size := utf8.decode_last_rune_in_string(s[:i])
  678. i -= size
  679. if p(state, r) == truth {
  680. return i
  681. }
  682. }
  683. return -1
  684. }
  685. trim_left_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  686. i := index_proc(s, p, false)
  687. if i == -1 {
  688. return ""
  689. }
  690. return s[i:]
  691. }
  692. index_rune :: proc(s: string, r: rune) -> int {
  693. switch {
  694. case 0 <= r && r < utf8.RUNE_SELF:
  695. return index_byte(s, byte(r))
  696. case r == utf8.RUNE_ERROR:
  697. for c, i in s {
  698. if c == utf8.RUNE_ERROR {
  699. return i
  700. }
  701. }
  702. return -1
  703. case !utf8.valid_rune(r):
  704. return -1
  705. }
  706. b, w := utf8.encode_rune(r)
  707. return index(s, string(b[:w]))
  708. }
  709. trim_left_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  710. i := index_proc_with_state(s, p, state, false)
  711. if i == -1 {
  712. return ""
  713. }
  714. return s[i:]
  715. }
  716. trim_right_proc :: proc(s: string, p: proc(rune) -> bool) -> string {
  717. i := last_index_proc(s, p, false)
  718. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  719. _, w := utf8.decode_rune_in_string(s[i:])
  720. i += w
  721. } else {
  722. i += 1
  723. }
  724. return s[0:i]
  725. }
  726. trim_right_proc_with_state :: proc(s: string, p: proc(rawptr, rune) -> bool, state: rawptr) -> string {
  727. i := last_index_proc_with_state(s, p, state, false)
  728. if i >= 0 && s[i] >= utf8.RUNE_SELF {
  729. _, w := utf8.decode_rune_in_string(s[i:])
  730. i += w
  731. } else {
  732. i += 1
  733. }
  734. return s[0:i]
  735. }
  736. is_in_cutset :: proc(state: rawptr, r: rune) -> bool {
  737. if state == nil {
  738. return false
  739. }
  740. cutset := (^string)(state)^
  741. for c in cutset {
  742. if r == c {
  743. return true
  744. }
  745. }
  746. return false
  747. }
  748. trim_left :: proc(s: string, cutset: string) -> string {
  749. if s == "" || cutset == "" {
  750. return s
  751. }
  752. state := cutset
  753. return trim_left_proc_with_state(s, is_in_cutset, &state)
  754. }
  755. trim_right :: proc(s: string, cutset: string) -> string {
  756. if s == "" || cutset == "" {
  757. return s
  758. }
  759. state := cutset
  760. return trim_right_proc_with_state(s, is_in_cutset, &state)
  761. }
  762. trim :: proc(s: string, cutset: string) -> string {
  763. return trim_right(trim_left(s, cutset), cutset)
  764. }
  765. trim_left_space :: proc(s: string) -> string {
  766. return trim_left_proc(s, is_space)
  767. }
  768. trim_right_space :: proc(s: string) -> string {
  769. return trim_right_proc(s, is_space)
  770. }
  771. trim_space :: proc(s: string) -> string {
  772. return trim_right_space(trim_left_space(s))
  773. }
  774. trim_left_null :: proc(s: string) -> string {
  775. return trim_left_proc(s, is_null)
  776. }
  777. trim_right_null :: proc(s: string) -> string {
  778. return trim_right_proc(s, is_null)
  779. }
  780. trim_null :: proc(s: string) -> string {
  781. return trim_right_null(trim_left_null(s))
  782. }
  783. trim_prefix :: proc(s, prefix: string) -> string {
  784. if has_prefix(s, prefix) {
  785. return s[len(prefix):]
  786. }
  787. return s
  788. }
  789. trim_suffix :: proc(s, suffix: string) -> string {
  790. if has_suffix(s, suffix) {
  791. return s[:len(s)-len(suffix)]
  792. }
  793. return s
  794. }
  795. split_multi :: proc(s: string, substrs: []string, skip_empty := false, allocator := context.allocator) -> []string #no_bounds_check {
  796. if s == "" || len(substrs) <= 0 {
  797. return nil
  798. }
  799. sublen := len(substrs[0])
  800. for substr in substrs[1:] {
  801. sublen = min(sublen, len(substr))
  802. }
  803. shared := len(s) - sublen
  804. if shared <= 0 {
  805. return nil
  806. }
  807. // number, index, last
  808. n, i, l := 0, 0, 0
  809. // count results
  810. first_pass: for i <= shared {
  811. for substr in substrs {
  812. if s[i:i+sublen] == substr {
  813. if !skip_empty || i - l > 0 {
  814. n += 1
  815. }
  816. i += sublen
  817. l = i
  818. continue first_pass
  819. }
  820. }
  821. _, skip := utf8.decode_rune_in_string(s[i:])
  822. i += skip
  823. }
  824. if !skip_empty || len(s) - l > 0 {
  825. n += 1
  826. }
  827. if n < 1 {
  828. // no results
  829. return nil
  830. }
  831. buf := make([]string, n, allocator)
  832. n, i, l = 0, 0, 0
  833. // slice results
  834. second_pass: for i <= shared {
  835. for substr in substrs {
  836. if s[i:i+sublen] == substr {
  837. if !skip_empty || i - l > 0 {
  838. buf[n] = s[l:i]
  839. n += 1
  840. }
  841. i += sublen
  842. l = i
  843. continue second_pass
  844. }
  845. }
  846. _, skip := utf8.decode_rune_in_string(s[i:])
  847. i += skip
  848. }
  849. if !skip_empty || len(s) - l > 0 {
  850. buf[n] = s[l:]
  851. }
  852. return buf
  853. }
  854. split_multi_iterator :: proc(s: ^string, substrs: []string, skip_empty := false) -> (string, bool) #no_bounds_check {
  855. if s == nil || s^ == "" || len(substrs) <= 0 {
  856. return "", false
  857. }
  858. sublen := len(substrs[0])
  859. for substr in substrs[1:] {
  860. sublen = min(sublen, len(substr))
  861. }
  862. shared := len(s) - sublen
  863. if shared <= 0 {
  864. return "", false
  865. }
  866. // index, last
  867. i, l := 0, 0
  868. loop: for i <= shared {
  869. for substr in substrs {
  870. if s[i:i+sublen] == substr {
  871. if !skip_empty || i - l > 0 {
  872. res := s[l:i]
  873. s^ = s[i:]
  874. return res, true
  875. }
  876. i += sublen
  877. l = i
  878. continue loop
  879. }
  880. }
  881. _, skip := utf8.decode_rune_in_string(s[i:])
  882. i += skip
  883. }
  884. if !skip_empty || len(s) - l > 0 {
  885. res := s[l:]
  886. s^ = s[len(s):]
  887. return res, true
  888. }
  889. return "", false
  890. }
  891. // scrub scruvs invalid utf-8 characters and replaces them with the replacement string
  892. // Adjacent invalid bytes are only replaced once
  893. scrub :: proc(s: string, replacement: string, allocator := context.allocator) -> string {
  894. str := s
  895. b: Builder
  896. init_builder(&b, 0, len(s), allocator)
  897. has_error := false
  898. cursor := 0
  899. origin := str
  900. for len(str) > 0 {
  901. r, w := utf8.decode_rune_in_string(str)
  902. if r == utf8.RUNE_ERROR {
  903. if !has_error {
  904. has_error = true
  905. write_string(&b, origin[:cursor])
  906. }
  907. } else if has_error {
  908. has_error = false
  909. write_string(&b, replacement)
  910. origin = origin[cursor:]
  911. cursor = 0
  912. }
  913. cursor += w
  914. str = str[w:]
  915. }
  916. return to_string(b)
  917. }
  918. reverse :: proc(s: string, allocator := context.allocator) -> string {
  919. str := s
  920. n := len(str)
  921. buf := make([]byte, n)
  922. i := n
  923. for len(str) > 0 {
  924. _, w := utf8.decode_rune_in_string(str)
  925. i -= w
  926. copy(buf[i:], str[:w])
  927. str = str[w:]
  928. }
  929. return string(buf)
  930. }
  931. expand_tabs :: proc(s: string, tab_size: int, allocator := context.allocator) -> string {
  932. if tab_size <= 0 {
  933. panic("tab size must be positive")
  934. }
  935. if s == "" {
  936. return ""
  937. }
  938. b: Builder
  939. init_builder(&b, allocator)
  940. writer := to_writer(&b)
  941. str := s
  942. column: int
  943. for len(str) > 0 {
  944. r, w := utf8.decode_rune_in_string(str)
  945. if r == '\t' {
  946. expand := tab_size - column%tab_size
  947. for i := 0; i < expand; i += 1 {
  948. io.write_byte(writer, ' ')
  949. }
  950. column += expand
  951. } else {
  952. if r == '\n' {
  953. column = 0
  954. } else {
  955. column += w
  956. }
  957. io.write_rune(writer, r)
  958. }
  959. str = str[w:]
  960. }
  961. return to_string(b)
  962. }
  963. partition :: proc(str, sep: string) -> (head, match, tail: string) {
  964. i := index(str, sep)
  965. if i == -1 {
  966. head = str
  967. return
  968. }
  969. head = str[:i]
  970. match = str[i:i+len(sep)]
  971. tail = str[i+len(sep):]
  972. return
  973. }
  974. center_justify :: centre_justify // NOTE(bill): Because Americans exist
  975. // centre_justify returns a string with a pad string at boths sides if the str's rune length is smaller than length
  976. centre_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  977. n := rune_count(str)
  978. if n >= length || pad == "" {
  979. return clone(str, allocator)
  980. }
  981. remains := length-1
  982. pad_len := rune_count(pad)
  983. b: Builder
  984. init_builder(&b, allocator)
  985. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  986. w := to_writer(&b)
  987. write_pad_string(w, pad, pad_len, remains/2)
  988. io.write_string(w, str)
  989. write_pad_string(w, pad, pad_len, (remains+1)/2)
  990. return to_string(b)
  991. }
  992. // left_justify returns a string with a pad string at left side if the str's rune length is smaller than length
  993. left_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  994. n := rune_count(str)
  995. if n >= length || pad == "" {
  996. return clone(str, allocator)
  997. }
  998. remains := length-1
  999. pad_len := rune_count(pad)
  1000. b: Builder
  1001. init_builder(&b, allocator)
  1002. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  1003. w := to_writer(&b)
  1004. io.write_string(w, str)
  1005. write_pad_string(w, pad, pad_len, remains)
  1006. return to_string(b)
  1007. }
  1008. // right_justify returns a string with a pad string at right side if the str's rune length is smaller than length
  1009. right_justify :: proc(str: string, length: int, pad: string, allocator := context.allocator) -> string {
  1010. n := rune_count(str)
  1011. if n >= length || pad == "" {
  1012. return clone(str, allocator)
  1013. }
  1014. remains := length-1
  1015. pad_len := rune_count(pad)
  1016. b: Builder
  1017. init_builder(&b, allocator)
  1018. grow_builder(&b, len(str) + (remains/pad_len + 1)*len(pad))
  1019. w := to_writer(&b)
  1020. write_pad_string(w, pad, pad_len, remains)
  1021. io.write_string(w, str)
  1022. return to_string(b)
  1023. }
  1024. @private
  1025. write_pad_string :: proc(w: io.Writer, pad: string, pad_len, remains: int) {
  1026. repeats := remains / pad_len
  1027. for i := 0; i < repeats; i += 1 {
  1028. io.write_string(w, pad)
  1029. }
  1030. n := remains % pad_len
  1031. p := pad
  1032. for i := 0; i < n; i += 1 {
  1033. r, width := utf8.decode_rune_in_string(p)
  1034. io.write_rune(w, r)
  1035. p = p[width:]
  1036. }
  1037. }
  1038. // fields splits the string s around each instance of one or more consecutive white space character, defined by unicode.is_space
  1039. // returning a slice of substrings of s or an empty slice if s only contains white space
  1040. fields :: proc(s: string, allocator := context.allocator) -> []string #no_bounds_check {
  1041. n := 0
  1042. was_space := 1
  1043. set_bits := u8(0)
  1044. // check to see
  1045. for i in 0..<len(s) {
  1046. r := s[i]
  1047. set_bits |= r
  1048. is_space := int(_ascii_space[r])
  1049. n += was_space & ~is_space
  1050. was_space = is_space
  1051. }
  1052. if set_bits >= utf8.RUNE_SELF {
  1053. return fields_proc(s, unicode.is_space, allocator)
  1054. }
  1055. if n == 0 {
  1056. return nil
  1057. }
  1058. a := make([]string, n, allocator)
  1059. na := 0
  1060. field_start := 0
  1061. i := 0
  1062. for i < len(s) && _ascii_space[s[i]] {
  1063. i += 1
  1064. }
  1065. field_start = i
  1066. for i < len(s) {
  1067. if !_ascii_space[s[i]] {
  1068. i += 1
  1069. continue
  1070. }
  1071. a[na] = s[field_start : i]
  1072. na += 1
  1073. i += 1
  1074. for i < len(s) && _ascii_space[s[i]] {
  1075. i += 1
  1076. }
  1077. field_start = i
  1078. }
  1079. if field_start < len(s) {
  1080. a[na] = s[field_start:]
  1081. }
  1082. return a
  1083. }
  1084. // fields_proc splits the string s at each run of unicode code points `ch` satisfying f(ch)
  1085. // returns a slice of substrings of s
  1086. // If all code points in s satisfy f(ch) or string is empty, an empty slice is returned
  1087. //
  1088. // fields_proc makes no guarantee about the order in which it calls f(ch)
  1089. // it assumes that `f` always returns the same value for a given ch
  1090. fields_proc :: proc(s: string, f: proc(rune) -> bool, allocator := context.allocator) -> []string #no_bounds_check {
  1091. substrings := make([dynamic]string, 0, 32, allocator)
  1092. start, end := -1, -1
  1093. for r, offset in s {
  1094. end = offset
  1095. if f(r) {
  1096. if start >= 0 {
  1097. append(&substrings, s[start : end])
  1098. // -1 could be used, but just speed it up through bitwise not
  1099. // gotta love 2's complement
  1100. start = ~start
  1101. }
  1102. } else {
  1103. if start < 0 {
  1104. start = end
  1105. }
  1106. }
  1107. }
  1108. if start >= 0 {
  1109. append(&substrings, s[start : len(s)])
  1110. }
  1111. return substrings[:]
  1112. }