aboutsummaryrefslogtreecommitdiff
path: root/works/life/computer-network-experiment/Output.cpp
blob: e3dc69e5c5d2cb6bf8a2aeed4b1023cd3e376b76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "Output.h"

#include <folly/CancellationToken.h>

#include <ostream>
#include <type_traits>

folly::MPMCQueue<Output> output_queue(100);

folly::CancellationSource cancellation_source;

std::thread output_thread(OutputThread);

void PrintOutput(const Output &output) {
  std::basic_ostream<Char> *stream;

  switch (output.type) {
  case OutputType::Error:
    stream = &error_stream;
    break;
  default:
    stream = &output_stream;
    break;
  }

  switch (output.color) {
  case OutputColor::Normal:
    (*stream) << output.message;
    break;
  case OutputColor::Green:
    (*stream) << CRUT("\x1b[32m") << output.message << CRUT("\x1b[0m");
    break;
  case OutputColor::Red:
    (*stream) << CRUT("\x1b[31m") << output.message << CRUT("\x1b[0m");
    break;
  case OutputColor::Yellow:
    (*stream) << CRUT("\x1b[33m") << output.message << CRUT("\x1b[0m");
    break;
  }
}

void OutputThread() {
  while (true) {
    if (cancellation_source.getToken().isCancellationRequested()) {
      while (true) {
        Output output;
        if (output_queue.readIfNotEmpty(output)) {
          PrintOutput(output);
        } else {
          return;
        }
      }
    }

    Output output;
    if (output_queue.readIfNotEmpty(output))
      PrintOutput(output);
  }
}

void SignalAndWaitForOutputThreadStop() {
  cancellation_source.requestCancellation();
  output_thread.join();
}