feat: make String iterable over code points with iterate/iteratorValue primitives
Add String as a subclass of Sequence in core.wren and implement the iterator protocol for strings in wren_core.c. The string_iterate native advances through UTF-8 code point boundaries, while string_iteratorValue extracts the full code point at a given byte index. Includes comprehensive test coverage for iteration, edge cases (empty strings, mid-sequence positions), and error handling for invalid iterator types and out-of-bounds indices. Also updates documentation for String, List, and Sequence classes with iterator protocol details and usage examples.
This commit is contained in:
@@ -4,6 +4,9 @@ IO.print(a.iterate(0)) // expect: 1
|
||||
IO.print(a.iterate(1)) // expect: 2
|
||||
IO.print(a.iterate(2)) // expect: 3
|
||||
IO.print(a.iterate(3)) // expect: false
|
||||
|
||||
// Out of bounds.
|
||||
IO.print(a.iterate(123)) // expect: false
|
||||
IO.print(a.iterate(-1)) // expect: false
|
||||
|
||||
// Nothing to iterate in an empty list.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
var s = "abçd"
|
||||
IO.print(s.iterate(null)) // expect: 0
|
||||
IO.print(s.iterate(0)) // expect: 1
|
||||
IO.print(s.iterate(1)) // expect: 2
|
||||
// Skip 3 because that's the middle of the ç sequence.
|
||||
IO.print(s.iterate(2)) // expect: 4
|
||||
// Iterating from the middle of a UTF-8 sequence goes to the next one.
|
||||
IO.print(s.iterate(3)) // expect: 4
|
||||
IO.print(s.iterate(4)) // expect: false
|
||||
|
||||
// Out of bounds.
|
||||
IO.print(s.iterate(123)) // expect: false
|
||||
IO.print(s.iterate(-1)) // expect: false
|
||||
|
||||
// Nothing to iterate in an empty string.
|
||||
IO.print("".iterate(null)) // expect: false
|
||||
@@ -0,0 +1 @@
|
||||
"s".iterate(1.5) // expect runtime error: Iterator must be an integer.
|
||||
@@ -0,0 +1 @@
|
||||
"s".iterate("2") // expect runtime error: Iterator must be a number.
|
||||
@@ -0,0 +1,7 @@
|
||||
var s = "abçd"
|
||||
IO.print(s.iteratorValue(0)) // expect: a
|
||||
IO.print(s.iteratorValue(1)) // expect: b
|
||||
IO.print(s.iteratorValue(2)) // expect: ç
|
||||
// Iterator value in middle of UTF sequence is an empty string.
|
||||
IO.print(s.iteratorValue(3) == "") // expect: true
|
||||
IO.print(s.iteratorValue(4)) // expect: d
|
||||
@@ -0,0 +1 @@
|
||||
"s".iteratorValue(1.5) // expect runtime error: Iterator must be an integer.
|
||||
@@ -0,0 +1 @@
|
||||
"s".iteratorValue("2") // expect runtime error: Iterator must be a number.
|
||||
@@ -0,0 +1 @@
|
||||
"123".iteratorValue(4) // expect runtime error: Iterator out of bounds.
|
||||
@@ -0,0 +1 @@
|
||||
"123".iteratorValue(-5) // expect runtime error: Iterator out of bounds.
|
||||
Reference in New Issue
Block a user