From f219dcd59bec67d5091c4d3f1aff503f235f0191 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Tue, 24 Dec 2019 10:11:47 -0800 Subject: [PATCH] Add fmt::bytes --- include/fmt/core.h | 9 +++++---- include/fmt/format.h | 16 ++++++++++++++++ test/format-test.cc | 6 ++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/include/fmt/core.h b/include/fmt/core.h index 9c435f53..ad6143da 100644 --- a/include/fmt/core.h +++ b/include/fmt/core.h @@ -1513,8 +1513,8 @@ FMT_API void vprint_mojibake(std::FILE*, string_view, format_args); /** \rst - Prints formatted data to the file *f*. For wide format strings *f* should be - in wide-oriented mode set via ``fwide(f, 1)``. + Prints formatted data to the file *f*. Strings are assumed to be + Unicode-encoded unless the ``FMT_UNICODE`` macro is set to 0. **Example**:: @@ -1535,8 +1535,9 @@ inline void print(std::FILE* f, const S& format_str, Args&&... args) { /** \rst - Formats ``args`` according to specifications in ``format_str`` and writes the - output to ``stdout``. + Formats ``args`` according to specifications in ``format_str`` and writes + the output to ``stdout``. Strings are assumed to be Unicode-encoded unless + the ``FMT_UNICODE`` macro is set to 0. **Example**:: diff --git a/include/fmt/format.h b/include/fmt/format.h index e1b34d19..3e29abac 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -3112,6 +3112,22 @@ template inline const void* ptr(const std::shared_ptr& p) { return p.get(); } +class bytes { + private: + string_view data_; + friend struct formatter; + + public: + explicit bytes(string_view data) : data_(data) {} +}; + +template <> struct formatter : formatter { + template + auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) { + return formatter::format(b.data_, ctx); + } +}; + template struct arg_join : internal::view { It begin; It end; diff --git a/test/format-test.cc b/test/format-test.cc index 6eee9fe6..1ba74d27 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1766,6 +1766,12 @@ TEST(FormatTest, Dynamic) { EXPECT_EQ("42 and abc1 and 1.5", result); } +TEST(FormatTest, Bytes) { + auto s = fmt::format("{:10}", fmt::bytes("ёжик")); + EXPECT_EQ("ёжик ", s); + EXPECT_EQ(10, s.size()); +} + TEST(FormatTest, JoinArg) { using fmt::join; int v1[3] = {1, 2, 3};