/
string.inko
924 lines (810 loc) · 24 KB
/
string.inko
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
# A UTF-8 encoded and immutable string.
#
# A `String` is an immutable, UTF-8 encoded string.
#
# Various methods for `String` may operate on or mention "characters". Whenever
# this is the case, we are referring to extended grapheme clusters, _not_
# Unicode scalar values or bytes.
import std.array.(bounds_check)
import std.byte_array.(IntoByteArray, ToByteArray)
import std.clone.Clone
import std.cmp.(Contains, Equal)
import std.drop.Drop
import std.fmt.(Format, Formatter)
import std.fs.path.(IntoPath, Path, ToPath)
import std.hash.(Hash, Hasher)
import std.io.Read
import std.iter.(Stream, Iter)
import std.ops.Add
class extern StringResult {
let @tag: Int
let @value: String
}
fn extern inko_string_to_lower(state: Pointer[UInt8], string: String) -> String
fn extern inko_string_to_upper(state: Pointer[UInt8], string: String) -> String
fn extern inko_string_slice_bytes_into(
string: String,
into: mut ByteArray,
start: Int,
size: Int,
)
fn extern inko_string_chars(string: String) -> Pointer[UInt8]
fn extern inko_string_chars_next(
state: Pointer[UInt8],
iter: Pointer[UInt8],
) -> StringResult
fn extern inko_string_chars_drop(iter: Pointer[UInt8])
fn extern inko_string_drop(string: String)
fn extern inko_string_to_byte_array(
state: Pointer[UInt8],
string: String,
) -> ByteArray
fn extern inko_string_concat(
state: Pointer[UInt8],
strings: Pointer[String],
size: Int,
) -> String
fn extern inko_string_from_pointer(
state: Pointer[UInt8],
pointer: Pointer[UInt8],
) -> String
let TAB = 0x9
let LF = 0xA
let CR = 0xD
let SPACE = 0x20
let DQUOTE = 0x22
let BSLASH = 0x5C
let LOWER_B = 0x62
let LOWER_N = 0x6e
let LOWER_F = 0x66
let LOWER_R = 0x72
let LOWER_T = 0x74
# A table mapping bytes to their replacements for `String.escaped`.
let ESCAPE_TABLE = [
-1, -1, -1, -1, -1, -1,
-1, -1, LOWER_B, LOWER_T, LOWER_N, -1,
LOWER_F, LOWER_R, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, DQUOTE, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1,
-1, -1, BSLASH, -1, -1, -1,
]
fn whitespace?(byte: Int) -> Bool {
byte == TAB or byte == LF or byte == CR or byte == SPACE
}
fn padding(string: String, chars: Int, pad_to: Int) -> String {
if chars >= pad_to { return '' }
let pad_size = pad_to - chars
let pad_buf = StringBuffer.new
pad_size.times fn (_) { pad_buf.push(string) }
let mut pad = pad_buf.into_string
if pad.chars.count > pad_size {
# In case the `with` value contains multiple characters, we may need to
# truncate the padding to produce the correct final size.
pad.substring(start: 0, chars: pad_size)
} else {
pad
}
}
# A type that can be moved into a `String`.
trait pub IntoString {
# Moves `self` into a `String`.
fn pub move into_string -> String
}
# A type that can be converted to a `String`.
trait pub ToString {
# Converts `self` to a `String`.
fn pub to_string -> String
}
# A type that is a contiguous sequence of bytes.
#
# This type is useful for methods that need to operate on a sequence of bytes
# (e.g. by iterating over them), but don't care if the input is a `String` or
# `ByteArray`.
trait pub Bytes {
# Returns the byte at the given byte index.
#
# # Panics
#
# If the index is out of bounds, this method panics.
fn pub byte(index: Int) -> Int
# Returns an iterator over the bytes in `self`.
fn pub bytes -> Iter[Int]
# Returns the number of bytes in `self`.
fn pub size -> Int
# Slices `self` into a sub sequence of bytes, using a byte range.
fn pub slice(start: Int, size: Int) -> ByteArray
# Returns a raw pointer to the bytes of `self`
#
# This method is meant for FFI purposes, and use of it should be avoided at
# all costs.
fn pub to_pointer -> Pointer[UInt8]
}
# An UTF-8 encoded and immutable string type.
class builtin String {
# The size of the string in bytes, _excluding_ the trailing NULL byte.
let @size: UInt64
# A pointer to the bytes of this string, including the trailing NULL byte.
let @bytes: Pointer[UInt8]
# Returns a `String` created from the given NULL terminated pointer.
#
# The purpose of this method is to allow creating a `String` from a pointer
# returned by C code. While this method ensures the input is valid UTF-8, it
# may crash your program if given an invalid pointer (e.g. a NULL pointer).
#
# Do not use this method unless you have somehow verified that the pointer is
# a valid NULL terminated C string.
#
# # Examples
#
# String.from_pointer("hello".to_pointer) == "hello" # => true
fn pub static from_pointer(pointer: Pointer[UInt8]) -> String {
inko_string_from_pointer(_INKO.state, pointer)
}
# Return a `String` that contains the values of the iterator, separated by the
# value of the `with` argument.
#
# # Examples
#
# let vals = [10, 20, 30].into_iter
#
# String.join(vals, with: ',') => '10,20,30'
fn pub static join[T: ToString, I: Iter[T]](
iter: move I,
with: String,
) -> String {
let result = iter.reduce(StringBuffer.new) fn (buff, val) {
if buff.size > 0 { buff.push(with) }
buff.push(val.to_string)
buff
}
result.to_string
}
# Returns the uppercase equivalent of the current `String`.
#
# # Examples
#
# Converting a `String` containing only ASCII symbols:
#
# 'hello'.to_upper # => 'HELLO'
#
# Converting a `String` containing Unicode symbols:
#
# 'ä'.to_upper # => 'Ä'
#
# Converting a `String` containing both ASCII and Unicode symbols:
#
# 'aä'.to_upper # => 'AÄ'
fn pub to_upper -> String {
inko_string_to_upper(_INKO.state, self)
}
# Returns the lowercase equivalent of the current `String`.
#
# # Examples
#
# Converting a `String` containing only ASCII symbols:
#
# 'HELLO'.to_lower # => 'hello'
#
# Converting a `String` containing Unicode symbols:
#
# 'Ä'.to_lower # => 'ä'
#
# Converting a `String` containing both ASCII and Unicode symbols:
#
# 'AÄ'.to_lower # => 'aä'
fn pub to_lower -> String {
inko_string_to_lower(_INKO.state, self)
}
# Slices `self` into a substring, using a range of _characters_ and _not_
# bytes.
#
# Slicing a string allows one to extract a substring by providing a start
# position and the number of characters. If the index is out of bounds, an
# empty `String` is returned.
#
# # Examples
#
# 'hello_world'.substring(start: 0, chars: 5) # => 'hello'
# 'hello_world'.substring(start: 0, chars: 100) # => 'hello_world'
fn pub substring(start: Int, chars: Int) -> String {
let buff = StringBuffer.new
self.chars.each_with_index fn (index, char) {
if index >= start and buff.size < chars { buff.push(char) }
}
buff.into_string
}
# Slices `self` into a sequence of bytes using a _byte_ range, appending the
# bytes to `bytes` argument.
#
# This method is useful if you want to slice a `String` into a `ByteArray`,
# but wish to reuse the same `ByteArray` rather than allocating a new one for
# each slice. Unless you've determined you indeed need to reuse the same
# `ByteArray`, you're probably better off using `String.slice` instead.
#
# # Examples
#
# let bytes = ByteArray.new
#
# '😊'.slice_into(bytes, start: 0, size: 4)
#
# bytes # => '😊'.to_byte_array
fn pub slice_into(bytes: mut ByteArray, start: Int, size: Int) {
inko_string_slice_bytes_into(self, bytes, start, size)
}
# Returns the _byte_ index of the first occurrence of the given `String`,
# starting at the given byte index.
#
# # Examples
#
# 'hello'.byte_index(of: 'h', starting_at: 0) # => Option.Some(0)
# 'hello'.byte_index(of: 'l', starting_at: 0) # => Option.Some(2)
# 'hello'.byte_index(of: 'l', starting_at: 3) # => Option.Some(3)
# 'hello'.byte_index(of: 'x', starting_at: 0) # => Option.None
fn pub byte_index(of: String, starting_at: Int) -> Option[Int] {
# This is a naive string searching algorithm (see
# https://en.wikipedia.org/wiki/String-searching_algorithm) for more details
# on the various algorithms.
#
# We're using the naive algorithm because:
#
# 1. It's easy to implement
# 2. It doesn't require any pre-processing
# 3. At the time of writing there was no need for something more performant
let find_size = of.size
if find_size == 0 or size == 0 or find_size > size { return Option.None }
let mut a = starting_at
let max = size - find_size
while a <= max {
let mut b = 0
while b < find_size and byte(a + b) == of.byte(b) { b += 1 }
if b == find_size { return Option.Some(a) }
a += 1
}
Option.None
}
# Returns `true` if `self` starts with the given `String`.
#
# # Examples
#
# Checking if a `String` starts with another `String`:
#
# 'test_starts_with'.starts_with?('test_') # => true
# 'hello'.starts_with?('test_') # => false
fn pub starts_with?(prefix: String) -> Bool {
match byte_index(of: prefix, starting_at: 0) {
case Some(idx) -> idx == 0
case _ -> false
}
}
# Returns `true` if `self` ends with the given `String`.
#
# # Examples
#
# Checking if a `String` ends with another `String`:
#
# 'hello_world'.ends_with?('world') # => true
# 'hello'.ends_with?('world') # => false
fn pub ends_with?(suffix: String) -> Bool {
byte_index(of: suffix, starting_at: size - suffix.size).some?
}
# Splits `self` into an iterator of `Strings`, each separated by the given
# separator.
#
# # Examples
#
# Splitting a `String` using a single character as the separator:
#
# let iter = 'foo/bar/baz'.split('/')
#
# iter.next # => Option.Some('foo')
# iter.next # => Option.Some('bar')
#
# Splitting a `String` using multiple characters as the separator:
#
# let iter = 'foo::bar::baz'.split('::')
#
# iter.next # => Option.Some('foo')
# iter.next # => Option.Some('bar')
fn pub split(separator: String) -> Stream[String] {
let mut offset = 0
Stream.new fn move {
match byte_index(of: separator, starting_at: offset) {
case Some(at) -> {
let start = offset := at + separator.size
Option.Some(slice(start: start, size: at - start).into_string)
}
case _ if offset < size -> {
# No separator found, but we haven't reached the end of the String
# yet. In this case we return the remaining String.
let at = offset := size
Option.Some(slice(start: at, size: size - at).into_string)
}
case _ -> Option.None
}
}
}
# Returns `true` if `self` is an empty `String`.
#
# # Examples
#
# ''.empty? # => true
# 'foo'.empty? # => false
fn pub empty? -> Bool {
size == 0
}
# Returns a new `String` that is padded with another `String` until the given
# number of characters is reached.
#
# The padding is applied at the start of the new `String`.
#
# # Examples
#
# 'hello'.pad_start(with: ' ', chars: 7) # => ' hello'
# 'hello'.pad_start(with: ' ', chars: 5) # => 'hello'
fn pub pad_start(with: String, chars: Int) -> String {
padding(with, chars: self.chars.count, pad_to: chars) + self
}
# Returns a new `String` that is padded with another `String` until the given
# number of characters is reached.
#
# The padding is applied at the end of the new `String`.
#
# # Examples
#
# 'hello'.pad_end(with: ' ', chars: 7) # => 'hello '
# 'hello'.pad_end(with: ' ', chars: 5) # => 'hello'
fn pub pad_end(with: String, chars: Int) -> String {
self + padding(with, chars: self.chars.count, pad_to: chars)
}
# Returns a new `String` that contains `self` multiple times.
#
# # Examples
#
# 'a'.repeat(4) # => 'aaaa'
fn pub repeat(times: Int) -> String {
match times {
case 0 -> ''
case 1 -> self
case _ -> {
let buf = StringBuffer.new
times.times fn (_) { buf.push(clone) }
buf.into_string
}
}
}
# Returns an iterator over the characters (= extended grapheme clusters) in
# `self`.
#
# # Examples
#
# '😀😃'.chars.next # => Option.Some('😀 ')
fn pub chars -> Chars {
Chars { @string = self, @iter = inko_string_chars(self) }
}
# Returns a new `String` without the given prefix.
#
# # Examples
#
# 'xhellox'.strip_prefix('x') # => 'hellox'
fn pub strip_prefix(prefix: String) -> String {
if starts_with?(prefix).false? { return clone }
slice(start: prefix.size, size: size - prefix.size).into_string
}
# Returns a new `String` without the given suffix.
#
# # Examples
#
# 'xhellox'.strip_suffix('x') # => 'xhello'
fn pub strip_suffix(suffix: String) -> String {
if ends_with?(suffix).false? { return clone }
slice(start: 0, size: size - suffix.size).into_string
}
# Returns a new `String` without any leading whitespace.
#
# # Examples
#
# ' hello'.trim_start # => 'hello'
# "\thello".trim_start # => 'hello'
fn pub trim_start -> String {
let mut index = 0
let max = size
while index < max {
if whitespace?(byte(index)) { index += 1 } else { break }
}
slice(start: index, size: size - index).into_string
}
# Returns a new `String` without any trailing whitespace.
#
# # Examples
#
# 'hello '.trim_end # => 'hello'
# "hello\t".trim_end # => 'hello'
fn pub trim_end -> String {
let mut index = size - 1
while index >= 0 {
if whitespace?(byte(index)) { index -= 1 } else { break }
}
slice(start: 0, size: index + 1).into_string
}
# Returns a new `String` with both leading and trailing whitespace removed.
#
# # Examples
#
# ' hello '.trim # => 'hello'
# " hello\t".trim # => 'hello'
fn pub trim -> String {
let max = size
let mut start = 0
let mut end = max - 1
while start < max {
if whitespace?(byte(start)) { start += 1 } else { break }
}
while end >= 0 {
if whitespace?(byte(end)) { end -= 1 } else { break }
}
slice(start: start, size: end + 1 - start).into_string
}
# Returns a copy of `self` with all special characters escaped.
#
# The following characters are escaped:
#
# 1. Double quotes
# 1. Tabs
# 1. Newlines
# 1. Carriage returns
# 1. Backspace
# 1. Form feed
# 1. Backslash
#
# # Examples
#
# "hello\nworld" # => 'hello\nworld'
# "hello\\world" # => 'hello\\world'
fn pub escaped -> String {
let buff = ByteArray.new
let max = ESCAPE_TABLE.size
bytes.each fn (byte) {
if byte >= max {
buff.push(byte)
return
}
match ESCAPE_TABLE.get(byte) {
case -1 -> buff.push(byte)
case byte -> {
buff.push(BSLASH)
buff.push(byte)
}
}
}
buff.into_string
}
# Replaces all occurrences of `string` with the value in `with`, returning the
# result as a new `String`.
#
# If the `string` argument is an empty `String`, this method doesn't perform
# any replacements and instead returns a copy of `self`.
#
# # Examples
#
# 'foo foo'.replace('foo', with: 'bar') # => 'bar bar'
fn pub replace(string: String, with: String) -> String {
# Different languages handle the pattern being empty differently. For
# example, Javascript and Node only match the start of the string if the
# pattern is empty. Other languages such as Ruby and Python appear to inject
# the replacement in between every character, such that
# `'AB'.replace('', ',')` results in `,A,B,`.
#
# We make the decision to just _not_ do any replacements in this case, as
# replacing an empty string is nonsensical to begin with.
if string.size == 0 { return self }
let buf = ByteArray.new
let mut start = 0
let mut last = 0
loop {
match byte_index(string, start) {
case Some(i) -> {
if i > last { slice_into(buf, start: last, size: i - last) }
with.slice_into(buf, start: 0, size: with.size)
start = i + string.size
last = start
}
case _ -> {
if start < size { slice_into(buf, start, size) }
break
}
}
}
buf.into_string
}
fn byte_unchecked(index: Int) -> Int {
(@bytes as Int + index as Pointer[UInt8]).0 as Int
}
}
impl Bytes for String {
# Returns the byte at the given byte index.
#
# # Examples
#
# Obtaining a single byte from a `String`:
#
# 'inko'.byte(0) # => 105
#
# # Panics
#
# If the index is out of bounds, this method panics.
fn pub byte(index: Int) -> Int {
bounds_check(index, size)
byte_unchecked(index)
}
# Returns an iterator over the bytes in `self`.
fn pub bytes -> Stream[Int] {
let mut idx = 0
let max = size
Stream.new fn move {
if idx < max { Option.Some(byte(idx := idx + 1)) } else { Option.None }
}
}
# Returns the size of the `String` in bytes.
#
# # Examples
#
# Getting the byte size of a `String`:
#
# 'foo'.size # => 3
# '😀'.size # => 4
fn pub size -> Int {
@size as Int
}
# Slices `self` into a sequence of bytes using a _byte_ range.
#
# # Examples
#
# Slicing a string using a valid range:
#
# '😊'.slice_bytes(start: 0, size: 4) # => '😊'.to_byte_array
# '😊'.slice_bytes(start: 0, size: 3) # => "\u{FFFD}".to_byte_array
fn pub slice(start: Int, size: Int) -> ByteArray {
let bytes = ByteArray.new
slice_into(bytes, start, size)
bytes
}
# Returns a raw pointer to the bytes of `self`.
#
# This method is meant to be used when passing strings to foreign functions
# (i.e. `*char` arguments). You should avoid using it for anything else.
fn pub to_pointer -> Pointer[UInt8] {
@bytes
}
}
impl Contains[String] for String {
fn pub contains?(value: ref String) -> Bool {
byte_index(of: value, starting_at: 0).some?
}
}
impl Drop for String {
fn mut drop {
inko_string_drop(self)
}
}
impl ToByteArray for String {
fn pub to_byte_array -> ByteArray {
inko_string_to_byte_array(_INKO.state, self)
}
}
impl IntoByteArray for String {
fn pub move into_byte_array -> ByteArray {
to_byte_array
}
}
impl Clone[String] for String {
fn pub clone -> String {
self
}
}
impl ToString for String {
fn pub to_string -> String {
clone
}
}
impl IntoString for String {
fn pub move into_string -> String {
self
}
}
impl Equal[ref String] for String {
# Returns `true` if the current `String` and `other` are equal to each other.
#
# # Examples
#
# Returns `true` if two Strings are equal:
#
# 'foo' == 'foo' # => true
#
# Returns `false` if two Strings are not equal:
#
# 'foo' == 'bar' # => false
fn pub ==(other: ref String) -> Bool {
let size = self.size
if size != other.size { return false }
let mut idx = 0
while idx < size {
if byte_unchecked(idx) != other.byte_unchecked(idx) { return false }
idx += 1
}
true
}
}
impl Hash for String {
fn pub hash[H: mut + Hasher](hasher: mut H) {
let mut index = 0
while index < size {
hasher.write(byte_unchecked(index))
index += 1
}
}
}
impl Add[String, String] for String {
# Concatenates `self` and the given `String`, returning a new `String`.
#
# # Examples
#
# 'hello ' + 'world' # => 'hello world'
fn pub +(other: ref String) -> String {
_INKO.string_concat(self, other)
}
}
impl ToPath for String {
fn pub to_path -> Path {
Path.new(clone)
}
}
impl IntoPath for String {
fn pub move into_path -> Path {
Path.new(self)
}
}
impl Format for String {
fn pub fmt(formatter: mut Formatter) {
formatter.write('"')
formatter.write(escaped)
formatter.write('"')
}
}
# An iterator over the characters (= extended grapheme clusters) in a String.
#
# The exact number of grapheme clusters a `String` contains may change over time
# as the Unicode specification changes. If you want to index into a `String` in
# a stable way, it's best to calculate the character index, then translate that
# to a more stable index such as the code point index, or the byte index.
class pub Chars {
# The String we're iterating over.
#
# We need to maintain a reference to the String, otherwise the underlying
# native iterator would be invalidated.
let @string: String
# The native iterator provided by the VM.
let @iter: Pointer[UInt8]
}
impl Iter[String] for Chars {
fn pub mut next -> Option[String] {
match inko_string_chars_next(_INKO.state, @iter) {
case { @tag = 0, @value = v } -> Option.Some(v)
case _ -> Option.None
}
}
}
impl Drop for Chars {
fn mut drop {
inko_string_chars_drop(@iter)
}
}
# A buffer for efficiently concatenating `String` objects together.
#
# When concatenating multiple `String` objects together, intermediate `String`
# objects are created. For example:
#
# 'foo' + 'bar' + 'baz'
#
# This code will allocate three `String` objects (for the `String` literals),
# and two additional `String` objects. This is the result of the above
# expression being evaluated as follows:
#
# ('foo' + 'bar') + 'baz'
#
# This means that the first allocated `String` resulting from this expression
# is `'foobar'`, which is then concatenated with `'baz'`, producing
# `'foobarbaz'`.
#
# Using a `StringBuffer` we can work around this, only allocating a `String`
# once we are done:
#
# import std.string.StringBuffer
#
# let buffer = StringBuffer.new
#
# buffer.push('foo')
# buffer.push('bar')
# buffer.push('baz')
#
# buffer.to_string # => 'foobarbaz'
#
# You can also create a `StringBuffer` and feed it values right away:
#
# import std.string.StringBuffer
#
# let buffer = StringBuffer.from_array(['foo', 'bar', 'baz'])
#
# buffer.to_string # => 'foobarbaz'
class pub StringBuffer {
let @strings: Array[String]
# Returns a new empty `StringBuffer`.
fn pub static new -> StringBuffer {
StringBuffer { @strings = [] }
}
# Returns a new `StringBuffer` from an existing `Array`.
#
# # Examples
#
# Creating a `StringBuffer` from an `Array`:
#
# import std.string.StringBuffer
#
# let strings = ['foo', 'bar']
#
# StringBuffer.from_array(strings).to_string # => 'foobar'
fn pub static from_array(strings: Array[String]) -> StringBuffer {
StringBuffer { @strings = strings }
}
# Adds the given `String` to the buffer.
#
# # Examples
#
# Adding a `String` to a `StringBuffer`:
#
# import std.string.StringBuffer
#
# let buffer = StringBuffer.new
#
# buffer.push('hello') # => 'hello'
fn pub mut push(string: String) {
@strings.push(string)
}
# Returns the number of values in `self`.
fn pub size -> Int {
@strings.size
}
}
impl ToString for StringBuffer {
# Generates a `String` using the current contents of the buffer.
#
# # Examples
#
# Converting a `StringBuffer` to a `String`:
#
# import std.string.StringBuffer
#
# let buffer = StringBuffer.new
#
# buffer.push('hello ')
# buffer.push('world')
#
# buffer.to_string # => 'hello world'
fn pub to_string -> String {
inko_string_concat(_INKO.state, @strings.to_pointer, @strings.size)
}
}
impl IntoString for StringBuffer {
fn pub move into_string -> String {
to_string
}
}