]> git.ipfire.org Git - thirdparty/vala.git/commitdiff
tests: Add async generator example to cover an edge case
authorRico Tzschichholz <ricotz@ubuntu.com>
Sun, 2 Oct 2016 15:28:37 +0000 (17:28 +0200)
committerRico Tzschichholz <ricotz@ubuntu.com>
Sun, 2 Oct 2016 15:28:37 +0000 (17:28 +0200)
https://bugzilla.gnome.org/show_bug.cgi?id=763345

tests/Makefile.am
tests/asynchronous/generator.vala [new file with mode: 0644]

index 0fd49d9fa02b4b71889a8bb292ecb9ea9a209c02..8ff0f3da33cd663ebb9e3a1ec4f5bb639c5452b6 100644 (file)
@@ -208,6 +208,7 @@ TESTS = \
        asynchronous/bug661961.vala \
        asynchronous/bug742621.vala \
        asynchronous/closures.vala \
+       asynchronous/generator.vala \
        asynchronous/yield.vala \
        dbus/basic-types.test \
        dbus/arrays.test \
diff --git a/tests/asynchronous/generator.vala b/tests/asynchronous/generator.vala
new file mode 100644 (file)
index 0000000..f31e12a
--- /dev/null
@@ -0,0 +1,60 @@
+// This is based on Luca Bruno's Generator. It illustrates using async methods
+// to emulate a generator style of iterator coding. Note that this runs fine
+// without a main loop.
+
+abstract class Generator<G> {
+       bool consumed;
+       unowned G value;
+       SourceFunc callback;
+
+       public Generator () {
+               helper.begin ();
+       }
+
+       async void helper () {
+               yield generate ();
+               consumed = true;
+       }
+
+       protected abstract async void generate ();
+
+       protected async void feed (G value) {
+               this.value = value;
+               this.callback = feed.callback;
+               yield;
+       }
+
+       public bool next () {
+               return !consumed;
+       }
+
+       public G get () {
+               var result = value;
+               callback ();
+               return result;
+       }
+
+       public Generator<G> iterator () {
+               return this;
+       }
+}
+
+class IntGenerator : Generator<int> {
+       protected override async void generate () {
+               for (int i = 0; i < 10; i++) {
+                        if (i % 2 == 0)
+                               yield feed (i);
+               }
+       }
+}
+
+void main () {
+       var gen = new IntGenerator ();
+       string result = "";
+
+       foreach (var item in gen)
+               result += "%i ".printf (item);
+
+       assert (result == "0 2 4 6 8 ");
+}
+