/** This file is a part of rexy's general purpose library Copyright (C) 2022 rexy712 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef REXY_DETAIL_FORMAT_OUTPUT_BUFFER_HPP #define REXY_DETAIL_FORMAT_OUTPUT_BUFFER_HPP #include //size_t #include //fputc, FILE #include //fputwc #include "format_error.hpp" namespace rexy::fmt::detail{ //polymorphic buffer of which a reference can be passed around to prevent //passing around multiple output iterator types template class format_output_buffer_base { public: using value_type = Char; protected: static constexpr std::size_t s_bufsize = 256; protected: Char m_data[s_bufsize]; std::size_t m_size = 0; std::size_t m_written_count = 0; public: format_output_buffer_base(void) = default; virtual ~format_output_buffer_base(void) = default; virtual std::size_t write_out(void) = 0; void clear(void); void push_back(Char c); constexpr std::size_t count(void)const; }; //Used with the 'formatter' to output a type //OutIt is an iterator where the output is written at the end. template class basic_format_output_buffer : public format_output_buffer_base { private: using base = format_output_buffer_base; private: OutIt m_out; public: basic_format_output_buffer(OutIt out); ~basic_format_output_buffer(void)override; std::size_t write_out(void)override; constexpr OutIt out(void); private: std::size_t write_out_simple(void); }; template class basic_format_output_n_buffer : public format_output_buffer_base { private: using base = format_output_buffer_base; private: OutIt m_out; std::size_t m_max_write = 0; public: basic_format_output_n_buffer(OutIt out, std::size_t max); ~basic_format_output_n_buffer(void)override; std::size_t write_out(void)override; constexpr OutIt out(void); }; template class basic_format_size_buffer : public format_output_buffer_base { public: constexpr basic_format_size_buffer(void) = default; constexpr ~basic_format_size_buffer(void)override; std::size_t write_out(void)override; }; template struct print_format_buffer : public format_output_buffer_base { private: FILE* m_stream; public: constexpr print_format_buffer(FILE* stream): m_stream(stream){} constexpr ~print_format_buffer(void){ write_out(); } std::size_t write_out(void)override{ const auto written = fwrite(this->m_data, sizeof(this->m_data[0]), this->m_size, m_stream); if(written != this->m_size){ REXY_THROW_FORMAT_ERROR("Failed to print data"); } } }; } #endif