First Draft: Coroutines

Richard Andrew Cattermole (Rikki) richard at cattermole.co.nz
Mon Aug 5 01:36:31 UTC 2024


Coroutines is a stack machine transformed representation for a 
function. It enables storing the state of a function externally 
to the stack to allow for high throughput event handling.

Latest: 
https://gist.github.com/rikkimax/fe2578e1dfbf66346201fd191db4bdd4

Current: 
https://gist.github.com/rikkimax/fe2578e1dfbf66346201fd191db4bdd4/0bb4442c092e061d520c35a43278f0819666f26f

It uses the ``@async`` attribute to transform into a type that is 
used to describe the function, with the help of implicit 
conversions using knowable library types and a hook for 
construction to produce a library object that represents the 
function.

There is support for such UDA's as ``@Route`` to make the 
function automatically marked as ``@async`` to prevent explicit 
annotation requirement.

An example usage of one:

```d
void clientCO(Socket socket) @async {
	writeln("Connection has been made");

	socket.write("GET / HTTP/1.1\r\n");
	socket.write("Accept-Encoding: identity\r\n");
	socket.write("\r\n");

	while(Future!string readLine = socket.readUntil("\n")) {
		if (!readLine.isComplete) {
			writeln("Not alive and did not get a result");
			return;
		}
		
		string result = readLine.result;
		writeln(result);

		if (result == "</html>") {
			writeln("Saw end of expected input");
			return;
		}
	}
}
```


More information about the dip.development mailing list