strings.odin 26 KB

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