#ifndef RFL_CBOR_WRITE_HPP_ #define RFL_CBOR_WRITE_HPP_ #include #include #include #include #include #include #include "../parsing/Parent.hpp" #include "Parser.hpp" namespace rfl { namespace cbor { template void write_into_buffer( const auto& _obj, CborEncoder* _encoder, std::vector* _buffer ) noexcept { using T = std::remove_cvref_t; using ParentType = parsing::Parent; cbor_encoder_init( _encoder, reinterpret_cast(_buffer->data()), _buffer->size(), 0 ); const auto writer = Writer(_encoder); Parser>::write( writer, _obj, typename ParentType::Root {} ); } /// Returns CBOR bytes. template std::vector write(const auto& _obj) noexcept { std::vector buffer(4096); CborEncoder encoder; write_into_buffer(_obj, &encoder, &buffer); const auto total_bytes_needed = buffer.size() + cbor_encoder_get_extra_bytes_needed(&encoder); if (total_bytes_needed != buffer.size()) { buffer.resize(total_bytes_needed); write_into_buffer(_obj, &encoder, &buffer); } const auto length = cbor_encoder_get_buffer_size( &encoder, reinterpret_cast(buffer.data()) ); buffer.resize(length); return buffer; } /// Writes a CBOR into an ostream. template std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept { auto buffer = write(_obj); _stream.write(buffer.data(), buffer.size()); return _stream; } } // namespace cbor } // namespace rfl #endif