source: tests/coroutine/devicedriver.cfa@ 1097bb7

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 1097bb7 was 7cfd6d4, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

illustrate coroutine refactoring

  • Property mode set to 100644
File size: 2.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// devicedriver.cfa --
8//
9// Author : Peter A. Buhr
10// Created On : Sat Mar 16 15:30:34 2019
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Mar 19 15:59:06 2019
13// Update Count : 87
14//
15
16#include <fstream.hfa>
17#include <coroutine.hfa>
18
19enum Status { CONT, MSG, ESTX, ELNTH, ECRC };
20coroutine Driver {
21 Status status;
22 char * msg, byte;
23}; // Driver
24
25void ?{}( Driver & d, char * m ) { d.msg = m; }
26Status next( Driver & d, char b ) with( d ) {
27 byte = b; resume( d ); return status;
28} // next
29
30void checkCRC( Driver & d, unsigned int sum ) with( d ) {
31 suspend();
32 unsigned short int crc = byte << 8; // sign extension over written
33 suspend();
34 // prevent sign extension for signed char
35 status = (crc | (unsigned char)byte) == sum ? MSG : ECRC;
36} // checkCRC
37
38void main( Driver & d ) with( d ) {
39 enum { STX = '\002', ESC = '\033', ETX = '\003', MaxMsg = 64 };
40 msg: for () { // parse message
41 status = CONT;
42 unsigned int lnth = 0, sum = 0;
43 while ( byte != STX ) suspend();
44 emsg: for () {
45 suspend();
46 choose ( byte ) { // process byte
47 case STX:
48 status = ESTX; suspend(); continue msg;
49 case ETX:
50 break emsg;
51 case ESC:
52 suspend();
53 } // choose
54 if ( lnth >= MaxMsg ) { // buffer full ?
55 status = ELNTH; suspend(); continue msg;
56 } // if
57 msg[lnth++] = byte;
58 sum += byte;
59 } // for
60 msg[lnth] = '\0'; // terminate string
61 checkCRC( d, sum ); // refactor CRC check
62 suspend();
63 } // for
64} // main
65
66int main() {
67 char msg[65], byte;
68 Driver driver = { msg };
69 eof: for () { // read until end of file
70 sin | byte; // read one character
71 if ( eof( sin ) ) break eof; // eof ?
72 choose( next( driver, byte ) ) { // analyse character
73 case MSG:
74 sout | "msg:" | msg;
75 case ESTX:
76 sout | "STX in message";
77 case ELNTH:
78 sout | "message too long";
79 case ECRC:
80 sout | "CRC failure";
81 default: ;
82 } // choose
83 } // for
84} // main
85
86// Local Variables: //
87// tab-width: 4 //
88// compile-command: "cfa -g -Wall -Wextra devicedriver.cfa" //
89// End: //
Note: See TracBrowser for help on using the repository browser.