static_string icon indicating copy to clipboard operation
static_string copied to clipboard

build string in-place?

Open jwdevel opened this issue 4 years ago • 3 comments

I cannot find a way to do this, so I suppose it is a feature request (unless I miss something).

I want to have a static_string allocated, then write some data into it via fmt::format_to_n (or you could imagine snprintf, etc), and then tell it "here is your new length." I am trying to avoid an extra copy.

eg:

static_string<10> str;
auto ret = fmt::format_to_n(
   str.data(),
   str.capacity(),
   "foo {}"
   123);
auto length = ret.out - str.data();
str.set_length_to(length);     // this function does not exist

I cannot use resize() because that will stomp the data with char(), which is 0.

Note: one alternative is to pass an insertion iterator, like so:

fmt::format_to_n(
  std::back_inserter(str),
  ...);

However, this repeatedly calls push_back on the string, which repeatedly null-terminates the data unnecessarily. Only the final null terminator matters, so the others are wasted work.

Or maybe there is a way to do this already, which I am missing?

jwdevel avatar May 01 '21 20:05 jwdevel

Currently, there is no way to do this. However, in Boost.JSON we permit access to characters in the range [size(), capacity()) for this exact purpose -- @vinniefalco @pdimov thoughts?

sdkrystian avatar May 12 '21 15:05 sdkrystian

C++23 introduces resize_and_overwrite member for basic_string. I think implementing it for the static_string should solve the described problem.

WPMGPRoSToTeMa avatar Oct 20 '22 00:10 WPMGPRoSToTeMa

Not strictly related to static_string, but the design of resize_and_overwrite is defective because of how it mandates an inversion of the flow of control. It makes some useful idioms impossible to express, in favor of "safety no matter what" (which was never a core C++ principle).

vinniefalco avatar Oct 20 '22 17:10 vinniefalco