Skip to content

<charconv>: instead of memcpy'ing the result you can calculate necessary buffer size ahead of time for integers #1024

@toughengineer

Description

@toughengineer

For integers instead of filling the buffer from right to left and memcpy'ing the result back so the most significant digit (that is written last) ends up in the leftmost position, you can calculate the necessary buffer size ahead of time and put all the digits exactly at their final destination place.

See example in libc++:
https://github.com/llvm/llvm-project/blob/f54402b63a4f5b0b4b15e0f82ce8ff8501b206e6/libcxx/include/charconv#L164-L168
straight from the Bit Twiddling Hacks:
https://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10

memcpy usage here:

STL/stl/inc/charconv

Lines 137 to 146 in 550713e

const ptrdiff_t _Digits_written = _Buff_end - _RNext;
if (_Last - _First < _Digits_written) {
return {_Last, errc::value_too_large};
}
_CSTD memcpy(_First, _RNext, static_cast<size_t>(_Digits_written));
return {_First + _Digits_written, errc{}};
}

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions