Skip to content

Commit 5c4aadf

Browse files
committed
[examples/echo.c3] inline client() function as lambda
1 parent 6682732 commit 5c4aadf

File tree

1 file changed

+27
-29
lines changed

1 file changed

+27
-29
lines changed

examples/echo.c3

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,6 @@ import std::io;
44
import std::net;
55
import coroutine;
66

7-
fn void client(void *arg) {
8-
io::printfn("[%d] Client connected!", coroutine::id());
9-
10-
TcpSocket* client_sock = (TcpSocket*)arg;
11-
char[] buf = mem::new_array(char, 1024);
12-
defer {
13-
client_sock.close()!!;
14-
free(client_sock);
15-
free(buf.ptr);
16-
}
17-
18-
while OUTER: (true) {
19-
coroutine::sleep_read(client_sock.sock);
20-
usz n = client_sock.read(buf)!!;
21-
if (n == 0) break OUTER;
22-
char[] chunk = buf[0:n];
23-
io::printfn("[%d] Client sent %d bytes", coroutine::id(), chunk.len);
24-
25-
while (chunk.len > 0) {
26-
coroutine::sleep_write(client_sock.sock);
27-
usz m = client_sock.write(chunk)!!;
28-
if (m == 0) break OUTER;
29-
chunk = chunk[m..];
30-
}
31-
}
32-
io::printfn("[%d] Client disconnected", coroutine::id());
33-
}
34-
357
fn void main() {
368
coroutine::init();
379

@@ -45,6 +17,32 @@ fn void main() {
4517
coroutine::sleep_read(server_sock.sock);
4618
TcpSocket client_sock = tcp::accept(&server_sock)!!;
4719
client_sock.sock.set_non_blocking(true)!!;
48-
coroutine::go(&client, @clone(client_sock));
20+
coroutine::go(fn void(void *arg) {
21+
io::printfn("[%d] Client connected!", coroutine::id());
22+
23+
TcpSocket* client_sock = (TcpSocket*)arg;
24+
char[] buf = mem::new_array(char, 1024);
25+
defer {
26+
client_sock.close()!!;
27+
free(client_sock);
28+
free(buf.ptr);
29+
}
30+
31+
while OUTER: (true) {
32+
coroutine::sleep_read(client_sock.sock);
33+
usz n = client_sock.read(buf)!!;
34+
if (n == 0) break OUTER;
35+
char[] chunk = buf[0:n];
36+
io::printfn("[%d] Client sent %d bytes", coroutine::id(), chunk.len);
37+
38+
while (chunk.len > 0) {
39+
coroutine::sleep_write(client_sock.sock);
40+
usz m = client_sock.write(chunk)!!;
41+
if (m == 0) break OUTER;
42+
chunk = chunk[m..];
43+
}
44+
}
45+
io::printfn("[%d] Client disconnected", coroutine::id());
46+
}, @clone(client_sock));
4947
}
5048
}

0 commit comments

Comments
 (0)