summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOri Bernstein <ori@eigenstate.org>2016-05-02 11:23:55 -0700
committerOri Bernstein <ori@eigenstate.org>2016-05-02 11:25:04 -0700
commite29104d6edc5f4a756db90d9b31428192db99f9e (patch)
tree221db601669716e4b89309eea6a1f390ecdbfe6e
parentbf6a03689f1e9f9a50ed1a9316dbfc058365143b (diff)
downloadmc-e29104d6edc5f4a756db90d9b31428192db99f9e.tar.gz
Add 'splititer' string iterator.
-rw-r--r--lib/std/striter.myr34
-rw-r--r--lib/std/test/striter.myr19
2 files changed, 53 insertions, 0 deletions
diff --git a/lib/std/striter.myr b/lib/std/striter.myr
index 6527b8a..2d6db55 100644
--- a/lib/std/striter.myr
+++ b/lib/std/striter.myr
@@ -1,15 +1,24 @@
use "die"
use "types"
use "utf"
+use "strfind"
+use "option"
pkg std =
type chariter = struct
rest : byte[:]
;;
+ type splititer = struct
+ rest : byte[:]
+ split : byte[:]
+ ;;
+
impl iterable chariter -> char
+ impl iterable splititer -> byte[:]
const bychar : (str : byte[:] -> chariter)
+ const bysplit : (str : byte[:], split : byte[:] -> splititer)
;;
impl iterable chariter -> char =
@@ -29,3 +38,28 @@ const bychar = {str
-> [.rest = str]
}
+impl iterable splititer -> byte[:] =
+ __iternext__ = {si, sp
+ match std.strfind(si.rest, si.split)
+ | `Some off:
+ sp# = si.rest[:off]
+ si.rest = si.rest[off + si.split.len:]
+ -> true
+ | `None:
+ if si.rest.len > 0
+ sp# = si.rest
+ si.rest = ""
+ -> true
+ ;;
+ ;;
+ -> false
+ }
+
+ __iterfin__ = {ci, c
+ }
+;;
+
+const bysplit = {str, split
+ -> [.rest = str, .split = split]
+}
+
diff --git a/lib/std/test/striter.myr b/lib/std/test/striter.myr
new file mode 100644
index 0000000..2684f8d
--- /dev/null
+++ b/lib/std/test/striter.myr
@@ -0,0 +1,19 @@
+use std
+
+const main = {
+ var chars = ['a', 'b', 'c']
+ var splits = ["foo", "+bar"]
+ var i
+
+ i = 0
+ for c in std.bychar("abc")
+ std.assert(chars[i++] == c, "wrong char")
+ ;;
+ std.assert(i == chars.len, "wrong split count")
+
+ i = 0
+ for sp in std.bysplit("foo+++bar", "++")
+ std.assert(std.streq(splits[i++], sp), "wrong split {}", sp)
+ ;;
+ std.assert(i == splits.len, "wrong split count")
+}