PageRenderTime 21ms CodeModel.GetById 1ms app.highlight 8ms RepoModel.GetById 2ms app.codeStats 0ms

/mordor/tests/coroutine.cpp

http://github.com/mozy/mordor
C++ | 65 lines | 56 code | 8 blank | 1 comment | 10 complexity | ce9f963a3aaf98a21fee46b51fd9cbba MD5 | raw file
 1// Copyright (c) 2009 - Mozy, Inc.
 2
 3#include "mordor/coroutine.h"
 4#include "mordor/test/test.h"
 5
 6using namespace Mordor;
 7using namespace Mordor::Test;
 8
 9static void countTo5(Coroutine<int> &self)
10{
11    self.yield(1);
12    self.yield(2);
13    self.yield(3);
14    self.yield(4);
15    self.yield(5);
16}
17
18MORDOR_UNITTEST(Coroutine, basic)
19{
20    Coroutine<int> coro(&countTo5);
21    int sequence = 0;
22    MORDOR_TEST_ASSERT_EQUAL(coro.state(), Fiber::INIT);
23    int value;
24    while (true) {
25        value = coro.call();
26        if (coro.state() == Fiber::TERM)
27            break;
28        MORDOR_TEST_ASSERT_EQUAL(value, ++sequence);
29    }
30    MORDOR_TEST_ASSERT_EQUAL(value, 0);
31    MORDOR_TEST_ASSERT_EQUAL(sequence, 5);
32}
33
34static void echo(Coroutine<int, int> &self, int arg)
35{
36    while (arg <= 5) {
37        arg = self.yield(arg);
38    }
39}
40
41MORDOR_UNITTEST(Coroutine, basicWithArg)
42{
43    Coroutine<int, int> coro(&echo);
44    MORDOR_TEST_ASSERT_EQUAL(coro.state(), Fiber::INIT);
45    for (int i = 0; i <= 5; ++i) {
46        MORDOR_TEST_ASSERT(coro.state() == Fiber::INIT || coro.state() == Fiber::HOLD);
47        MORDOR_TEST_ASSERT_EQUAL(coro.call(i), i);
48    }
49}
50
51static void countTo5Arg(Coroutine<void, int> &self, int arg)
52{
53    int sequence = 0;
54    for (int i = 0; i < 5; ++i) {
55        MORDOR_TEST_ASSERT_EQUAL(arg, sequence++);
56        arg = self.yield();
57    }
58}
59
60MORDOR_UNITTEST(Coroutine, voidWithArg)
61{
62    Coroutine<void, int> coro(&countTo5Arg);
63    for (int i = 0; i < 5; ++i)
64        coro.call(i);
65}