Kagome
Polkadot Runtime Engine in C++17
peer_id_formatter.hpp
Go to the documentation of this file.
1 
6 #include <fmt/format.h>
7 #include <libp2p/peer/peer_id.hpp>
8 #include <string_view>
9 
10 #ifndef KAGOME__FMT_FORMATTER_PEERID
11 #define KAGOME__FMT_FORMATTER_PEERID
12 
13 #include <fmt/format.h>
14 #include <libp2p/peer/peer_id.hpp>
15 
16 template <>
17 struct fmt::formatter<libp2p::peer::PeerId> {
18  // Presentation format: 's' - short, 'l' - long.
19  char presentation = 's';
20 
21  // Parses format specifications of the form ['s' | 'l'].
22  constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) {
23  // Parse the presentation format and store it in the formatter:
24  auto it = ctx.begin(), end = ctx.end();
25  if (it != end && (*it == 's' || *it == 'l')) {
26  presentation = *it++;
27  }
28 
29  // Check if reached the end of the range:
30  if (it != end && *it != '}') {
31  throw format_error("invalid format");
32  }
33 
34  // Return an iterator past the end of the parsed range:
35  return it;
36  }
37 
38  // Formats the Blob using the parsed format specification (presentation)
39  // stored in this formatter.
40  template <typename FormatContext>
41  auto format(const libp2p::peer::PeerId &peer_id, FormatContext &ctx)
42  -> decltype(ctx.out()) {
43  // ctx.out() is an output iterator to write to.
44 
45  auto &&b58 = peer_id.toBase58();
46 
47  if (presentation == 's') {
48  return format_to(ctx.out(),
49  "…{}",
50  std::string_view(b58.data() + b58.size()
51  - std::min<size_t>(6, b58.size()),
52  std::min<size_t>(6, b58.size())));
53  }
54 
55  return format_to(ctx.out(), "{}", b58);
56  }
57 };
58 
59 #endif // KAGOME__FMT_FORMATTER_PEERID
constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin())
auto format(const libp2p::peer::PeerId &peer_id, FormatContext &ctx) -> decltype(ctx.out())
libp2p::peer::PeerId PeerId