VLink  2.3.0
A high-performance communication middleware
format.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 format.h
26  * @brief Minimal heap-free @c {} placeholder formatter for the logger hot path.
27  *
28  * @details
29  * VLink targets C++17 first; @c std::format is unavailable on that baseline and far heavier on
30  * older standards. This header provides a focused subset of std::format-style formatting that
31  * writes through a stack-allocated buffer or a user-supplied output iterator, never allocates,
32  * and dispatches via a compile-time type tag rather than a virtual call chain.
33  *
34  * @par Supported argument types
35  *
36  * | C++ type | Example output |
37  * | --------------------------------------------------------- | ---------------------- |
38  * | all integral types incl. @c char and @c bool | @c 42 / @c A / @c true |
39  * | @c float / @c double / @c long @c double | @c 3.14 |
40  * | @c const @c char* / @c std::string / @c std::string_view | @c hello |
41  * | @c T* (any pointer) and @c nullptr | @c 0x7ffe1234 / @c 0x0 |
42  * | @c enum | underlying integer |
43  * | any type with an ADL @c format_as(T) | mapped result |
44  *
45  * @par Placeholder syntax
46  *
47  * | Token | Meaning |
48  * | ----------------------- | ------------------------------------------- |
49  * | @c {} | Consume the next argument in order |
50  * | @c {0}, @c {1}, ... | Explicit positional index |
51  * | @c {:spec}, @c {0:spec} | Apply a std::format-style format spec |
52  * | @c {{ / @c }} | Literal opening / closing brace |
53  *
54  * @par Format specification
55  *
56  * The std::format grammar: @c [[fill]align][sign][#][0][width][.precision][type]
57  *
58  * - fill + align: any byte except braces before @c < (left), @c > (right), @c ^ (center).
59  * - sign: @c + / @c - / space for arithmetic presentations.
60  * - @c #: @c 0b / @c 0B / @c 0 / @c 0x / @c 0X prefix; floats keep the decimal point and
61  * @c g / @c G keep trailing zeros.
62  * - @c 0: zero padding after sign/prefix; ignored with an explicit align.
63  * - width / precision: literal digits, or dynamic @c {} / @c {n} consuming an integral
64  * argument; precision also truncates strings.
65  * - type: @c b @c B @c c @c d @c o @c x @c X integral; @c a @c A @c e @c E @c f @c F
66  * @c g @c G floating; @c s string/bool; @c ? escaped debug string/char; @c p pointer.
67  *
68  * @par Public API
69  *
70  * | Function | Output target | Allocates |
71  * | --------------------------------- | ------------------------------ | --------- |
72  * | @c format_to_n(out, n, fmt, ...) | @c char* buffer with cap @p n | no |
73  * | @c format_to(out[N], fmt, ...) | Fixed-size array | no |
74  * | @c format_to(it, fmt, ...) | Output iterator | no |
75  * | @c format(fmt, ...) | Returned @c std::string | yes |
76  *
77  * @par Example
78  * @code
79  * char buf[128];
80  * auto result = vlink::format::format_to_n(buf, sizeof(buf) - 1, "x={} y={:.1f}", 3, 4.5);
81  * buf[result.size] = '\0';
82  * // buf == "x=3 y=4.5"
83  * @endcode
84  *
85  * @note Deviations from std::format: locale (@c L) is not supported, the fill byte is
86  * single-byte, and invalid or inapplicable spec fields are ignored instead of throwing,
87  * so formatting never fails at runtime. A dynamic width/precision referencing a missing,
88  * non-integral or negative argument degrades to "not specified". Width and precision
89  * count bytes, so multi-byte UTF-8 sequences may be split by a string precision.
90  * Floating precision is clamped to 340 digits. A @c c presentation outside the @c char
91  * range and a @c c presentation of @c bool fall back to the decimal form. Without a
92  * spec (and for @c {:#} without type and precision), floating values use the @c "%g"
93  * 6 significant digit representation. Platforms without floating-point @c std::to_chars
94  * format floats through @c snprintf with printf semantics, including the @c %a
95  * representation. The @c ? presentation escapes ASCII control bytes, quotes and backslashes;
96  * string bytes at or above @c 0x80 pass through unescaped while a lone @c char code unit
97  * above @c 0x7F is escaped as @c \\x{..}. Unsupported argument types trigger a compile-time @c
98  * static_assert.
99  *
100  * @note The allocating entry point shares its name with this namespace; call it fully qualified
101  * as @c vlink::format::format(...). @c vlink::format(...) resolves to the namespace and
102  * does not compile.
103  *
104  * @note Custom types opt in by defining @c format_as(const T&) in the namespace of @c T,
105  * returning a directly formattable value; specs then apply to the mapped result.
106  * Class-type results must be returned by reference or as @c std::string_view.
107  */
108 
109 #pragma once
110 
111 #include <climits>
112 #include <cstddef>
113 #include <cstdint>
114 #include <cstring>
115 #include <string>
116 #include <string_view>
117 #include <type_traits>
118 #include <utility>
119 
120 #include "./macros.h"
121 
122 namespace vlink {
123 
124 /**
125  * @namespace vlink::format
126  * @brief Minimal allocation-free @c {} placeholder formatter.
127  */
128 namespace format {
129 
130 namespace detail {
131 
132 template <typename TypeT>
133 using RemoveCvref = typename std::remove_cv_t<std::remove_reference_t<TypeT>>;
134 
135 template <typename TypeT, typename = void>
136 struct IsOutputIteratorImpl final : std::false_type {};
137 
138 template <typename TypeT>
139 struct IsOutputIteratorImpl<TypeT, std::enable_if_t<std::is_assignable_v<decltype(*std::declval<TypeT&>()++), char>>>
140  final : std::true_type {};
141 
142 template <>
143 struct IsOutputIteratorImpl<char*> final : std::true_type {};
144 
145 template <typename TypeT, size_t NumT>
146 struct IsOutputIteratorImpl<TypeT[NumT]> final : std::false_type {};
147 
148 template <typename TypeT>
150 
151 enum class Type : uint8_t {
152  kNone,
153  kInt,
154  kUint,
155  kLongLong,
156  kUlongLong,
157  kBool,
158  kChar,
159  kFloat,
160  kDouble,
161  kLongDouble,
162  kString,
163  kCstring,
164  kPointer
165 };
166 
167 // NOLINTBEGIN
168 template <typename T>
169 struct TypeConstant final : std::integral_constant<Type, Type::kNone> {};
170 
171 template <>
172 struct TypeConstant<signed char> final : std::integral_constant<Type, Type::kInt> {};
173 
174 template <>
175 struct TypeConstant<unsigned char> final : std::integral_constant<Type, Type::kUint> {};
176 
177 template <>
178 struct TypeConstant<short> final : std::integral_constant<Type, Type::kInt> {};
179 
180 template <>
181 struct TypeConstant<unsigned short> final : std::integral_constant<Type, Type::kUint> {};
182 
183 template <>
184 struct TypeConstant<int> final : std::integral_constant<Type, Type::kInt> {};
185 
186 template <>
187 struct TypeConstant<unsigned> final : std::integral_constant<Type, Type::kUint> {};
188 
189 template <>
190 struct TypeConstant<long> final : std::integral_constant<Type, Type::kLongLong> {};
191 
192 template <>
193 struct TypeConstant<unsigned long> final : std::integral_constant<Type, Type::kUlongLong> {};
194 
195 template <>
196 struct TypeConstant<long long> final : std::integral_constant<Type, Type::kLongLong> {};
197 
198 template <>
199 struct TypeConstant<unsigned long long> final : std::integral_constant<Type, Type::kUlongLong> {};
200 
201 template <>
202 struct TypeConstant<bool> final : std::integral_constant<Type, Type::kBool> {};
203 
204 template <>
205 struct TypeConstant<char> final : std::integral_constant<Type, Type::kChar> {};
206 
207 template <>
208 struct TypeConstant<float> final : std::integral_constant<Type, Type::kFloat> {};
209 
210 template <>
211 struct TypeConstant<double> final : std::integral_constant<Type, Type::kDouble> {};
212 
213 template <>
214 struct TypeConstant<long double> final : std::integral_constant<Type, Type::kLongDouble> {};
215 
216 template <>
217 struct TypeConstant<std::nullptr_t> final : std::integral_constant<Type, Type::kPointer> {};
218 
219 template <>
220 struct TypeConstant<const char*> final : std::integral_constant<Type, Type::kCstring> {};
221 
222 template <>
223 struct TypeConstant<char*> final : std::integral_constant<Type, Type::kCstring> {};
224 
225 template <>
226 struct TypeConstant<std::string_view> final : std::integral_constant<Type, Type::kString> {};
227 
228 template <>
229 struct TypeConstant<std::string> final : std::integral_constant<Type, Type::kString> {};
230 
231 template <size_t NumT>
232 struct TypeConstant<char[NumT]> final : std::integral_constant<Type, Type::kCstring> {};
233 
234 template <size_t NumT>
235 struct TypeConstant<const char[NumT]> final : std::integral_constant<Type, Type::kCstring> {};
236 
237 template <typename T>
238 struct TypeConstant<T*> final : std::integral_constant<Type, Type::kPointer> {};
239 // NOLINTEND
240 
241 template <typename TypeT, typename = void>
242 struct HasFormatAs final : std::false_type {};
243 
244 template <typename TypeT>
245 struct HasFormatAs<TypeT, std::void_t<decltype(format_as(std::declval<const TypeT&>()))>> final : std::true_type {};
246 
247 VLINK_EXPORT inline size_t format_uint_to(char* buf, unsigned value) noexcept;
248 
249 VLINK_EXPORT inline size_t format_int_to(char* buf, int value) noexcept;
250 
251 VLINK_EXPORT inline size_t format_ulong_long_to(
252  char* buf, unsigned long long value) noexcept; // NOLINT(runtime/int,google-runtime-int)
253 
254 VLINK_EXPORT inline size_t format_long_long_to(char* buf,
255  long long value) noexcept; // NOLINT(runtime/int,google-runtime-int)
256 
257 VLINK_EXPORT size_t format_pointer_to(char* buf, const void* ptr) noexcept;
258 
259 VLINK_EXPORT size_t format_float_to(char* buf, size_t buflen, float value) noexcept;
260 
261 VLINK_EXPORT size_t format_double_to(char* buf, size_t buflen, double value) noexcept;
262 
263 VLINK_EXPORT size_t format_long_double_to(char* buf, size_t buflen,
264  long double value) noexcept; // NOLINT(google-runtime-float)
265 
266 VLINK_EXPORT size_t format_double_spec_to(char* buf, size_t buflen, double value, char type, int precision,
267  bool alt) noexcept;
268 
269 // NOLINTNEXTLINE(google-runtime-float)
270 VLINK_EXPORT size_t format_long_double_spec_to(char* buf, size_t buflen, long double value, char type, int precision,
271  bool alt) noexcept;
272 
273 inline constexpr int kSpecRefNone = -1;
274 inline constexpr int kSpecRefAuto = -2;
275 
276 enum class Align : uint8_t { kNone, kLeft, kRight, kCenter };
277 
278 enum class Sign : uint8_t { kMinus, kPlus, kSpace };
279 
280 struct FormatSpec final {
281  char fill{' '};
284  bool alt{false};
285  bool zero{false};
286  int width{0};
287  int precision{-1};
290  char type{'\0'};
291 };
292 
293 VLINK_EXPORT const char* parse_spec_ref(const char* p, const char* end, int& ref) noexcept;
294 
295 VLINK_EXPORT const char* parse_format_spec(const char* p, const char* end, FormatSpec& spec) noexcept;
296 
297 // NOLINTNEXTLINE(runtime/int,google-runtime-int)
298 VLINK_EXPORT inline size_t format_base_digits_to(char (&buf)[64], unsigned long long value, unsigned base_bits,
299  bool upper) noexcept;
300 
302  public:
303  StringWriter(char* buf, size_t size) noexcept;
304 
305  char* out() const noexcept;
306 
307  size_t written() const noexcept;
308 
309  size_t total_size() const noexcept;
310 
311  void write(char c);
312 
313  void write(const char* s, size_t count);
314 
315  void write(std::string_view sv);
316 
317  void write_fill(char fill, size_t count);
318 
319  private:
320  char* begin_{nullptr};
321  char* ptr_{nullptr};
322  char* end_{nullptr};
323  size_t total_size_{0};
324 };
325 
326 template <typename OutputItT>
328  public:
329  inline explicit IteratorWriter(OutputItT out) : out_(out) {}
330 
331  inline OutputItT out() const noexcept { return out_; }
332 
333  inline size_t size() const noexcept { return count_; }
334 
335  inline void write(char c) {
336  *out_++ = c;
337  ++count_;
338  }
339 
340  inline void write(const char* s, size_t count) {
341  for (size_t i = 0; i < count; ++i) {
342  *out_++ = s[i];
343  }
344 
345  count_ += count;
346  }
347 
348  inline void write(std::string_view sv) { write(sv.data(), sv.size()); }
349 
350  inline void write_fill(char fill, size_t count) {
351  for (size_t i = 0; i < count; ++i) {
352  *out_++ = fill;
353  }
354 
355  count_ += count;
356  }
357 
358  private:
359  OutputItT out_;
360  size_t count_{0};
361 };
362 
363 template <typename CharT>
364 class Value {
365  public:
366  // NOLINTBEGIN
367  union {
369  unsigned uint_value;
370  long long long_long_value;
371  unsigned long long ulong_long_value;
373  CharT char_value;
374  float float_value;
375  double double_value;
376  long double long_double_value;
377  const CharT* string_value;
378  std::string_view string_view_value;
379  const void* pointer_value;
380  };
381 
382  constexpr Value() : int_value(0) {}
383 
384  constexpr explicit Value(signed char val) : int_value(static_cast<int>(val)) {}
385 
386  constexpr explicit Value(unsigned char val) : uint_value(static_cast<unsigned>(val)) {}
387 
388  constexpr explicit Value(short val) : int_value(static_cast<int>(val)) {}
389 
390  constexpr explicit Value(unsigned short val) : uint_value(static_cast<unsigned>(val)) {}
391 
392  constexpr explicit Value(int val) : int_value(val) {}
393 
394  constexpr explicit Value(unsigned val) : uint_value(val) {}
395 
396  constexpr explicit Value(long val) : long_long_value(val) {}
397 
398  constexpr explicit Value(unsigned long val) : ulong_long_value(val) {}
399 
400  constexpr explicit Value(long long val) : long_long_value(val) {}
401 
402  constexpr explicit Value(unsigned long long val) : ulong_long_value(val) {}
403 
404  constexpr explicit Value(bool val) : bool_value(val) {}
405 
406  constexpr explicit Value(CharT val) : char_value(val) {}
407 
408  constexpr explicit Value(float val) : float_value(val) {}
409 
410  constexpr explicit Value(double val) : double_value(val) {}
411 
412  constexpr explicit Value(long double val) : long_double_value(val) {}
413 
414  constexpr explicit Value(std::nullptr_t) : pointer_value(nullptr) {}
415 
416  constexpr explicit Value(const CharT* val) : string_value(val) {}
417 
418  constexpr explicit Value(CharT* val) : string_value(val) {}
419 
420  constexpr explicit Value(std::string_view val) : string_view_value(val) {}
421 
422  constexpr explicit Value(const std::string& val) : string_view_value(val) {}
423 
424  template <size_t NumT>
425  constexpr explicit Value(const CharT (&val)[NumT]) : string_value(val) {}
426 
427  template <size_t NumT>
428  constexpr explicit Value(CharT (&val)[NumT]) : string_value(val) {}
429 
430  template <typename TypeT>
431  constexpr explicit Value(TypeT* val) : pointer_value(static_cast<const void*>(val)) {}
432  // NOLINTEND
433 };
434 
435 template <typename CharT>
436 class FormatArg {
437  public:
438  constexpr FormatArg() = default; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
439 
440  template <typename TypeT>
441  constexpr explicit FormatArg(const TypeT& val) {
442  if constexpr (HasFormatAs<TypeT>::value) {
443  using ResultT = decltype(format_as(val));
444  using MappedT = RemoveCvref<ResultT>;
445  static_assert(std::is_enum_v<MappedT> || TypeConstant<MappedT>::value != Type::kNone,
446  "[vlink::format] format_as must return a directly formattable type");
447  static_assert(std::is_reference_v<ResultT> || !std::is_same_v<MappedT, std::string>,
448  "[vlink::format] format_as returning std::string by value would dangle, "
449  "return a reference or std::string_view");
450 
451  if constexpr (std::is_enum_v<MappedT>) {
452  using UnderlyingT = std::underlying_type_t<MappedT>;
453  value_ = Value<CharT>(static_cast<UnderlyingT>(format_as(val)));
455  } else {
456  value_ = Value<CharT>(format_as(val));
458  }
459  } else if constexpr (std::is_enum_v<TypeT>) {
460  using UnderlyingT = std::underlying_type_t<TypeT>;
461  value_ = Value<CharT>(static_cast<UnderlyingT>(val));
463  } else if constexpr (TypeConstant<RemoveCvref<TypeT>>::value != Type::kNone) {
464  value_ = Value<CharT>(val);
466  } else {
467  static_assert(!sizeof(TypeT),
468  "[vlink::format] unsupported type for format_to/MLOG, "
469  "convert to string first or provide format_as");
470  }
471  }
472 
473  constexpr Type type() const { return type_; }
474  constexpr const Value<CharT>& value() const { return value_; }
475 
476  private:
477  Value<CharT> value_;
478  Type type_{Type::kNone};
479 };
480 
481 template <typename CharT, typename... ArgsT>
482 struct FormatArgStore final {
483  static constexpr size_t kNumArgs = sizeof...(ArgsT);
485 
486  template <typename... ValuesT>
487  constexpr explicit FormatArgStore(const ValuesT&... values) : args{FormatArg<CharT>(values)...} {}
488 };
489 
490 template <typename CharT>
492  public:
493  constexpr BasicFormatArgs() : args_(nullptr), size_(0) {}
494 
495  template <typename... ArgsT>
496  constexpr explicit BasicFormatArgs(const FormatArgStore<CharT, ArgsT...>& store)
497  : args_(store.args), size_(sizeof...(ArgsT)) {}
498 
499  constexpr FormatArg<CharT> get(size_t id) const {
500  return id < size_ ? args_[id] : FormatArg<CharT>();
501  } // LCOV_EXCL_LINE GCOVR_EXCL_LINE
502 
503  constexpr size_t size() const { return size_; }
504 
505  private:
506  const FormatArg<CharT>* args_;
507  size_t size_;
508 };
509 
511 
512 template <typename CharT, typename WriterT>
514  public:
515  inline explicit FormatWriter(WriterT writer) : writer_(writer) {}
516 
517  void format(std::string_view fmt, BasicFormatArgs<CharT> args, size_t arg_id = 0) {
518  const char* p = fmt.data();
519  const char* end = p + fmt.size();
520 
521  while (p != end) {
522  char c = *p++;
523 
524  if (c == '}') {
525  if (p != end && *p == '}') {
526  writer_.write('}');
527  ++p;
528  } else {
529  writer_.write('}');
530  }
531 
532  continue;
533  }
534 
535  if VLIKELY (c != '{') {
536  const char* begin = p - 1;
537 
538  while (p != end && *p != '{' && *p != '}') {
539  ++p;
540  }
541 
542  writer_.write(begin, static_cast<size_t>(p - begin));
543  continue;
544  }
545 
546  if VUNLIKELY (p == end) {
547  writer_.write('{');
548  break;
549  }
550 
551  if (*p == '{') {
552  writer_.write('{');
553  ++p;
554  continue;
555  }
556 
557  if VLIKELY (*p == '}') {
558  if VLIKELY (arg_id < args.size()) {
559  write_arg(args.get(arg_id++));
560  }
561 
562  ++p;
563 
564  continue;
565  }
566 
567  size_t index = arg_id;
568  bool has_explicit_index = false;
569 
570  if (*p >= '0' && *p <= '9') {
571  index = 0;
572  has_explicit_index = true;
573 
574  while (p != end && *p >= '0' && *p <= '9') {
575  index = index * 10 + static_cast<size_t>(*p++ - '0');
576  }
577  }
578 
579  if (!has_explicit_index) {
580  ++arg_id;
581  }
582 
583  FormatSpec spec;
584  bool has_spec = false;
585 
586  if (p != end && *p == ':') {
587  ++p;
588  p = parse_format_spec(p, end, spec);
589  resolve_spec_refs(spec, args, arg_id);
590  has_spec = true;
591  }
592 
593  while (p != end && *p != '}') {
594  ++p;
595  }
596 
597  if VLIKELY (p != end) {
598  if VLIKELY (index < args.size()) {
599  if (has_spec) {
600  write_arg_spec(args.get(index), spec);
601  } else {
602  write_arg(args.get(index));
603  }
604  }
605 
606  ++p;
607  }
608  }
609  }
610 
611  template <typename... ArgsT>
612  bool try_format(std::string_view& fmt, size_t& arg_id, const ArgsT&... args) {
613  return try_format_args(fmt, arg_id, args...);
614  }
615 
616  inline auto out() const { return writer_.out(); }
617 
618  template <typename WriterImplT = WriterT>
619  inline auto total_size() const -> decltype(std::declval<WriterImplT>().total_size()) {
620  return writer_.total_size();
621  }
622 
623  inline size_t size() const { return writer_.size(); }
624 
625  private:
626  // NOLINTBEGIN
627  bool try_format_args(std::string_view& fmt, size_t&) {
628  for (char c : fmt) {
629  if VUNLIKELY (c == '{' || c == '}') {
630  return false;
631  }
632  }
633 
634  writer_.write(fmt);
635  return true;
636  }
637 
638  template <typename ArgT, typename... ArgsT>
639  bool try_format_args(std::string_view& fmt, size_t& arg_id, const ArgT& arg, const ArgsT&... args) {
640  size_t pos = 0;
641 
642  while (pos < fmt.size() && fmt[pos] != '{' && fmt[pos] != '}') {
643  ++pos;
644  }
645 
646  if (pos == fmt.size()) {
647  writer_.write(fmt);
648  return true;
649  }
650 
651  if VUNLIKELY (fmt[pos] != '{' || pos + 1 >= fmt.size() || fmt[pos + 1] != '}') {
652  return false;
653  }
654 
655  if constexpr (HasFormatAs<RemoveCvref<ArgT>>::value) {
656  return false;
657  } else {
658  writer_.write(fmt.data(), pos);
659  write_value(arg);
660  ++arg_id;
661  fmt.remove_prefix(pos + 2);
662 
663  return try_format_args(fmt, arg_id, args...);
664  }
665  }
666 
667  template <typename TypeT>
668  void write_value(const TypeT& value) {
669  using ValueT = RemoveCvref<TypeT>;
670 
671  if constexpr (std::is_enum_v<ValueT>) {
672  write_value(static_cast<std::underlying_type_t<ValueT>>(value));
673  } else if constexpr (TypeConstant<ValueT>::value == Type::kInt) {
674  write_int(static_cast<int>(value));
675  } else if constexpr (TypeConstant<ValueT>::value == Type::kUint) {
676  write_uint(static_cast<unsigned>(value));
677  } else if constexpr (TypeConstant<ValueT>::value == Type::kLongLong) {
678  write_long_long(static_cast<long long>(value));
679  } else if constexpr (TypeConstant<ValueT>::value == Type::kUlongLong) {
680  write_ulong_long(static_cast<unsigned long long>(value));
681  } else if constexpr (TypeConstant<ValueT>::value == Type::kBool) {
682  write_bool(value);
683  } else if constexpr (TypeConstant<ValueT>::value == Type::kChar) {
684  write_char(value);
685  } else if constexpr (TypeConstant<ValueT>::value == Type::kFloat) {
686  write_float(value);
687  } else if constexpr (TypeConstant<ValueT>::value == Type::kDouble) {
688  write_double(value);
689  } else if constexpr (TypeConstant<ValueT>::value == Type::kLongDouble) {
690  write_long_double(value);
691  } else if constexpr (TypeConstant<ValueT>::value == Type::kCstring) {
692  write_string(value);
693  } else if constexpr (TypeConstant<ValueT>::value == Type::kString) {
694  write_string_view(value);
695  } else if constexpr (TypeConstant<ValueT>::value == Type::kPointer) {
696  write_pointer(static_cast<const void*>(value));
697  } else {
698  static_assert(!sizeof(TypeT),
699  "[vlink::format] unsupported type for format_to/MLOG, "
700  "convert to string first");
701  }
702  }
703 
704  void write_int(int value) {
705  char buf[11];
706  size_t n = format_int_to(buf, value);
707  writer_.write(buf, n);
708  }
709 
710  void write_uint(unsigned value) {
711  char buf[10];
712  size_t n = format_uint_to(buf, value);
713  writer_.write(buf, n);
714  }
715 
716  void write_long_long(long long value) {
717  char buf[20];
718  size_t n = format_long_long_to(buf, value);
719  writer_.write(buf, n);
720  }
721 
722  void write_ulong_long(unsigned long long value) {
723  char buf[20];
724  size_t n = format_ulong_long_to(buf, value);
725  writer_.write(buf, n);
726  }
727 
728  void write_bool(bool value) {
729  if (value) {
730  writer_.write("true", 4);
731  } else {
732  writer_.write("false", 5);
733  }
734  }
735 
736  void write_char(char value) { writer_.write(value); }
737 
738  void write_string(const char* str) {
739  if VLIKELY (str) {
740  writer_.write(str, std::strlen(str));
741  } else {
742  writer_.write("(null)", 6);
743  }
744  }
745 
746  void write_string_view(std::string_view sv) { writer_.write(sv); }
747 
748  void write_pointer(const void* ptr) {
749  char buf[18];
750  size_t n = format_pointer_to(buf, ptr);
751  writer_.write(buf, n);
752  }
753 
754  void write_float(float value) {
755  char buf[32];
756  size_t n = format_float_to(buf, sizeof(buf), value);
757  writer_.write(buf, n);
758  }
759 
760  void write_double(double value) {
761  char buf[32];
762  size_t n = format_double_to(buf, sizeof(buf), value);
763  writer_.write(buf, n);
764  }
765 
766  void write_long_double(long double value) {
767  char buf[64];
768  size_t n = format_long_double_to(buf, sizeof(buf), value);
769  writer_.write(buf, n);
770  }
771 
772  void write_arg(const FormatArg<CharT>& arg) {
773  switch (arg.type()) {
774  case Type::kInt:
775  write_int(arg.value().int_value);
776  break;
777  case Type::kUint:
778  write_uint(arg.value().uint_value);
779  break;
780  case Type::kLongLong:
781  write_long_long(arg.value().long_long_value);
782  break;
783  case Type::kUlongLong:
784  write_ulong_long(arg.value().ulong_long_value);
785  break;
786  case Type::kBool:
787  write_bool(arg.value().bool_value);
788  break;
789  case Type::kChar:
790  write_char(arg.value().char_value);
791  break;
792  case Type::kFloat:
793  write_float(arg.value().float_value);
794  break;
795  case Type::kDouble:
796  write_double(arg.value().double_value);
797  break;
798  case Type::kLongDouble:
799  write_long_double(arg.value().long_double_value);
800  break;
801  case Type::kCstring:
802  write_string(arg.value().string_value);
803  break;
804  case Type::kString:
805  write_string_view(arg.value().string_view_value);
806  break;
807  case Type::kPointer:
808  write_pointer(arg.value().pointer_value);
809  break;
810  default: // LCOV_EXCL_LINE GCOVR_EXCL_LINE
811  break; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
812  }
813  }
814 
815  static long long spec_ref_value(const FormatArg<CharT>& arg) {
816  switch (arg.type()) {
817  case Type::kInt:
818  return arg.value().int_value;
819  case Type::kUint:
820  return arg.value().uint_value;
821  case Type::kLongLong:
822  return arg.value().long_long_value;
823  case Type::kUlongLong:
824  return arg.value().ulong_long_value > static_cast<unsigned long long>(LLONG_MAX)
825  ? LLONG_MAX
826  : static_cast<long long>(arg.value().ulong_long_value);
827  default:
828  return -1;
829  }
830  }
831 
832  void resolve_spec_refs(FormatSpec& spec, const BasicFormatArgs<CharT>& args, size_t& arg_id) {
833  if (spec.width_ref != kSpecRefNone) {
834  const size_t ref = spec.width_ref == kSpecRefAuto ? arg_id++ : static_cast<size_t>(spec.width_ref);
835  const long long value = spec_ref_value(args.get(ref));
836  spec.width = value > 0 ? (value > 999999999 ? 999999999 : static_cast<int>(value)) : 0;
837  }
838 
839  if (spec.precision_ref != kSpecRefNone) {
840  const size_t ref = spec.precision_ref == kSpecRefAuto ? arg_id++ : static_cast<size_t>(spec.precision_ref);
841  const long long value = spec_ref_value(args.get(ref));
842  spec.precision = value >= 0 ? (value > 999999999 ? 999999999 : static_cast<int>(value)) : -1;
843  }
844  }
845 
846  void write_fill(char fill, size_t count) { writer_.write_fill(fill, count); }
847 
848  void write_padded(const FormatSpec& spec, std::string_view prefix, std::string_view body, Align default_align,
849  bool allow_zero) {
850  const size_t content = prefix.size() + body.size();
851  const size_t width = static_cast<size_t>(spec.width);
852  const size_t pad = width > content ? width - content : 0U;
853 
854  if VLIKELY (pad == 0U) {
855  if (!prefix.empty()) {
856  writer_.write(prefix);
857  }
858 
859  writer_.write(body);
860 
861  return;
862  }
863 
864  if (spec.zero && spec.align == Align::kNone && allow_zero) {
865  if (!prefix.empty()) {
866  writer_.write(prefix);
867  }
868 
869  write_fill('0', pad);
870  writer_.write(body);
871 
872  return;
873  }
874 
875  const Align align = spec.align == Align::kNone ? default_align : spec.align;
876  size_t left = 0U;
877 
878  if (align == Align::kRight) {
879  left = pad;
880  } else if (align == Align::kCenter) {
881  left = pad / 2U;
882  }
883 
884  write_fill(spec.fill, left);
885 
886  if (!prefix.empty()) {
887  writer_.write(prefix);
888  }
889 
890  writer_.write(body);
891  write_fill(spec.fill, pad - left);
892  }
893 
894  void write_int_spec(long long value, const FormatSpec& spec) {
895  if VUNLIKELY (spec.type == 'c' && value >= CHAR_MIN && value <= CHAR_MAX) {
896  write_char_spec(static_cast<char>(value), spec);
897 
898  return;
899  }
900 
901  if (value < 0) {
902  write_uint_spec(static_cast<unsigned long long>(-(value + 1)) + 1U, true, spec);
903  } else {
904  write_uint_spec(static_cast<unsigned long long>(value), false, spec);
905  }
906  }
907 
908  void write_uint_spec(unsigned long long magnitude, bool negative, const FormatSpec& spec) {
909  if VUNLIKELY (spec.type == 'c' && !negative && magnitude <= static_cast<unsigned long long>(CHAR_MAX)) {
910  write_char_spec(static_cast<char>(magnitude), spec);
911 
912  return;
913  }
914 
915  char prefix[3];
916  size_t prefix_size = 0;
917 
918  if (negative) {
919  prefix[prefix_size++] = '-';
920  } else if (spec.sign == Sign::kPlus) {
921  prefix[prefix_size++] = '+';
922  } else if (spec.sign == Sign::kSpace) {
923  prefix[prefix_size++] = ' ';
924  }
925 
926  char digits[64];
927  size_t digit_count = 0;
928  const char* digit_begin = digits;
929 
930  switch (spec.type) {
931  case 'b':
932  case 'B':
933  digit_count = format_base_digits_to(digits, magnitude, 1U, false);
934  digit_begin = digits + sizeof(digits) - digit_count;
935 
936  if (spec.alt) {
937  prefix[prefix_size++] = '0';
938  prefix[prefix_size++] = spec.type;
939  }
940 
941  break;
942  case 'o':
943  digit_count = format_base_digits_to(digits, magnitude, 3U, false);
944  digit_begin = digits + sizeof(digits) - digit_count;
945 
946  if (spec.alt && magnitude != 0U) {
947  prefix[prefix_size++] = '0';
948  }
949 
950  break;
951  case 'x':
952  case 'X':
953  digit_count = format_base_digits_to(digits, magnitude, 4U, spec.type == 'X');
954  digit_begin = digits + sizeof(digits) - digit_count;
955 
956  if (spec.alt) {
957  prefix[prefix_size++] = '0';
958  prefix[prefix_size++] = spec.type;
959  }
960 
961  break;
962  default:
963  digit_count = format_ulong_long_to(digits, magnitude);
964  break;
965  }
966 
967  write_padded(spec, std::string_view(prefix, prefix_size), std::string_view(digit_begin, digit_count), Align::kRight,
968  true);
969  }
970 
971  void write_bool_spec(bool value, const FormatSpec& spec) {
972  switch (spec.type) {
973  case 'b':
974  case 'B':
975  case 'c':
976  case 'd':
977  case 'o':
978  case 'x':
979  case 'X': {
980  FormatSpec decimal_spec = spec;
981  decimal_spec.type = spec.type == 'c' ? 'd' : spec.type;
982  write_uint_spec(value ? 1U : 0U, false, decimal_spec);
983 
984  return;
985  }
986  default:
987  break;
988  }
989 
990  write_padded(spec, std::string_view(), value ? std::string_view("true") : std::string_view("false"), Align::kLeft,
991  false);
992  }
993 
994  void write_char_spec(char value, const FormatSpec& spec) {
995  if VUNLIKELY (spec.type == '?') {
996  write_debug_spec(std::string_view(&value, 1), '\'', spec);
997 
998  return;
999  }
1000 
1001  switch (spec.type) {
1002  case 'b':
1003  case 'B':
1004  case 'd':
1005  case 'o':
1006  case 'x':
1007  case 'X':
1008  write_int_spec(static_cast<long long>(static_cast<unsigned char>(value)), spec);
1009  return;
1010  default:
1011  break;
1012  }
1013 
1014  write_padded(spec, std::string_view(), std::string_view(&value, 1), Align::kLeft, false);
1015  }
1016 
1017  template <typename FloatT>
1018  void write_float_spec(FloatT value, const FormatSpec& spec) {
1019  constexpr size_t kMaxIntegerDigits = std::is_same_v<FloatT, long double> ? 4933U : 309U;
1020  constexpr int kMaxPrecision = 340;
1021  char buf[kMaxIntegerDigits + 3U + kMaxPrecision];
1022  size_t size = 0;
1023  const int precision = spec.precision > kMaxPrecision ? kMaxPrecision : spec.precision;
1024 
1025  if (spec.type == '\0' && precision < 0 && !spec.alt) {
1026  if constexpr (std::is_same_v<FloatT, long double>) {
1027  size = format_long_double_to(buf, sizeof(buf), value);
1028  } else if constexpr (std::is_same_v<FloatT, float>) {
1029  size = format_float_to(buf, sizeof(buf), value);
1030  } else {
1031  size = format_double_to(buf, sizeof(buf), value);
1032  }
1033  } else {
1034  if constexpr (std::is_same_v<FloatT, long double>) {
1035  size = format_long_double_spec_to(buf, sizeof(buf), value, spec.type, precision, spec.alt);
1036  } else {
1037  size = format_double_spec_to(buf, sizeof(buf), static_cast<double>(value), spec.type, precision, spec.alt);
1038  }
1039  }
1040 
1041  std::string_view text(buf, size);
1042  char sign = '\0';
1043 
1044  if (!text.empty() && text.front() == '-') {
1045  sign = '-';
1046  text.remove_prefix(1);
1047  } else if (spec.sign == Sign::kPlus) {
1048  sign = '+';
1049  } else if (spec.sign == Sign::kSpace) {
1050  sign = ' ';
1051  }
1052 
1053  const bool numeric = !text.empty() && text.front() >= '0' && text.front() <= '9';
1054 
1055  write_padded(spec, sign != '\0' ? std::string_view(&sign, 1) : std::string_view(), text, Align::kRight, numeric);
1056  }
1057 
1058  static size_t escape_debug_char(char c, char quote, bool escape_high, char (&out)[8]) {
1059  switch (c) {
1060  case '\t':
1061  out[0] = '\\';
1062  out[1] = 't';
1063  return 2U;
1064  case '\n':
1065  out[0] = '\\';
1066  out[1] = 'n';
1067  return 2U;
1068  case '\r':
1069  out[0] = '\\';
1070  out[1] = 'r';
1071  return 2U;
1072  case '\\':
1073  out[0] = '\\';
1074  out[1] = '\\';
1075  return 2U;
1076  default:
1077  break;
1078  }
1079 
1080  if (c == quote) {
1081  out[0] = '\\';
1082  out[1] = quote;
1083  return 2U;
1084  }
1085 
1086  const auto code = static_cast<unsigned char>(c);
1087 
1088  if VUNLIKELY (code < 0x20U || code == 0x7FU || (escape_high && code > 0x7FU)) {
1089  static constexpr const char kHexDigits[] = "0123456789abcdef";
1090  size_t n = 0;
1091  out[n++] = '\\';
1092  out[n++] = code > 0x7FU ? 'x' : 'u';
1093  out[n++] = '{';
1094 
1095  if (code >= 0x10U) {
1096  out[n++] = kHexDigits[code >> 4U];
1097  }
1098 
1099  out[n++] = kHexDigits[code & 0xFU];
1100  out[n++] = '}';
1101 
1102  return n;
1103  }
1104 
1105  out[0] = c;
1106 
1107  return 1U;
1108  }
1109 
1110  void write_debug_spec(std::string_view sv, char quote, const FormatSpec& spec) {
1111  const bool escape_high = quote == '\'';
1112  char piece[8];
1113  size_t body = 2U;
1114 
1115  for (const char c : sv) {
1116  body += escape_debug_char(c, quote, escape_high, piece);
1117  }
1118 
1119  const size_t width = static_cast<size_t>(spec.width);
1120  const size_t pad = width > body ? width - body : 0U;
1121  const Align align = spec.align == Align::kNone ? Align::kLeft : spec.align;
1122  size_t left = 0U;
1123 
1124  if (align == Align::kRight) {
1125  left = pad;
1126  } else if (align == Align::kCenter) {
1127  left = pad / 2U;
1128  }
1129 
1130  write_fill(spec.fill, left);
1131 
1132  writer_.write(quote);
1133 
1134  for (const char c : sv) {
1135  writer_.write(piece, escape_debug_char(c, quote, escape_high, piece));
1136  }
1137 
1138  writer_.write(quote);
1139  write_fill(spec.fill, pad - left);
1140  }
1141 
1142  void write_cstring_spec(const char* str, const FormatSpec& spec) {
1143  if VLIKELY (str) {
1144  write_string_spec(std::string_view(str, std::strlen(str)), spec);
1145  } else {
1146  write_string_spec(std::string_view("(null)"), spec);
1147  }
1148  }
1149 
1150  void write_string_spec(std::string_view sv, const FormatSpec& spec) {
1151  if (spec.precision >= 0 && static_cast<size_t>(spec.precision) < sv.size()) {
1152  sv = sv.substr(0, static_cast<size_t>(spec.precision));
1153  }
1154 
1155  if VUNLIKELY (spec.type == '?') {
1156  write_debug_spec(sv, '"', spec);
1157 
1158  return;
1159  }
1160 
1161  write_padded(spec, std::string_view(), sv, Align::kLeft, false);
1162  }
1163 
1164  void write_pointer_spec(const void* ptr, const FormatSpec& spec) {
1165  char buf[18];
1166  const size_t size = format_pointer_to(buf, ptr);
1167  write_padded(spec, std::string_view(buf, 2), std::string_view(buf + 2, size - 2), Align::kRight, true);
1168  }
1169 
1170  void write_arg_spec(const FormatArg<CharT>& arg, const FormatSpec& spec) {
1171  switch (arg.type()) {
1172  case Type::kInt:
1173  write_int_spec(arg.value().int_value, spec);
1174  break;
1175  case Type::kUint:
1176  write_uint_spec(arg.value().uint_value, false, spec);
1177  break;
1178  case Type::kLongLong:
1179  write_int_spec(arg.value().long_long_value, spec);
1180  break;
1181  case Type::kUlongLong:
1182  write_uint_spec(arg.value().ulong_long_value, false, spec);
1183  break;
1184  case Type::kBool:
1185  write_bool_spec(arg.value().bool_value, spec);
1186  break;
1187  case Type::kChar:
1188  write_char_spec(arg.value().char_value, spec);
1189  break;
1190  case Type::kFloat:
1191  write_float_spec(arg.value().float_value, spec);
1192  break;
1193  case Type::kDouble:
1194  write_float_spec(arg.value().double_value, spec);
1195  break;
1196  case Type::kLongDouble:
1197  write_float_spec(arg.value().long_double_value, spec);
1198  break;
1199  case Type::kCstring:
1200  write_cstring_spec(arg.value().string_value, spec);
1201  break;
1202  case Type::kString:
1203  write_string_spec(arg.value().string_view_value, spec);
1204  break;
1205  case Type::kPointer:
1206  write_pointer_spec(arg.value().pointer_value, spec);
1207  break;
1208  default:
1209  break;
1210  }
1211  }
1212  // NOLINTEND
1213 
1214  WriterT writer_;
1215 };
1216 
1217 } // namespace detail
1218 
1219 template <typename... ArgsT>
1220 struct FString final {
1221  std::string_view str;
1222  using t = FString;
1223 
1224  template <size_t NumT>
1225  // NOLINTNEXTLINE(runtime/explicit,google-explicit-constructor,hicpp-explicit-conversions)
1226  constexpr FString(const char (&s)[NumT]) : str(s, NumT - 1) {}
1227 
1228  // NOLINTNEXTLINE(modernize-use-constraints)
1229  template <typename StrT, std::enable_if_t<std::is_convertible_v<const StrT&, std::string_view>, int> = 0>
1230  // NOLINTNEXTLINE(runtime/explicit,google-explicit-constructor,hicpp-explicit-conversions)
1231  constexpr FString(const StrT& s) : str(s) {}
1232 
1233  // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions)
1234  inline operator std::string_view() const { return str; }
1235 
1236  std::string_view get() const { return str; }
1237 };
1238 
1239 template <typename... ArgsT>
1240 using format_string = typename FString<ArgsT...>::t;
1241 
1242 template <typename OutputItT>
1243 struct FormatToNResult final {
1244  OutputItT out;
1245  size_t size{0};
1246  bool truncated{false};
1247 };
1248 
1249 struct FormatToResult final {
1250  char* out{nullptr};
1251  size_t size{0};
1252  bool truncated{false};
1253 };
1254 
1255 ////////////////////////////////////////////////////////////////
1256 /// Public API
1257 ////////////////////////////////////////////////////////////////
1258 
1259 /**
1260  * @brief Builds a type-erased argument store from a parameter pack.
1261  *
1262  * @tparam ArgsT Argument types.
1263  * @param args Argument values.
1264  * @return Argument store usable by the format engine.
1265  */
1266 template <typename... ArgsT>
1268 
1269 /**
1270  * @brief Formats @p args into @p out, writing at most @p n characters.
1271  *
1272  * @details
1273  * Placeholders in @p fmt are substituted with @p args in order. When the produced text would
1274  * exceed @p n the output is truncated and @c truncated is set to @c true. The caller is
1275  * responsible for null termination if needed.
1276  *
1277  * @tparam ArgsT Argument types (deduced).
1278  * @param out Destination buffer with capacity of at least @p n bytes.
1279  * @param n Maximum characters to write, not counting a null terminator.
1280  * @param fmt Format string with @c {} placeholders.
1281  * @param args Arguments to substitute.
1282  * @return @c FormatToNResult describing the end iterator, total size and truncation flag.
1283  */
1284 template <typename... ArgsT>
1285 inline FormatToNResult<char*> format_to_n(char* out, size_t n, format_string<ArgsT...> fmt, const ArgsT&... args);
1286 
1287 /**
1288  * @brief Formats @p args into a fixed-size character array; equivalent to @c format_to_n.
1289  *
1290  * @tparam NumT Array size (deduced).
1291  * @tparam ArgsT Argument types.
1292  * @param out Destination array.
1293  * @param fmt Format string.
1294  * @param args Arguments to substitute.
1295  * @return @c FormatToResult describing the end pointer, total size and truncation flag.
1296  */
1297 template <size_t NumT, typename... ArgsT>
1298 inline FormatToResult format_to(char (&out)[NumT], format_string<ArgsT...> fmt, const ArgsT&... args);
1299 
1300 /**
1301  * @brief Formats @p args through an output iterator.
1302  *
1303  * @details
1304  * Writes each character via @c *out++ = @c c. The iterator must satisfy the OutputIterator
1305  * concept; arrays are explicitly excluded so the fixed-array overload wins overload resolution.
1306  *
1307  * @tparam OutputItT Output iterator type.
1308  * @tparam ArgsT Argument types.
1309  * @param out Destination iterator.
1310  * @param fmt Format string.
1311  * @param args Arguments to substitute.
1312  * @return Iterator one past the last written character.
1313  */
1314 template <typename OutputItT, typename... ArgsT,
1315  // NOLINTNEXTLINE(modernize-use-constraints)
1316  std::enable_if_t<detail::kIsOutputIterator<detail::RemoveCvref<OutputItT>> &&
1317  !std::is_array_v<std::remove_reference_t<OutputItT>>,
1318  int> = 0>
1319 inline detail::RemoveCvref<OutputItT> format_to(OutputItT&& out, format_string<ArgsT...> fmt, const ArgsT&... args);
1320 
1321 /**
1322  * @brief Formats @p args into a newly allocated @c std::string.
1323  *
1324  * @details
1325  * Convenience wrapper over the iterator @c format_to; the only entry point that allocates.
1326  * Hot paths should prefer @c format_to_n with a caller-owned buffer.
1327  *
1328  * @tparam ArgsT Argument types.
1329  * @param fmt Format string.
1330  * @param args Arguments to substitute.
1331  * @return Formatted result.
1332  */
1333 template <typename... ArgsT>
1334 [[nodiscard]] inline std::string format(format_string<ArgsT...> fmt, const ArgsT&... args);
1335 
1336 } // namespace format
1337 
1338 ////////////////////////////////////////////////////////////////
1339 /// Details
1340 ////////////////////////////////////////////////////////////////
1341 
1342 namespace format {
1343 namespace detail {
1344 
1345 // NOLINTBEGIN
1346 template <typename UIntT>
1347 inline int count_digits(UIntT n) noexcept {
1348  int count = 1;
1349 
1350  while (n >= 10) {
1351  n /= 10;
1352  ++count;
1353  }
1354 
1355  return count;
1356 }
1357 
1358 template <typename UIntT>
1359 inline void write_int_digits(char* buf, UIntT value, int num_digits) noexcept {
1360  char* end = buf + num_digits;
1361 
1362  while (value >= 10) {
1363  auto digit = static_cast<unsigned>(value % 10);
1364  *--end = static_cast<char>('0' + digit);
1365  value /= 10;
1366  }
1367 
1368  *--end = static_cast<char>('0' + value);
1369 }
1370 
1371 inline size_t format_uint_to(char* buf, unsigned value) noexcept {
1372  int num_digits = count_digits(value);
1373  write_int_digits(buf, value, num_digits);
1374 
1375  return static_cast<size_t>(num_digits);
1376 }
1377 
1378 inline size_t format_int_to(char* buf, int value) noexcept {
1379  if (value < 0) {
1380  buf[0] = '-';
1381  unsigned u = static_cast<unsigned>(-(value + 1)) + 1;
1382 
1383  return 1 + format_uint_to(buf + 1, u);
1384  }
1385 
1386  return format_uint_to(buf, static_cast<unsigned>(value));
1387 }
1388 
1389 inline size_t format_ulong_long_to(char* buf, unsigned long long value) noexcept {
1390  int num_digits = count_digits(value);
1391  write_int_digits(buf, value, num_digits);
1392 
1393  return static_cast<size_t>(num_digits);
1394 }
1395 
1396 inline size_t format_long_long_to(char* buf, long long value) noexcept {
1397  if (value < 0) {
1398  buf[0] = '-';
1399  unsigned long long u = static_cast<unsigned long long>(-(value + 1)) + 1;
1400 
1401  return 1 + format_ulong_long_to(buf + 1, u);
1402  }
1403 
1404  return format_ulong_long_to(buf, static_cast<unsigned long long>(value));
1405 }
1406 
1407 inline size_t format_base_digits_to(char (&buf)[64], unsigned long long value, unsigned base_bits,
1408  bool upper) noexcept {
1409  static constexpr const char kLowerDigits[] = "0123456789abcdef";
1410  static constexpr const char kUpperDigits[] = "0123456789ABCDEF";
1411  const char* digit_chars = upper ? kUpperDigits : kLowerDigits;
1412  const unsigned mask = (1U << base_bits) - 1U;
1413  char* p = buf + sizeof(buf);
1414 
1415  do {
1416  *--p = digit_chars[value & mask];
1417  value >>= base_bits;
1418  } while (value != 0U);
1419 
1420  return static_cast<size_t>(buf + sizeof(buf) - p);
1421 }
1422 // NOLINTEND
1423 
1424 } // namespace detail
1425 } // namespace format
1426 
1427 inline format::detail::StringWriter::StringWriter(char* buf, size_t size) noexcept
1428  : begin_(buf), ptr_(buf), end_(buf + size) {}
1429 
1430 inline char* format::detail::StringWriter::out() const noexcept { return ptr_; }
1431 
1432 inline size_t format::detail::StringWriter::written() const noexcept { return static_cast<size_t>(ptr_ - begin_); }
1433 
1434 inline size_t format::detail::StringWriter::total_size() const noexcept { return total_size_; }
1435 
1437  ++total_size_;
1438 
1439  if VLIKELY (ptr_ < end_) {
1440  *ptr_++ = c;
1441  }
1442 }
1443 
1444 inline void format::detail::StringWriter::write(const char* s, size_t count) {
1445  total_size_ += count;
1446 
1447  auto avail = static_cast<size_t>(end_ - ptr_);
1448  size_t n = (count <= avail) ? count : avail;
1449 
1450  if VLIKELY (n > 0) {
1451  std::memcpy(ptr_, s, n);
1452  ptr_ += n;
1453  }
1454 }
1455 
1456 inline void format::detail::StringWriter::write(std::string_view sv) { write(sv.data(), sv.size()); }
1457 
1458 inline void format::detail::StringWriter::write_fill(char fill, size_t count) {
1459  total_size_ += count;
1460 
1461  const auto avail = static_cast<size_t>(end_ - ptr_);
1462  const size_t n = count <= avail ? count : avail;
1463 
1464  if VLIKELY (n > 0U) {
1465  std::memset(ptr_, fill, n);
1466  ptr_ += n;
1467  }
1468 }
1469 
1470 template <typename... ArgsT>
1472  const ArgsT&... args) {
1474 }
1475 
1476 template <typename... ArgsT>
1477 inline format::FormatToNResult<char*> format::format_to_n(char* out, size_t n, format_string<ArgsT...> fmt,
1478  const ArgsT&... args) {
1479  format::detail::StringWriter sw(out, n);
1481  std::string_view remaining = fmt.get();
1482  size_t arg_id = 0;
1483 
1484  if VLIKELY (writer.try_format(remaining, arg_id, args...)) {
1485  size_t total = writer.total_size();
1486 
1487  return {writer.out(), total, total > n};
1488  }
1489 
1490  format::detail::FormatArgStore<char, format::detail::RemoveCvref<ArgsT>...> arg_store{args...};
1491  format::detail::FormatArgs fargs(arg_store);
1492  writer.format(remaining, fargs, arg_id);
1493 
1494  size_t total = writer.total_size();
1495 
1496  return {writer.out(), total, total > n};
1497 }
1498 
1499 template <size_t NumT, typename... ArgsT>
1500 inline format::FormatToResult format::format_to(char (&out)[NumT], format_string<ArgsT...> fmt, const ArgsT&... args) {
1501  auto result = ::vlink::format::format_to_n(out, NumT, fmt, args...);
1502 
1503  return {result.out, result.size, result.truncated};
1504 }
1505 
1506 template <typename OutputItT, typename... ArgsT,
1507  std::enable_if_t<format::detail::kIsOutputIterator<format::detail::RemoveCvref<OutputItT>> &&
1508  !std::is_array_v<std::remove_reference_t<OutputItT>>,
1509  int>>
1510 inline format::detail::RemoveCvref<OutputItT> format::format_to(OutputItT&& out, format_string<ArgsT...> fmt,
1511  const ArgsT&... args) {
1512  using ItT = format::detail::RemoveCvref<OutputItT>;
1513 
1514  auto arg_store = ::vlink::format::make_format_args(args...);
1515 
1516  format::detail::FormatArgs fargs(arg_store);
1517  format::detail::IteratorWriter<ItT> iter_writer(out);
1518  format::detail::FormatWriter<char, format::detail::IteratorWriter<ItT>> writer(iter_writer);
1519 
1520  writer.format(fmt.get(), fargs);
1521 
1522  return writer.out();
1523 }
1524 
1525 template <typename... ArgsT>
1526 inline std::string format::format(format_string<ArgsT...> fmt, const ArgsT&... args) {
1527  char buf[256];
1528  const auto result = ::vlink::format::format_to_n(buf, sizeof(buf), fmt, args...);
1529 
1530  if VLIKELY (!result.truncated) {
1531  return std::string(buf, result.size);
1532  }
1533 
1534  std::string full(result.size, '\0');
1535  (void)::vlink::format::format_to_n(full.data(), full.size(), fmt, args...);
1536 
1537  return full;
1538 }
1539 
1540 } // namespace vlink
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLINK_EXPORT
Definition: macros.h:81
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284