Skip to content

capped append, assign and insert #81

@GitSparTV

Description

@GitSparTV

Hello, I've found a few cases when I have to write excessively long expressions while using this library, I want to share them and propose new methods.

Currently append, assign and insert will throw an exception if the final size is greater than the capacity. Due to this I had to write something like this in my code:

boost::static_string<128> str;

str.assign(some_runtime_info, 0, str.max_size() - str.size());
str.append(" "sv, 0, str.max_size() - str.size());
str.append(something_else, 0, str.max_size() - str.size());

In this example str is a small name for a variable, but in reality it might be a long chain of nested structures.
Notice I had to append single char as a string_view so I can cap it to the buffer size.
That's because str.append(std::min(str.max_size() - str.size(), 1), ' '); is longer.

I propose to add additional methods named capped_append/capped_assign/capped_insert that will add characters up to string capacity.
I saw there is capped_length, so chose it. It could be safe_append, trim_append, cap_append, clip_append, limit_append, bounded_append, truncating_append, fit_append, max_append, shrink_append, you name it.

std::inplace_vector has somewhat similar API: emplace_back, try_emplace_back, unchecked_emplace_back. Their naming will not be suitable because try_* method is trying to emplace single item (single char in terms of std::inplace_vector<char, N>) – my problem wasn't "try to emplace a whole string or ignore" type of situation. And unchecked_* method is not what I propose, however, it could be discussed as well.

I'm also willing to contribute a PR for these methods if you are open for them and we agree on the design

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions