clean up integer_to_str() function

This commit is contained in:
arvidn 2018-11-16 02:39:31 +01:00 committed by Arvid Norberg
parent 66a8f133b0
commit 7538d68086
4 changed files with 28 additions and 16 deletions

View File

@ -97,15 +97,13 @@ namespace detail {
static_assert(sizeof(entry::integer_type) <= 8, "64 bit integers required");
static_assert(sizeof(data) <= sizeof(entry::integer_type), "input data too big, see entry::integer_type");
char buf[21];
int ret = 0;
for (char const* str = integer_to_str(buf, 21, val);
*str != 0; ++str)
auto const str = integer_to_str(buf, val);
for (char const c : str)
{
*out = *str;
*out = c;
++out;
++ret;
}
return ret;
return static_cast<int>(str.size());
}
template <class OutIt>

View File

@ -342,9 +342,9 @@ namespace aux {
namespace detail {
TORRENT_EXPORT char const* integer_to_str(char* buf, int size
, entry::integer_type val);
}
TORRENT_EXTRA_EXPORT string_view integer_to_str(span<char> buf
, entry::integer_type val);
}
#if TORRENT_USE_IOSTREAM
// prints the bencoded structure to the ostream as a JSON-style structure.

View File

@ -45,7 +45,7 @@ namespace libtorrent {
namespace detail {
char const* integer_to_str(char* buf, int size
string_view integer_to_str(span<char> buf
, entry::integer_type val)
{
int sign = 0;
@ -54,15 +54,17 @@ namespace detail {
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
while (size > sign && val != 0)
char* ptr = &buf.back();
*ptr-- = '\0';
if (val == 0) *ptr-- = '0';
while (ptr > buf.data() + sign && val != 0)
{
buf[--size] = '0' + char(val % 10);
*ptr-- = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
if (sign) *ptr-- = '-';
++ptr;
return {ptr, static_cast<std::size_t>(&buf.back() - ptr)};
}
} // detail

View File

@ -228,6 +228,18 @@ TORRENT_TEST(print_deep_dict)
TEST_EQUAL(e.to_string(), "{\n 'a': 'foobar',\n 'ints': [\n 1,\n 2,\n 3 ],\n 'strings': [\n 'foo',\n 'bar' ] }");
}
TORRENT_TEST(integer_to_str)
{
using lt::detail::integer_to_str;
char buf[30];
TEST_CHECK(integer_to_str(buf, 0) == "0"_sv);
TEST_CHECK(integer_to_str(buf, 1234) == "1234"_sv);
TEST_CHECK(integer_to_str(buf, -1234) == "-1234"_sv);
TEST_CHECK(integer_to_str(buf, 123456789012345678LL) == "123456789012345678"_sv);
TEST_CHECK(integer_to_str(buf, -123456789012345678LL) == "-123456789012345678"_sv);
}
TORRENT_TEST(lazy_entry)
{
{