CBOE Emulator  1.0
cli.hpp
1 // A template-based asynchronous command line interface based on asio.
2 // Copyright 2020 Christian Kauten
3 //
4 // Author: Christian Kauten (kautenja@auburn.edu)
5 //
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16 //
17 
18 #ifndef CLI_HPP
19 #define CLI_HPP
20 
21 #include <asio.hpp>
22 #include <iostream>
23 
27 template<typename CommandHandler>
28 class CLI {
29  private:
31  static constexpr int BUFFER_SIZE = 1024;
33  asio::io_context& context;
35  asio::posix::stream_descriptor input_stream;
37  asio::streambuf input_buffer;
39  CommandHandler& handler;
40 
42  void read_command_line() {
43  asio::async_read_until(input_stream, input_buffer, '\n',
44  [&](const std::error_code& error, std::size_t length){
45  if (error) { // TODO: handle error
46  std::cout << "CLI::read_command_line - " << error << std::endl;
47  return;
48  }
49  // get the data from the buffer
50  auto data = asio::buffers_begin(input_buffer.data());
51  // convert the data to string and parse the command
52  handler.parse(std::string(data, data + length));
53  // consume the data from the input buffer
54  input_buffer.consume(length);
55  // read another line from the console
56  read_command_line();
57  }
58  );
59  }
60 
61  public:
67  CLI(asio::io_context& context_, CommandHandler& handler_) :
68  context(context_),
69  input_stream(context, ::dup(STDIN_FILENO)),
70  input_buffer(BUFFER_SIZE),
71  handler(handler_) { read_command_line(); }
72 };
73 
74 #endif // CLI_HPP
CLI::CLI
CLI(asio::io_context &context_, CommandHandler &handler_)
Initialize a new command line interface.
Definition: cli.hpp:67
CLI
A template-based asynchronous command line interface based on asio.
Definition: cli.hpp:28