commit 9ab47de0abbc69e30d8b5039e919b6c0937fdbda
parent e55a8339c2baca8c33a20b543cba5910b95ffa3c
Author: Bor Grošelj Simić <bor.groseljsimic@telemach.net>
Date: Mon, 22 Feb 2021 20:46:19 +0100
strings/iter.ha: add strings::iter_reverse()
Diffstat:
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/strings/iter.ha b/strings/iter.ha
@@ -6,12 +6,22 @@ export type iterator = struct {
push: (rune | void),
};
-// Initializes a string iterator.
+// Initializes a string iterator, starting at the beginning of the string.
export fn iter(src: str) iterator = iterator {
dec = utf8::decode(src),
push = void,
};
+// Initializes a string iterator, starting at the end of the string.
+export fn iter_reverse(src: str) iterator = {
+ let ret = iterator {
+ dec = utf8::decode(src),
+ push = void,
+ };
+ ret.dec.offs = len(src);
+ return ret;
+};
+
// Get the next rune from an iterator, or void if there are none left.
export fn next(iter: *iterator) (rune | void) = {
match (iter.push) {
@@ -80,4 +90,15 @@ export fn iter_str(iter: *iterator) str = {
push(&s, 'q');
assert(next(&s) as rune == 'q');
assert(prev(&s) as rune == 'は');
+
+ s = iter_reverse("にちは");
+ const expected3 = ['は', 'ち', 'に'];
+ for (let i = 0z; i< len(expected3); i += 1) {
+ match (prev(&s)) {
+ r: rune => assert(r == expected3[i]),
+ void => abort(),
+ };
+ };
+ assert(prev(&s) is void);
+ assert(next(&s) as rune == 'に');
};