Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

build string in-place? #22

Open
jwdevel opened this issue May 1, 2021 · 3 comments
Open

build string in-place? #22

jwdevel opened this issue May 1, 2021 · 3 comments
Labels
Feature New feature or request

Comments

@jwdevel
Copy link

jwdevel commented May 1, 2021

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?

@sdkrystian
Copy link
Member

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 sdkrystian added the Feature New feature or request label Oct 25, 2021
@WPMGPRoSToTeMa
Copy link

WPMGPRoSToTeMa commented Oct 20, 2022

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

@vinniefalco
Copy link
Member

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Feature New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants