aboutsummaryrefslogtreecommitdiff
path: root/store/works/life/computer-network-experiment/IO.h
blob: 1658b78ee490050169d75eceb740022edc5b7cab (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
65
66
67
68
#pragma once
#include "Common.h"
#include "StringUtil.hpp"

#include <fmt/format.h>
#include <folly/CancellationToken.h>
#include <folly/MPMCPipeline.h>
#include <folly/MPMCQueue.h>

#include <iostream>
#include <thread>

enum class OutputType { Normal, Error };
enum class OutputColor { Normal, Green, Red, Yellow };

struct Output {
  Output() = default;
  Output(String message, OutputType type = OutputType::Normal)
      : message(std::move(message)), type(type),
        color(type == OutputType::Error ? OutputColor::Red
                                        : OutputColor::Normal) {}

  Output(String message, OutputColor color)
      : message(std::move(message)), type(OutputType::Normal), color(color) {}

  Output(String message, OutputType type, OutputColor color)
      : message(std::move(message)), type(type), color(color) {}

  CRU_DEFAULT_COPY(Output)
  CRU_DEFAULT_MOVE(Output)
  ~Output() = default;

  String message;
  OutputType type;
  OutputColor color;
};

extern folly::MPMCQueue<Output> output_queue;

inline void SendOutput(Output output) {
  output_queue.blockingWrite(std::move(output));
}

inline void SendOutput(String output) { SendOutput(Output{std::move(output)}); }

template <typename... Args> void SendOutput(StringView format, Args &&...args) {
  output_queue.blockingWrite(fmt::format(format, std::forward<Args>(args)...));
}

template <typename... Args>
void SendOutput(OutputType type, StringView format, Args &&...args) {
  output_queue.blockingWrite(
      Output{fmt::format(format, std::forward<Args>(args)...), type});
}

template <typename... Args>
void SendOutput(OutputColor color, StringView format, Args &&...args) {
  output_queue.blockingWrite(
      Output{fmt::format(format, std::forward<Args>(args)...), color});
}

void SignalAndWaitForOutputThreadStop();

void OnInputLine(StringView line);

void StartIOThread();

String ReadInputLine();