2021-03-11 01:01:43 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <llarp/util/buffer.hpp>
|
2022-07-16 00:41:14 +00:00
|
|
|
#include <llarp/util/formattable.hpp>
|
2021-03-11 01:01:43 +00:00
|
|
|
|
|
|
|
#include <string_view>
|
|
|
|
#include <type_traits>
|
|
|
|
#include <cstddef>
|
|
|
|
#include <iosfwd>
|
|
|
|
|
|
|
|
namespace llarp
|
|
|
|
{
|
|
|
|
// Buffer printer lets you print a string as a nicely formatted buffer with a hex breakdown and
|
|
|
|
// visual representation of the data for logging purposes. Wraps the string data with a object
|
|
|
|
// that prints the buffer format during output; use as:
|
|
|
|
//
|
2022-07-16 00:41:14 +00:00
|
|
|
// fmt::print("{}", buffer_printer(my_buffer));
|
|
|
|
//
|
|
|
|
// or similarly in a log statement.
|
2021-03-11 01:01:43 +00:00
|
|
|
//
|
|
|
|
struct buffer_printer
|
|
|
|
{
|
|
|
|
std::basic_string_view<std::byte> buf;
|
|
|
|
|
|
|
|
// Constructed from any type of string_view<T> for a single-byte T (char, std::byte, uint8_t,
|
|
|
|
// etc.)
|
|
|
|
template <typename T, typename = std::enable_if_t<sizeof(T) == 1>>
|
|
|
|
explicit buffer_printer(std::basic_string_view<T> buf)
|
|
|
|
: buf{reinterpret_cast<const std::byte*>(buf.data()), buf.size()}
|
|
|
|
{}
|
|
|
|
|
2021-03-12 13:50:21 +00:00
|
|
|
// Constructed from any type of lvalue string<T> for a single-byte T (char, std::byte, uint8_t,
|
|
|
|
// etc.)
|
2021-03-11 01:01:43 +00:00
|
|
|
template <typename T, typename = std::enable_if_t<sizeof(T) == 1>>
|
|
|
|
explicit buffer_printer(const std::basic_string<T>& buf)
|
|
|
|
: buffer_printer(std::basic_string_view<T>{buf})
|
|
|
|
{}
|
|
|
|
|
2021-03-12 13:50:21 +00:00
|
|
|
// *Not* constructable from a string<T> rvalue (because we only hold a view and do not take
|
|
|
|
// ownership).
|
2021-03-11 01:01:43 +00:00
|
|
|
template <typename T, typename = std::enable_if_t<sizeof(T) == 1>>
|
|
|
|
explicit buffer_printer(std::basic_string<T>&& buf) = delete;
|
|
|
|
|
|
|
|
// Constructable from a (T*, size) argument pair, for byte-sized T's.
|
|
|
|
template <typename T, typename = std::enable_if_t<sizeof(T) == 1>>
|
|
|
|
explicit buffer_printer(const T* data, size_t size)
|
|
|
|
: buffer_printer(std::basic_string_view<T>{data, size})
|
|
|
|
{}
|
|
|
|
|
|
|
|
// llarp_buffer_t printer:
|
|
|
|
explicit buffer_printer(const llarp_buffer_t& buf)
|
|
|
|
: buffer_printer(std::basic_string_view<byte_t>{buf.base, buf.sz})
|
|
|
|
{}
|
2022-07-16 00:41:14 +00:00
|
|
|
|
|
|
|
std::string
|
|
|
|
ToString() const;
|
2021-03-11 01:01:43 +00:00
|
|
|
};
|
2022-07-16 00:41:14 +00:00
|
|
|
|
|
|
|
template <>
|
|
|
|
constexpr inline bool IsToStringFormattable<buffer_printer> = true;
|
2021-03-12 13:50:21 +00:00
|
|
|
} // namespace llarp
|