VLink  2.3.0
A high-performance communication middleware
fast_stream.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file fast_stream.h
26  * @brief Allocation-light @c std::ostream backed by a growable string buffer.
27  *
28  * @details
29  * @c FastStream is the zero-copy log assembly buffer used inside the VLink logger. Inheriting
30  * from @c std::ostream means every @c operator<< overload and manipulator works unchanged; the
31  * difference lies in the @c StringBuf backing storage and in @c take_view, which yields a
32  * @c std::string_view directly into the buffer for hand-off to the active sink without an
33  * intermediate copy.
34  *
35  * @par Supported operators
36  *
37  * | Operation | Source | Notes |
38  * | --------------------- | -------------------------------- | ----------------------------------------------- |
39  * | @c operator<< | @c std::ostream interface | All integral, floating, pointer types |
40  * | Standard manipulators | @c std::ios_base::fmtflags etc. | @c std::hex, @c std::setw, @c std::setfill, ... |
41  * | @c write_raw | direct buffer write | Bypasses locale and format flags |
42  * | @c append_to | append current contents | Does not reset the buffer |
43  * | @c take_view | hand-off as @c string_view | View invalidated by the next write |
44  *
45  * @par Growth policy
46  *
47  * | Stage | Capacity |
48  * | ------------------ | --------------------------------- |
49  * | Initial | @c kDefaultCapacity (@c 256) |
50  * | Doubling | until @c kMaxExpandSize (@c 8192) |
51  * | Linear increments | @c kMaxExpandSize step thereafter |
52  *
53  * @par Example
54  * @code
55  * vlink::FastStream stream;
56  * stream << "sensor_id=" << 42 << " value=" << 3.14;
57  * std::string_view view = stream.take_view(); // valid until next write
58  * write_to_sink(view);
59  * stream.reset();
60  *
61  * stream.write_raw("LITERAL", 7); // bypass formatting
62  * @endcode
63  *
64  * @note Not thread-safe; the logger keeps one @c FastStream per thread via @c thread_local.
65  * Views returned by @c take_view become invalid on the next stream operation or @c reset.
66  */
67 
68 #pragma once
69 
70 #include <cstdint>
71 #include <ostream>
72 #include <string>
73 #include <string_view>
74 #include <type_traits>
75 #include <utility>
76 
77 #include "./macros.h"
78 
79 namespace vlink {
80 
81 /**
82  * @class FastStream
83  * @brief Logger-friendly @c std::ostream with a custom growable string buffer.
84  *
85  * @details
86  * Routes every write through an embedded @c StringBuf that owns a @c std::string. The buffer
87  * grows by doubling up to 8 KiB and by linear 8 KiB increments thereafter. @c take_view yields
88  * a non-owning view into the buffer, so a single log line incurs at most one allocation when
89  * the buffer must grow and zero allocations on the steady-state path.
90  */
91 class VLINK_EXPORT FastStream : public std::ostream {
92  public:
93  /**
94  * @brief Constructs the stream with the default initial backing capacity.
95  *
96  * @details
97  * Initial capacity is @c kDefaultCapacity (@c 256 bytes); the buffer grows on demand.
98  */
99  FastStream() noexcept;
100 
101  /**
102  * @brief Destructor; releases the underlying string buffer.
103  */
104  ~FastStream() noexcept override;
105 
106  /**
107  * @brief Empties the buffer and clears the stream's error state.
108  *
109  * @details
110  * Retains the allocated capacity so subsequent messages avoid reallocation.
111  */
112  void reset() noexcept;
113 
114  /**
115  * @brief Appends the current buffer contents to @p target without resetting the stream.
116  *
117  * @param target Destination string; contents are appended in place.
118  */
119  void append_to(std::string& target) const;
120 
121  /**
122  * @brief Returns a non-owning view of the current buffer contents.
123  *
124  * @details
125  * Primary zero-copy hand-off used by the logger. The view remains valid until the next write
126  * to this stream or an explicit @c reset.
127  *
128  * @warning Do not retain the view beyond the next stream operation; doing so dereferences
129  * freed or moved storage.
130  *
131  * @return View covering the current buffer.
132  */
133  std::string_view take_view();
134 
135  /**
136  * @brief Returns the number of bytes currently held in the buffer.
137  *
138  * @return Buffer length in bytes.
139  */
140  [[nodiscard]] size_t size() const noexcept;
141 
142  /**
143  * @brief Returns the current allocated capacity of the backing buffer.
144  *
145  * @return Capacity in bytes.
146  */
147  [[nodiscard]] size_t capacity() const noexcept;
148 
149  /**
150  * @brief Trims the underlying buffer to its current backing size.
151  *
152  * @details
153  * Does not shrink to the formatted message length; content already written is kept.
154  */
155  void shrink_to_fit() noexcept;
156 
157  /**
158  * @brief Writes raw bytes into the buffer without going through @c std::ostream formatting.
159  *
160  * @details
161  * Faster than @c std::ostream::write for pre-formatted C strings because it skips the locale
162  * and format-flag plumbing.
163  *
164  * @param data Source pointer; non-null when @p len is non-zero.
165  * @param len Number of bytes to write.
166  * @return Reference to @c *this for chaining.
167  */
168  FastStream& write_raw(const char* data, size_t len);
169 
170  /**
171  * @brief Appends a value using the logger's fast formatting paths when applicable.
172  *
173  * @note Integer fast formatting is locale-independent.
174  *
175  * @tparam T Value type.
176  * @param value Value to append.
177  * @return Reference to @c *this for chaining.
178  */
179  template <typename T>
180  FastStream& push(T&& value);
181 
182  private:
183  FastStream& push_floating(float value);
184 
185  FastStream& push_floating(double value);
186 
187  bool push_integer(int64_t value);
188 
189  bool push_integer(uint64_t value);
190 
191  static constexpr size_t kDefaultCapacity{256};
192  static constexpr size_t kMinCapacity{64};
193  static constexpr size_t kMaxExpandSize{8192};
194 
195  class VLINK_EXPORT StringBuf final : public std::streambuf {
196  public:
197  explicit StringBuf(size_t initial_capacity = kDefaultCapacity);
198 
199  void reset() noexcept;
200 
201  void shrink_to_fit() noexcept;
202 
203  void append_to(std::string& target) const;
204 
205  [[nodiscard]] std::string_view take_view();
206 
207  [[nodiscard]] size_t size() const noexcept;
208 
209  [[nodiscard]] size_t capacity() const noexcept;
210 
211  [[nodiscard]] int_type overflow(int_type ch) override;
212 
213  std::streamsize xsputn(const char* s, std::streamsize n) override;
214 
215  private:
216  void grow_buffer(size_t required_size);
217 
218  void advance_pptr(size_t count) noexcept;
219 
220  std::string buffer_;
221 
223  };
224 
225  StringBuf buf_;
226 
228 };
229 
230 ////////////////////////////////////////////////////////////////
231 /// Details
232 ////////////////////////////////////////////////////////////////
233 
234 template <typename T>
235 inline FastStream& FastStream::push(T&& value) {
236  using ValueT = std::remove_cv_t<std::remove_reference_t<T>>;
237 
238  if constexpr (std::is_array_v<ValueT> && std::is_same_v<std::remove_extent_t<ValueT>, char>) {
239  if VLIKELY (width() == 0) {
240  return write_raw(value, std::char_traits<char>::length(value));
241  }
242  } else if constexpr (std::is_same_v<ValueT, char*> || std::is_same_v<ValueT, const char*>) {
243  if VLIKELY (value && width() == 0) {
244  return write_raw(value, std::char_traits<char>::length(value));
245  }
246  } else if constexpr (std::is_same_v<ValueT, std::string>) {
247  if VLIKELY (width() == 0) {
248  return write_raw(value.data(), value.size());
249  }
250  } else if constexpr (std::is_same_v<ValueT, std::string_view>) {
251  if VLIKELY (width() == 0) {
252  return write_raw(value.data(), value.size());
253  }
254  } else if constexpr (std::is_same_v<ValueT, float> || std::is_same_v<ValueT, double>) {
255  return push_floating(value);
256  } else if constexpr (std::is_integral_v<ValueT> && sizeof(std::decay_t<ValueT>) <= sizeof(uint64_t) &&
257  !std::is_same_v<ValueT, bool> && !std::is_same_v<ValueT, char> &&
258  !std::is_same_v<ValueT, signed char> && !std::is_same_v<ValueT, unsigned char> &&
259  !std::is_same_v<ValueT, wchar_t> && !std::is_same_v<ValueT, char16_t> &&
260  !std::is_same_v<ValueT, char32_t>) {
261  if constexpr (std::is_signed_v<ValueT>) {
262  if VLIKELY (push_integer(static_cast<int64_t>(value))) {
263  return *this;
264  }
265  } else {
266  if VLIKELY (push_integer(static_cast<uint64_t>(value))) {
267  return *this;
268  }
269  }
270  }
271 
272  // NOLINTNEXTLINE(bugprone-unintended-char-ostream-output)
273  static_cast<std::ostream&>(*this) << std::forward<T>(value);
274  return *this;
275 }
276 
277 } // namespace vlink
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VLINK_EXPORT
Definition: macros.h:81
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174