Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// tinyformat.h2// Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com]3//4// Boost Software License - Version 1.05//6// Permission is hereby granted, free of charge, to any person or organization7// obtaining a copy of the software and accompanying documentation covered by8// this license (the "Software") to use, reproduce, display, distribute,9// execute, and transmit the Software, and to prepare derivative works of the10// Software, and to permit third-parties to whom the Software is furnished to11// do so, all subject to the following:12//13// The copyright notices in the Software and this entire statement, including14// the above license grant, this restriction and the following disclaimer,15// must be included in all copies of the Software, in whole or in part, and16// all derivative works of the Software, unless such copies or derivative17// works are solely in the form of machine-executable object code generated by18// a source language processor.19//20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR21// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,22// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT23// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE24// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,25// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER26// DEALINGS IN THE SOFTWARE.28//------------------------------------------------------------------------------29// Tinyformat: A minimal type safe printf replacement30//31// tinyformat.h is a type safe printf replacement library in a single C++32// header file. Design goals include:33//34// * Type safety and extensibility for user defined types.35// * C99 printf() compatibility, to the extent possible using std::ostream36// * POSIX extension for positional arguments37// * Simplicity and minimalism. A single header file to include and distribute38// with your projects.39// * Augment rather than replace the standard stream formatting mechanism40// * C++98 support, with optional C++11 niceties41//42//43// Main interface example usage44// ----------------------------45//46// To print a date to std::cout for American usage:47//48// std::string weekday = "Wednesday";49// const char* month = "July";50// size_t day = 27;51// long hour = 14;52// int min = 44;53//54// tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min);55//56// POSIX extension for positional arguments is available.57// The ability to rearrange formatting arguments is an important feature58// for localization because the word order may vary in different languages.59//60// Previous example for German usage. Arguments are reordered:61//62// tfm::printf("%1$s, %3$d. %2$s, %4$d:%5$.2d\n", weekday, month, day, hour, min);63//64// The strange types here emphasize the type safety of the interface; it is65// possible to print a std::string using the "%s" conversion, and a66// size_t using the "%d" conversion. A similar result could be achieved67// using either of the tfm::format() functions. One prints on a user provided68// stream:69//70// tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n",71// weekday, month, day, hour, min);72//73// The other returns a std::string:74//75// std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n",76// weekday, month, day, hour, min);77// std::cout << date;78//79// These are the three primary interface functions. There is also a80// convenience function printfln() which appends a newline to the usual result81// of printf() for super simple logging.82//83//84// User defined format functions85// -----------------------------86//87// Simulating variadic templates in C++98 is pretty painful since it requires88// writing out the same function for each desired number of arguments. To make89// this bearable tinyformat comes with a set of macros which are used90// internally to generate the API, but which may also be used in user code.91//92// The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and93// TINYFORMAT_PASSARGS(n) will generate a list of n argument types,94// type/name pairs and argument names respectively when called with an integer95// n between 1 and 16. We can use these to define a macro which generates the96// desired user defined function with n arguments. To generate all 16 user97// defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an98// example, see the implementation of printf() at the end of the source file.99//100// Sometimes it's useful to be able to pass a list of format arguments through101// to a non-template function. The FormatList class is provided as a way to do102// this by storing the argument list in a type-opaque way. Continuing the103// example from above, we construct a FormatList using makeFormatList():104//105// FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min);106//107// The format list can now be passed into any non-template function and used108// via a call to the vformat() function:109//110// tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList);111//112//113// Additional API information114// --------------------------115//116// Error handling: Define TINYFORMAT_ERROR to customize the error handling for117// format strings which are unsupported or have the wrong number of format118// specifiers (calls assert() by default).119//120// User defined types: Uses operator<< for user defined types by default.121// Overload formatValue() for more control.124#ifndef TINYFORMAT_H_INCLUDED125#define TINYFORMAT_H_INCLUDED127namespace tinyformat {}128//------------------------------------------------------------------------------129// Config section. Customize to your liking!131// Namespace alias to encourage brevity132namespace tfm = tinyformat;134// Error handling; calls assert() by default.135#define TINYFORMAT_ERROR(reasonString) throw tinyformat::format_error(reasonString)137// Define for C++11 variadic templates which make the code shorter & more138// general. If you don't define this, C++11 support is autodetected below.139#define TINYFORMAT_USE_VARIADIC_TEMPLATES142//------------------------------------------------------------------------------143// Implementation details.144#include <algorithm>145#include <attributes.h> // Added for Bitcoin Core146#include <iostream>147#include <sstream>148#include <stdexcept> // Added for Bitcoin Core149#include <util/string.h> // Added for Bitcoin Core151#ifndef TINYFORMAT_ASSERT152# include <cassert>153# define TINYFORMAT_ASSERT(cond) assert(cond)154#endif156#ifndef TINYFORMAT_ERROR157# include <cassert>158# define TINYFORMAT_ERROR(reason) assert(0 && reason)159#endif161#if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES)162# ifdef __GXX_EXPERIMENTAL_CXX0X__163# define TINYFORMAT_USE_VARIADIC_TEMPLATES164# endif165#endif167#if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201168// std::showpos is broken on old libstdc++ as provided with macOS. See169// http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html170# define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND171#endif173#ifdef __APPLE__174// Workaround macOS linker warning: Xcode uses different default symbol175// visibilities for static libs vs executables (see issue #25)176# define TINYFORMAT_HIDDEN __attribute__((visibility("hidden")))177#else178# define TINYFORMAT_HIDDEN179#endif181namespace tinyformat {183// Added for Bitcoin Core. Similar to std::runtime_format from C++26.184struct RuntimeFormat {185const std::string& fmt; // Not a string view, because tinyformat requires a c_str186explicit RuntimeFormat(LIFETIMEBOUND const std::string& str) : fmt{str} {}187};189// Added for Bitcoin Core. Wrapper for checking format strings at compile time.190// Unlike ConstevalFormatString this supports RunTimeFormat-wrapped std::string191// for runtime string formatting without compile time checks.192template <unsigned num_params>193struct FormatStringCheck {194consteval FormatStringCheck(const char* str) : fmt{util::ConstevalFormatString<num_params>{str}.fmt} {}195FormatStringCheck(LIFETIMEBOUND const RuntimeFormat& run) : fmt{run.fmt.c_str()} {}196FormatStringCheck(util::ConstevalFormatString<num_params> str) : fmt{str.fmt} {}197operator const char*() { return fmt; }198const char* fmt;199};201// Added for Bitcoin Core202class format_error: public std::runtime_error203{204public:205explicit format_error(const std::string &what): std::runtime_error(what) {206}207};209//------------------------------------------------------------------------------210namespace detail {212// Test whether type T1 is convertible to type T2213template <typename T1, typename T2>214struct is_convertible215{216private:217// two types of different size218struct fail { char dummy[2]; };219struct succeed { char dummy; };220// Try to convert a T1 to a T2 by plugging into tryConvert221static fail tryConvert(...);222static succeed tryConvert(const T2&);223static const T1& makeT1();224public:225# ifdef _MSC_VER226// Disable spurious loss of precision warnings in tryConvert(makeT1())227# pragma warning(push)228# pragma warning(disable:4244)229# pragma warning(disable:4267)230# endif231// Standard trick: the (...) version of tryConvert will be chosen from232// the overload set only if the version taking a T2 doesn't match.233// Then we compare the sizes of the return types to check which234// function matched. Very neat, in a disgusting kind of way :)235static constexpr bool value =236sizeof(tryConvert(makeT1())) == sizeof(succeed);237# ifdef _MSC_VER238# pragma warning(pop)239# endif240};243// Detect when a type is not a wchar_t string244template<typename T> struct is_wchar { typedef int tinyformat_wchar_is_not_supported; };245template<> struct is_wchar<wchar_t*> {};246template<> struct is_wchar<const wchar_t*> {};247template<int n> struct is_wchar<const wchar_t[n]> {};248template<int n> struct is_wchar<wchar_t[n]> {};
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.