summaryrefslogtreecommitdiff
path: root/lib/std/striter.myr
blob: 0dd1b022874d6b1d7b83ebb70750095128a6a105 (plain)
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
use "die"
use "types"
use "utf"
use "strfind"
use "option"

pkg std =
	type chariter = struct
		rest	: byte[:]
	;;

	type charoffiter = struct
		str	: byte[:]
		idx	: size
	;;

	type splititer = struct
		rest	: byte[:]
		split	: byte[:]
	;;

	impl iterable chariter	-> char
	impl iterable charoffiter	-> (char, size)
	impl iterable splititer -> byte[:]

	const bychar	: (str : byte[:] -> chariter)
	const bycharoff	: (str : byte[:] -> charoffiter)
	const bysplit	: (str : byte[:], split : byte[:] -> splititer)
;;

impl iterable chariter -> char =
	__iternext__ = {ci, c
		if ci.rest.len == 0
			-> false
		;;
		(c#, ci.rest) = charstep(ci.rest)
		-> true
	}

	__iterfin__ = {ci, c
	}
;;

const bychar = {str
	-> [.rest = str]
}


impl iterable charoffiter -> (char, size) = 
	__iternext__ = {ci, cv
		var c

		if ci.idx == ci.str.len
			-> false
		;;
		c = std.decode(ci.str[ci.idx:])
		ci.idx += std.charlen(c)
		cv# = (c, ci.idx)
		-> true
	}

	__iterfin__ = {ci, c
	}
;;

const bycharoff = {s
	-> [.str=s, .idx=0]
}

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]
}