#pragma once #include #include #include namespace Bilicraft { // Incremental input with no wait for a user, a writer, or a complete line. // The caller must be the sole reader of fd (including its duplicated descriptors) // and must keep it open. This class never closes fd or changes its flags/mode. // Do not mix it with std::cin/getline: their buffering can read ahead. // // POSIX supports canonical terminals, pipes and ordinary files. Windows supports // redirected pipes and ordinary files; native consoles/other handle types fail // explicitly rather than falling back to a potentially blocking cooked read. class TerminalInput { public: static constexpr std::size_t MaxLineBytes = 64 * 1024; TerminalInput(); explicit TerminalInput(int fd); TerminalInput(const TerminalInput &) = delete; TerminalInput &operator=(const TerminalInput &) = delete; // Consumes at most one line, stopping at its LF without reading the next // byte. nullopt means not ready, a partial line, or EOF (see IsEof()). Work // per call is bounded, so long lines may need several calls even from files. // A final nonempty line without LF is returned once, with IsEof() == true. // CR immediately before LF is removed; other CR bytes are preserved. // Up to MaxLineBytes bytes before LF are accepted (including any CR). // I/O/unsupported errors throw std::runtime_error once; overlong lines throw // std::length_error once. Both discard the partial line and latch EOF. std::optional PollLine(); bool IsEof() const; bool IsInteractive() const; private: enum class ReadResult { NotReady, Byte, End }; ReadResult ReadByte(char &byte); [[noreturn]] void Fail(const std::string &message); std::string TakeLine(bool removeCr); int fd; bool interactive; bool eof = false; std::string partial; }; } // namespace Bilicraft