microfmt
Zero-allocation C++ formatting for constrained environments
Loading...
Searching...
No Matches
tee_sink.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
9#include "../microfmt.hpp"
10#include <cstddef>
11#include <string_view>
12
13namespace microfmt {
14
15// ============================================================================
16// Tee Sink (Multi-target broadcast)
17// ============================================================================
18
19template <size_t N = 2> class tee_sink {
20 static_assert(N > 0, "tee_sink must have at least one target sink");
21
22public:
23 template <typename... Sinks, std::enable_if_t<(sizeof...(Sinks) <= N), int> = 0>
24 explicit constexpr tee_sink(Sinks... sinks) noexcept : targets_{sinks...}, count_(sizeof...(Sinks)) {}
25
26 // Non-copyable
27 tee_sink(const tee_sink &) = delete;
28 tee_sink &operator=(const tee_sink &) = delete;
29 tee_sink(tee_sink &&) noexcept = default;
30 tee_sink &operator=(tee_sink &&) noexcept = default;
31
32 [[nodiscard]] sink as_sink() & noexcept RELOCO_LIFETIMEBOUND {
33 return sink{this, [](void *ctx, microfmt::string_view sv) noexcept { static_cast<tee_sink *>(ctx)->write(sv); }};
34 }
35
36 bool add_target(sink s) noexcept {
37 if (count_ >= N) {
38 return false;
39 }
40 targets_[count_++] = s;
41 return true;
42 }
43
44 void put(char c) const noexcept {
45 for (size_t i = 0; i < count_; ++i) {
46 targets_[i].put(c);
47 }
48 }
49
50 void write(microfmt::string_view sv) const noexcept {
51 for (size_t i = 0; i < count_; ++i) {
52 targets_[i].write(sv);
53 }
54 }
55
56 [[nodiscard]] constexpr size_t target_count() const noexcept { return count_; }
57
58private:
59 microfmt::array<sink, N> targets_{};
60 size_t count_{0};
61};
62
63// Convenience factory deduction helper
64template <typename... Sinks> [[nodiscard]] constexpr auto make_tee(Sinks... sinks) noexcept {
65 return tee_sink<sizeof...(Sinks)>{sinks...};
66}
67
68} // namespace microfmt
Definition tee_sink.hpp:19
tee_sink(const tee_sink &)=delete
constexpr size_t target_count() const noexcept
Definition tee_sink.hpp:56
void write(microfmt::string_view sv) const noexcept
Definition tee_sink.hpp:50
constexpr tee_sink(Sinks... sinks) noexcept
Definition tee_sink.hpp:24
bool add_target(sink s) noexcept
Definition tee_sink.hpp:36
void put(char c) const noexcept
Definition tee_sink.hpp:44
tee_sink & operator=(const tee_sink &)=delete
tee_sink(tee_sink &&) noexcept=default
sink as_sink() &noexcept RELOCO_LIFETIMEBOUND
Definition tee_sink.hpp:32
Definition assert.hpp:19
reloco::sink sink
Type-erased, zero-allocation output sink.
Definition microfmt.hpp:46
constexpr auto make_tee(Sinks... sinks) noexcept
Definition tee_sink.hpp:64