From bce1206c7002141af69266a025b039fa8ae7d65b Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Mon, 29 Jan 2018 08:19:14 -0800 Subject: [PATCH] ircd::util: Add string construction buffer closures over a common pattern. --- include/ircd/util/util.h | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/include/ircd/util/util.h b/include/ircd/util/util.h index 3da6327a2..18eadeaef 100644 --- a/include/ircd/util/util.h +++ b/include/ircd/util/util.h @@ -169,6 +169,37 @@ string(const uint8_t *const &buf, return string(reinterpret_cast(buf), size); } +/// Close over the common pattern to write directly into a post-C++11 standard +/// string through the data() member requiring a const_cast. Closure returns +/// the final size of the data written into the buffer. +inline auto +string(const size_t &size, + const std::function &closure) +{ + std::string ret(size, char{}); + const mutable_buffer buf + { + const_cast(ret.data()), ret.size() + }; + + ret.resize(closure(buf)); + return ret; +} + +/// Close over the common pattern to write directly into a post-C++11 standard +/// string through the data() member requiring a const_cast. Closure returns +/// a view of the data actually written to the buffer. +inline auto +string(const size_t &size, + const std::function &closure) +{ + return string(size, [&closure] + (const mutable_buffer &buffer) + { + return ircd::size(closure(buffer)); + }); +} + // // Misc bang participants //