Created
May 9, 2017 17:20
-
-
Save yshui/716cfe987c89997760cabc2c951ca430 to your computer and use it in GitHub Desktop.
Turn struct with opApply into ranages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct applyRange(T, ElemType) { | |
| import core.thread; | |
| private { | |
| class rangeFiber : Fiber { | |
| ElemType *tmp = null; | |
| T r; | |
| this(T r) { | |
| this.r = r; | |
| super(&work); | |
| } | |
| int dg(ref ElemType x) { | |
| tmp = &x; | |
| f.yield(); | |
| return 0; | |
| } | |
| void work() { | |
| r.opApply(&dg); | |
| tmp = null; | |
| } | |
| } | |
| rangeFiber f; | |
| } | |
| this(T r) { | |
| f = new rangeFiber(r); | |
| f.call(); | |
| } | |
| ref ElemType front() { | |
| return *f.tmp; | |
| } | |
| void popFront() { | |
| f.call(); | |
| } | |
| bool empty() { | |
| return f.tmp is null; | |
| } | |
| } | |
| struct Iter { | |
| int opApply(int delegate(ref int x) dg) { | |
| foreach(i; 0..10) | |
| dg(i); | |
| return 0; | |
| } | |
| } | |
| void main() { | |
| import std.stdio; | |
| Iter i; | |
| auto x = applyRange!(Iter, int)(i); | |
| foreach(y; x) | |
| writeln(y); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment