microfmt
Zero-allocation C++ formatting for constrained environments
Loading...
Searching...
No Matches
asio_coroutine.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Jarosław Pelczar <jarek@jpelczar.com>
2//
3// SPDX-License-Identifier: BSD-2-Clause
4
5#pragma once
6
13#include "../microfmt.hpp"
14#include "../reloco.hpp"
15#include "asio_sink.hpp"
16#include <boost/asio/awaitable.hpp>
17#include <boost/asio/use_awaitable.hpp>
18#include <boost/asio/write.hpp>
19#include <cstddef>
20#include <utility>
21
22namespace microfmt::coro {
23
40template <typename Stream, std::size_t StackSize = 256, typename... Args>
41[[nodiscard]] boost::asio::awaitable<std::size_t> async_format_to(Stream &stream, string_view fmt, Args &&...args) {
42 // Allocate a temporary buffer entirely on the coroutine frame / stack.
43 char stack_buffer[StackSize];
44
45 // Wrap it in our zero-allocation Boost.Asio mutable buffer sink; the sink
46 // only borrows stack_buffer, so it must not outlive this coroutine frame.
47 asio_mutable_buffer_sink sink(boost::asio::buffer(stack_buffer));
48
49 // Perform zero-heap formatting directly into the stack buffer.
50 microfmt::format_to(sink.as_sink(), fmt, std::forward<Args>(args)...);
51
52 // Asynchronously stream the exact written bytes using C++20 co_await.
53 co_return co_await boost::asio::async_write(stream, sink.written_buffer(), boost::asio::use_awaitable);
54}
55
56} // namespace microfmt::coro
Boost.Asio buffer and stream sink adapters for zero-allocation formatting.
A sink adapter that writes formatted output directly into a boost::asio::mutable_buffer.
Definition asio_sink.hpp:30
Definition fmt.hpp:17
Definition asio_coroutine.hpp:22
boost::asio::awaitable< std::size_t > async_format_to(Stream &stream, string_view fmt, Args &&...args)
Formats a message directly into a stack buffer and asynchronously writes it to a Boost....
Definition asio_coroutine.hpp:41
reloco::sink sink
Type-erased, zero-allocation output sink.
Definition microfmt.hpp:46
RELOCO_CONSTEXPR20 void format_to(const sink &out, microfmt::string_view fmt, const Args &...args) noexcept
Definition microfmt.hpp:1766