/
string.v
2372 lines (2198 loc) · 58.9 KB
/
string.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019-2023 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module builtin
import strconv
/*
Note: A V string should be/is immutable from the point of view of
V user programs after it is first created. A V string is
also slightly larger than the equivalent C string because
the V string also has an integer length attached.
This tradeoff is made, since V strings are created just *once*,
but potentially used *many times* over their lifetime.
The V string implementation uses a struct, that has a .str field,
which points to a C style 0 terminated memory block. Although not
strictly necessary from the V point of view, that additional 0
is *very useful for C interoperability*.
The V string implementation also has an integer .len field,
containing the length of the .str field, excluding the
terminating 0 (just like the C's strlen(s) would do).
The 0 ending of .str, and the .len field, mean that in practice:
a) a V string s can be used very easily, wherever a
C string is needed, just by passing s.str,
without a need for further conversion/copying.
b) where strlen(s) is needed, you can just pass s.len,
without having to constantly recompute the length of s
*over and over again* like some C programs do. This is because
V strings are immutable and so their length does not change.
Ordinary V code *does not need* to be concerned with the
additional 0 in the .str field. The 0 *must* be put there by the
low level string creating functions inside this module.
Failing to do this will lead to programs that work most of the
time, when used with pure V functions, but fail in strange ways,
when used with modules using C functions (for example os and so on).
*/
pub struct string {
pub:
str &u8 = 0 // points to a C style 0 terminated string of bytes.
len int // the length of the .str field, excluding the ending 0 byte. It is always equal to strlen(.str).
// NB string.is_lit is an enumeration of the following:
// .is_lit == 0 => a fresh string, should be freed by autofree
// .is_lit == 1 => a literal string from .rodata, should NOT be freed
// .is_lit == -98761234 => already freed string, protects against double frees.
// ---------> ^^^^^^^^^ calling free on these is a bug.
// Any other value means that the string has been corrupted.
mut:
is_lit int
}
// runes returns an array of all the utf runes in the string `s`
// which is useful if you want random access to them
[direct_array_access]
pub fn (s string) runes() []rune {
mut runes := []rune{cap: s.len}
for i := 0; i < s.len; i++ {
char_len := utf8_char_len(unsafe { s.str[i] })
if char_len > 1 {
end := if s.len - 1 >= i + char_len { i + char_len } else { s.len }
mut r := unsafe { s[i..end] }
runes << r.utf32_code()
i += char_len - 1
} else {
runes << unsafe { s.str[i] }
}
}
return runes
}
// cstring_to_vstring creates a new V string copy of the C style string,
// pointed by `s`. This function is most likely what you want to use when
// working with C style pointers to 0 terminated strings (i.e. `char*`).
// It is recommended to use it, unless you *do* understand the implications of
// tos/tos2/tos3/tos4/tos5 in terms of memory management and interactions with
// -autofree and `[manualfree]`.
// It will panic, if the pointer `s` is 0.
[unsafe]
pub fn cstring_to_vstring(s &char) string {
return unsafe { tos2(&u8(s)) }.clone()
}
// tos_clone creates a new V string copy of the C style string, pointed by `s`.
// See also cstring_to_vstring (it is the same as it, the only difference is,
// that tos_clone expects `&byte`, while cstring_to_vstring expects &char).
// It will panic, if the pointer `s` is 0.
[unsafe]
pub fn tos_clone(s &u8) string {
return unsafe { tos2(s) }.clone()
}
// tos creates a V string, given a C style pointer to a 0 terminated block.
// Note: the memory block pointed by s is *reused, not copied*!
// It will panic, when the pointer `s` is 0.
// See also `tos_clone`.
[unsafe]
pub fn tos(s &u8, len int) string {
if s == 0 {
panic('tos(): nil string')
}
return string{
str: unsafe { s }
len: len
}
}
// tos2 creates a V string, given a C style pointer to a 0 terminated block.
// Note: the memory block pointed by s is *reused, not copied*!
// It will calculate the length first, thus it is more costly than `tos`.
// It will panic, when the pointer `s` is 0.
// It is the same as `tos3`, but for &byte pointers, avoiding callsite casts.
// See also `tos_clone`.
[unsafe]
pub fn tos2(s &u8) string {
if s == 0 {
panic('tos2: nil string')
}
return string{
str: unsafe { s }
len: unsafe { vstrlen(s) }
}
}
// tos3 creates a V string, given a C style pointer to a 0 terminated block.
// Note: the memory block pointed by s is *reused, not copied*!
// It will calculate the length first, so it is more costly than tos.
// It will panic, when the pointer `s` is 0.
// It is the same as `tos2`, but for &char pointers, avoiding callsite casts.
// See also `tos_clone`.
[unsafe]
pub fn tos3(s &char) string {
if s == 0 {
panic('tos3: nil string')
}
return string{
str: unsafe { &u8(s) }
len: unsafe { vstrlen_char(s) }
}
}
// tos4 creates a V string, given a C style pointer to a 0 terminated block.
// Note: the memory block pointed by s is *reused, not copied*!
// It will calculate the length first, so it is more costly than tos.
// It returns '', when given a 0 pointer `s`, it does NOT panic.
// It is the same as `tos5`, but for &byte pointers, avoiding callsite casts.
// See also `tos_clone`.
[unsafe]
pub fn tos4(s &u8) string {
if s == 0 {
return ''
}
return string{
str: unsafe { s }
len: unsafe { vstrlen(s) }
}
}
// tos5 creates a V string, given a C style pointer to a 0 terminated block.
// Note: the memory block pointed by s is *reused, not copied*!
// It will calculate the length first, so it is more costly than tos.
// It returns '', when given a 0 pointer `s`, it does NOT panic.
// It is the same as `tos4`, but for &char pointers, avoiding callsite casts.
// See also `tos_clone`.
[unsafe]
pub fn tos5(s &char) string {
if s == 0 {
return ''
}
return string{
str: unsafe { &u8(s) }
len: unsafe { vstrlen_char(s) }
}
}
// vstring converts a C style string to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// Note: instead of `&u8(arr.data).vstring()`, do use `tos_clone(&u8(arr.data))`.
// Strings returned from this function will be normal V strings beside that,
// (i.e. they would be freed by V's -autofree mechanism, when they are no longer used).
// See also `tos_clone`.
[unsafe]
pub fn (bp &u8) vstring() string {
return string{
str: unsafe { bp }
len: unsafe { vstrlen(bp) }
}
}
// vstring_with_len converts a C style 0 terminated string to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// This method has lower overhead compared to .vstring(), since it
// does not need to calculate the length of the 0 terminated string.
// See also `tos_clone`.
[unsafe]
pub fn (bp &u8) vstring_with_len(len int) string {
return string{
str: unsafe { bp }
len: len
is_lit: 0
}
}
// vstring converts a C style string to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// Strings returned from this function will be normal V strings beside that,
// (i.e. they would be freed by V's -autofree mechanism, when they are
// no longer used).
// Note: instead of `&u8(a.data).vstring()`, use `tos_clone(&u8(a.data))`.
// See also `tos_clone`.
[unsafe]
pub fn (cp &char) vstring() string {
return string{
str: &u8(cp)
len: unsafe { vstrlen_char(cp) }
is_lit: 0
}
}
// vstring_with_len converts a C style 0 terminated string to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// This method has lower overhead compared to .vstring(), since it
// does not calculate the length of the 0 terminated string.
// See also `tos_clone`.
[unsafe]
pub fn (cp &char) vstring_with_len(len int) string {
return string{
str: &u8(cp)
len: len
is_lit: 0
}
}
// vstring_literal converts a C style string to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// NB2: unlike vstring, vstring_literal will mark the string
// as a literal, so it will not be freed by -autofree.
// This is suitable for readonly strings, C string literals etc,
// that can be read by the V program, but that should not be
// managed/freed by it, for example `os.args` is implemented using it.
// See also `tos_clone`.
[unsafe]
pub fn (bp &u8) vstring_literal() string {
return string{
str: unsafe { bp }
len: unsafe { vstrlen(bp) }
is_lit: 1
}
}
// vstring_with_len converts a C style string to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// This method has lower overhead compared to .vstring_literal(), since it
// does not need to calculate the length of the 0 terminated string.
// See also `tos_clone`.
[unsafe]
pub fn (bp &u8) vstring_literal_with_len(len int) string {
return string{
str: unsafe { bp }
len: len
is_lit: 1
}
}
// vstring_literal converts a C style string char* pointer to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// See also `byteptr.vstring_literal` for more details.
// See also `tos_clone`.
[unsafe]
pub fn (cp &char) vstring_literal() string {
return string{
str: &u8(cp)
len: unsafe { vstrlen_char(cp) }
is_lit: 1
}
}
// vstring_literal_with_len converts a C style string char* pointer,
// to a V string.
// Note: the memory block pointed by `bp` is *reused, not copied*!
// This method has lower overhead compared to .vstring_literal(), since it
// does not need to calculate the length of the 0 terminated string.
// See also `tos_clone`.
[unsafe]
pub fn (cp &char) vstring_literal_with_len(len int) string {
return string{
str: &u8(cp)
len: len
is_lit: 1
}
}
// len_utf8 returns the number of runes contained in the string `s`.
pub fn (s string) len_utf8() int {
mut l := 0
mut i := 0
for i < s.len {
l++
i += ((0xe5000000 >> ((unsafe { s.str[i] } >> 3) & 0x1e)) & 3) + 1
}
return l
}
// clone_static returns an independent copy of a given array.
// It should be used only in -autofree generated code.
[inline]
fn (a string) clone_static() string {
return a.clone()
}
// clone returns a copy of the V string `a`.
pub fn (a string) clone() string {
if a.len == 0 {
return ''
}
mut b := string{
str: unsafe { malloc_noscan(a.len + 1) }
len: a.len
}
unsafe {
vmemcpy(b.str, a.str, a.len)
b.str[a.len] = 0
}
return b
}
// replace_once replaces the first occurrence of `rep` with the string passed in `with`.
pub fn (s string) replace_once(rep string, with string) string {
idx := s.index_(rep)
if idx == -1 {
return s.clone()
}
return s.substr(0, idx) + with + s.substr(idx + rep.len, s.len)
}
// replace replaces all occurrences of `rep` with the string passed in `with`.
[direct_array_access]
pub fn (s string) replace(rep string, with string) string {
if s.len == 0 || rep.len == 0 || rep.len > s.len {
return s.clone()
}
if !s.contains(rep) {
return s.clone()
}
// TODO PERF Allocating ints is expensive. Should be a stack array
// Get locations of all reps within this string
mut idxs := []int{cap: s.len / rep.len}
defer {
unsafe { idxs.free() }
}
mut idx := 0
for {
idx = s.index_after(rep, idx)
if idx == -1 {
break
}
idxs << idx
idx += rep.len
}
// Dont change the string if there's nothing to replace
if idxs.len == 0 {
return s.clone()
}
// Now we know the number of replacements we need to do and we can calc the len of the new string
new_len := s.len + idxs.len * (with.len - rep.len)
mut b := unsafe { malloc_noscan(new_len + 1) } // add space for the null byte at the end
// Fill the new string
mut b_i := 0
mut s_idx := 0
for _, rep_pos in idxs {
for i in s_idx .. rep_pos { // copy everything up to piece being replaced
unsafe {
b[b_i] = s[i]
}
b_i++
}
s_idx = rep_pos + rep.len // move string index past replacement
for i in 0 .. with.len { // copy replacement piece
unsafe {
b[b_i] = with[i]
}
b_i++
}
}
if s_idx < s.len { // if any original after last replacement, copy it
for i in s_idx .. s.len {
unsafe {
b[b_i] = s[i]
}
b_i++
}
}
unsafe {
b[new_len] = 0
return tos(b, new_len)
}
}
struct RepIndex {
idx int
val_idx int
}
// replace_each replaces all occurrences of the string pairs given in `vals`.
// Example: assert 'ABCD'.replace_each(['B','C/','C','D','D','C']) == 'AC/DC'
[direct_array_access]
pub fn (s string) replace_each(vals []string) string {
if s.len == 0 || vals.len == 0 {
return s.clone()
}
if vals.len % 2 != 0 {
eprintln('string.replace_each(): odd number of strings')
return s.clone()
}
// `rep` - string to replace
// `with` - string to replace with
// Remember positions of all rep strings, and calculate the length
// of the new string to do just one allocation.
mut new_len := s.len
mut idxs := []RepIndex{cap: 6}
mut idx := 0
s_ := s.clone()
for rep_i := 0; rep_i < vals.len; rep_i += 2 {
// vals: ['rep1, 'with1', 'rep2', 'with2']
rep := vals[rep_i]
with := vals[rep_i + 1]
for {
idx = s_.index_after(rep, idx)
if idx == -1 {
break
}
// The string already found is set to `/del`, to avoid duplicate searches.
for i in 0 .. rep.len {
unsafe {
s_.str[idx + i] = 127
}
}
// We need to remember both the position in the string,
// and which rep/with pair it refers to.
idxs << RepIndex{
idx: idx
val_idx: rep_i
}
idx += rep.len
new_len += with.len - rep.len
}
}
// Dont change the string if there's nothing to replace
if idxs.len == 0 {
return s.clone()
}
idxs.sort(a.idx < b.idx)
mut b := unsafe { malloc_noscan(new_len + 1) } // add space for 0 terminator
// Fill the new string
mut idx_pos := 0
mut cur_idx := idxs[idx_pos]
mut b_i := 0
for i := 0; i < s.len; i++ {
if i == cur_idx.idx {
// Reached the location of rep, replace it with "with"
rep := vals[cur_idx.val_idx]
with := vals[cur_idx.val_idx + 1]
for j in 0 .. with.len {
unsafe {
b[b_i] = with[j]
}
b_i++
}
// Skip the length of rep, since we just replaced it with "with"
i += rep.len - 1
// Go to the next index
idx_pos++
if idx_pos < idxs.len {
cur_idx = idxs[idx_pos]
}
} else {
// Rep doesnt start here, just copy
unsafe {
b[b_i] = s.str[i]
}
b_i++
}
}
unsafe {
b[new_len] = 0
return tos(b, new_len)
}
}
// replace_char replaces all occurrences of the character `rep` multiple occurrences of the character passed in `with` with respect to `repeat`.
// Example: assert '\tHello!'.replace_char(`\t`,` `,8) == ' Hello!'
[direct_array_access]
pub fn (s string) replace_char(rep u8, with u8, repeat int) string {
$if !no_bounds_checking {
if repeat <= 0 {
panic('string.replace_char(): tab length too short')
}
}
if s.len == 0 {
return s.clone()
}
// TODO Allocating ints is expensive. Should be a stack array
// - string.replace()
mut idxs := []int{cap: s.len}
defer {
unsafe { idxs.free() }
}
// No need to do a contains(), it already traverses the entire string
for i, ch in s {
if ch == rep { // Found char? Mark its location
idxs << i
}
}
if idxs.len == 0 {
return s.clone()
}
// Now we know the number of replacements we need to do and we can calc the len of the new string
new_len := s.len + idxs.len * (repeat - 1)
mut b := unsafe { malloc_noscan(new_len + 1) } // add space for the null byte at the end
// Fill the new string
mut b_i := 0
mut s_idx := 0
for rep_pos in idxs {
for i in s_idx .. rep_pos { // copy everything up to piece being replaced
unsafe {
b[b_i] = s[i]
}
b_i++
}
s_idx = rep_pos + 1 // move string index past replacement
for _ in 0 .. repeat { // copy replacement piece
unsafe {
b[b_i] = with
}
b_i++
}
}
if s_idx < s.len { // if any original after last replacement, copy it
for i in s_idx .. s.len {
unsafe {
b[b_i] = s[i]
}
b_i++
}
}
unsafe {
b[new_len] = 0
return tos(b, new_len)
}
}
// normalize_tabs replaces all tab characters with `tab_len` amount of spaces
// Example: assert '\t\tpop rax\t; pop rax'.normalize_tabs(2) == ' pop rax ; pop rax'
[inline]
pub fn (s string) normalize_tabs(tab_len int) string {
return s.replace_char(`\t`, ` `, tab_len)
}
// bool returns `true` if the string equals the word "true" it will return `false` otherwise.
[inline]
pub fn (s string) bool() bool {
return s == 'true' || s == 't' // TODO t for pg, remove
}
// int returns the value of the string as an integer `'1'.int() == 1`.
[inline]
pub fn (s string) int() int {
return int(strconv.common_parse_int(s, 0, 32, false, false) or { 0 })
}
// i64 returns the value of the string as i64 `'1'.i64() == i64(1)`.
[inline]
pub fn (s string) i64() i64 {
return strconv.common_parse_int(s, 0, 64, false, false) or { 0 }
}
// i8 returns the value of the string as i8 `'1'.i8() == i8(1)`.
[inline]
pub fn (s string) i8() i8 {
return i8(strconv.common_parse_int(s, 0, 8, false, false) or { 0 })
}
// i16 returns the value of the string as i16 `'1'.i16() == i16(1)`.
[inline]
pub fn (s string) i16() i16 {
return i16(strconv.common_parse_int(s, 0, 16, false, false) or { 0 })
}
// f32 returns the value of the string as f32 `'1.0'.f32() == f32(1)`.
[inline]
pub fn (s string) f32() f32 {
return f32(strconv.atof64(s) or { 0 })
}
// f64 returns the value of the string as f64 `'1.0'.f64() == f64(1)`.
[inline]
pub fn (s string) f64() f64 {
return strconv.atof64(s) or { 0 }
}
// u8 returns the value of the string as u8 `'1'.u8() == u8(1)`.
[inline]
pub fn (s string) u8() u8 {
return u8(strconv.common_parse_uint(s, 0, 8, false, false) or { 0 })
}
// u16 returns the value of the string as u16 `'1'.u16() == u16(1)`.
[inline]
pub fn (s string) u16() u16 {
return u16(strconv.common_parse_uint(s, 0, 16, false, false) or { 0 })
}
// u32 returns the value of the string as u32 `'1'.u32() == u32(1)`.
[inline]
pub fn (s string) u32() u32 {
return u32(strconv.common_parse_uint(s, 0, 32, false, false) or { 0 })
}
// u64 returns the value of the string as u64 `'1'.u64() == u64(1)`.
[inline]
pub fn (s string) u64() u64 {
return strconv.common_parse_uint(s, 0, 64, false, false) or { 0 }
}
// parse_uint is like `parse_int` but for unsigned numbers
//
// This method directly exposes the `parse_uint` function from `strconv`
// as a method on `string`. For more advanced features,
// consider calling `strconv.common_parse_uint` directly.
[inline]
pub fn (s string) parse_uint(_base int, _bit_size int) !u64 {
return strconv.parse_uint(s, _base, _bit_size)
}
// parse_int interprets a string s in the given base (0, 2 to 36) and
// bit size (0 to 64) and returns the corresponding value i.
//
// If the base argument is 0, the true base is implied by the string's
// prefix: 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise.
// Also, for argument base 0 only, underscore characters are permitted
// as defined by the Go syntax for integer literals.
//
// The bitSize argument specifies the integer type
// that the result must fit into. Bit sizes 0, 8, 16, 32, and 64
// correspond to int, int8, int16, int32, and int64.
// If bitSize is below 0 or above 64, an error is returned.
//
// This method directly exposes the `parse_int` function from `strconv`
// as a method on `string`. For more advanced features,
// consider calling `strconv.common_parse_int` directly.
[inline]
pub fn (s string) parse_int(_base int, _bit_size int) !i64 {
return strconv.parse_int(s, _base, _bit_size)
}
[direct_array_access]
fn (s string) == (a string) bool {
if s.str == 0 {
// should never happen
panic('string.eq(): nil string')
}
if s.len != a.len {
return false
}
if s.len > 0 {
last_idx := s.len - 1
if s[last_idx] != a[last_idx] {
return false
}
}
unsafe {
return vmemcmp(s.str, a.str, a.len) == 0
}
}
// compare returns -1 if `s` < `a`, 0 if `s` == `a`, and 1 if `s` > `a`
[direct_array_access]
pub fn (s string) compare(a string) int {
min_len := if s.len < a.len { s.len } else { a.len }
for i in 0 .. min_len {
if s[i] < a[i] {
return -1
}
if s[i] > a[i] {
return 1
}
}
if s.len < a.len {
return -1
}
if s.len > a.len {
return 1
}
return 0
}
[direct_array_access]
fn (s string) < (a string) bool {
for i in 0 .. s.len {
if i >= a.len || s[i] > a[i] {
return false
} else if s[i] < a[i] {
return true
}
}
if s.len < a.len {
return true
}
return false
}
[direct_array_access]
fn (s string) + (a string) string {
new_len := a.len + s.len
mut res := string{
str: unsafe { malloc_noscan(new_len + 1) }
len: new_len
}
unsafe {
vmemcpy(res.str, s.str, s.len)
vmemcpy(res.str + s.len, a.str, a.len)
}
unsafe {
res.str[new_len] = 0 // V strings are not null terminated, but just in case
}
return res
}
// split_any splits the string to an array by any of the `delim` chars.
// Example: "first row\nsecond row".split_any(" \n") == ['first', 'row', 'second', 'row']
// Split a string using the chars in the delimiter string as delimiters chars.
// If the delimiter string is empty then `.split()` is used.
[direct_array_access]
pub fn (s string) split_any(delim string) []string {
mut res := []string{}
mut i := 0
// check empty source string
if s.len > 0 {
// if empty delimiter string using default split
if delim.len <= 0 {
return s.split('')
}
for index, ch in s {
for delim_ch in delim {
if ch == delim_ch {
res << s[i..index]
i = index + 1
break
}
}
}
if i < s.len {
res << s[i..]
}
}
return res
}
// rsplit_any splits the string to an array by any of the `delim` chars in reverse order.
// Example: "first row\nsecond row".rsplit_any(" \n") == ['row', 'second', 'row', 'first']
// Split a string using the chars in the delimiter string as delimiters chars.
// If the delimiter string is empty then `.rsplit()` is used.
[direct_array_access]
pub fn (s string) rsplit_any(delim string) []string {
mut res := []string{}
mut i := s.len - 1
if s.len > 0 {
if delim.len <= 0 {
return s.rsplit('')
}
mut rbound := s.len
for i >= 0 {
for delim_ch in delim {
if s[i] == delim_ch {
res << s[i + 1..rbound]
rbound = i
break
}
}
i--
}
if rbound > 0 {
res << s[..rbound]
}
}
return res
}
// split splits the string to an array by `delim`.
// Example: assert 'A B C'.split(' ') == ['A','B','C']
// If `delim` is empty the string is split by it's characters.
// Example: assert 'DEF'.split('') == ['D','E','F']
[inline]
pub fn (s string) split(delim string) []string {
return s.split_nth(delim, 0)
}
// rsplit splits the string to an array by `delim` in reverse order.
// Example: assert 'A B C'.rsplit(' ') == ['C','B','A']
// If `delim` is empty the string is split by it's characters.
// Example: assert 'DEF'.rsplit('') == ['F','E','D']
[inline]
pub fn (s string) rsplit(delim string) []string {
return s.rsplit_nth(delim, 0)
}
// split_once divides string into pair of string by `delim`.
// Example:
// ```v
// path, ext := 'file.ts.dts'.splice_once('.')?
// assert path == 'file'
// assert ext == 'ts.dts'
// ```
// Note that rsplit_once returns splitted string string as first part of pair,
// and returns remaining as second part of pair.
pub fn (s string) split_once(delim string) ?(string, string) {
result := s.split_nth(delim, 2)
if result.len != 2 {
return none
}
return result[0], result[1]
}
// rsplit_once divides string into pair of string by `delim`.
// Example:
// ```v
// path, ext := 'file.ts.dts'.splice_once('.')?
// assert path == 'file.ts'
// assert ext == 'dts'
// ```
// Note that rsplit_once returns remaining string as first part of pair,
// and returns splitted string as second part of pair.
pub fn (s string) rsplit_once(delim string) ?(string, string) {
result := s.rsplit_nth(delim, 2)
if result.len != 2 {
return none
}
return result[1], result[0]
}
// split_nth splits the string based on the passed `delim` substring.
// It returns the first Nth parts. When N=0, return all the splits.
// The last returned element has the remainder of the string, even if
// the remainder contains more `delim` substrings.
[direct_array_access]
pub fn (s string) split_nth(delim string, nth int) []string {
mut res := []string{}
mut i := 0
match delim.len {
0 {
i = 1
for ch in s {
if nth > 0 && i >= nth {
res << s[i - 1..]
break
}
res << ch.ascii_str()
i++
}
return res
}
1 {
mut start := 0
delim_byte := delim[0]
for i < s.len {
if s[i] == delim_byte {
was_last := nth > 0 && res.len == nth - 1
if was_last {
break
}
val := s.substr(start, i)
res << val
start = i + delim.len
i = start
} else {
i++
}
}
// Then the remaining right part of the string
if nth < 1 || res.len < nth {
res << s[start..]
}
return res
}
else {
mut start := 0
// Take the left part for each delimiter occurrence
for i <= s.len {
is_delim := i + delim.len <= s.len && s.substr(i, i + delim.len) == delim
if is_delim {
was_last := nth > 0 && res.len == nth - 1
if was_last {
break
}
val := s.substr(start, i)
res << val
start = i + delim.len
i = start
} else {
i++
}
}
// Then the remaining right part of the string
if nth < 1 || res.len < nth {
res << s[start..]
}
return res
}
}
}
// rsplit_nth splits the string based on the passed `delim` substring in revese order.
// It returns the first Nth parts. When N=0, return all the splits.
// The last returned element has the remainder of the string, even if
// the remainder contains more `delim` substrings.
[direct_array_access]
pub fn (s string) rsplit_nth(delim string, nth int) []string {
mut res := []string{}
mut i := s.len - 1
match delim.len {
0 {
for i >= 0 {
if nth > 0 && res.len == nth - 1 {
res << s[..i + 1]
break
}
res << s[i].ascii_str()
i--
}
return res
}
1 {
mut rbound := s.len
delim_byte := delim[0]
for i >= 0 {
if s[i] == delim_byte {
if nth > 0 && res.len == nth - 1 {
break
}
res << s[i + 1..rbound]
rbound = i
i--
} else {
i--
}
}
if nth < 1 || res.len < nth {
res << s[..rbound]
}
return res
}
else {
mut rbound := s.len
for i >= 0 {
is_delim := i - delim.len >= 0 && s[i - delim.len..i] == delim
if is_delim {
if nth > 0 && res.len == nth - 1 {
break
}
res << s[i..rbound]
rbound = i - delim.len
i -= delim.len
} else {
i--
}
}
if nth < 1 || res.len < nth {
res << s[..rbound]
}
return res
}
}
}
// split_into_lines splits the string by newline characters.
// newlines are stripped.
// `\r` (MacOS), `\n` (POSIX), and `\r\n` (WinOS) line endings are all supported (including mixed line endings).
// NOTE: algorithm is "greedy", consuming '\r\n' as a single line ending with higher priority than '\r' and '\n' as multiple endings
[direct_array_access]