diff --git a/include/libtorrent/bencode.hpp b/include/libtorrent/bencode.hpp index 6117a62e0..57382b761 100644 --- a/include/libtorrent/bencode.hpp +++ b/include/libtorrent/bencode.hpp @@ -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(str.size()); } template diff --git a/include/libtorrent/entry.hpp b/include/libtorrent/entry.hpp index 6be8a501f..c7d410e42 100644 --- a/include/libtorrent/entry.hpp +++ b/include/libtorrent/entry.hpp @@ -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 buf + , entry::integer_type val); +} #if TORRENT_USE_IOSTREAM // prints the bencoded structure to the ostream as a JSON-style structure. diff --git a/src/entry.cpp b/src/entry.cpp index 312df40b2..23a81c721 100644 --- a/src/entry.cpp +++ b/src/entry.cpp @@ -45,7 +45,7 @@ namespace libtorrent { namespace detail { - char const* integer_to_str(char* buf, int size + string_view integer_to_str(span 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(&buf.back() - ptr)}; } } // detail diff --git a/test/test_bencoding.cpp b/test/test_bencoding.cpp index afb841986..6814dac3c 100644 --- a/test/test_bencoding.cpp +++ b/test/test_bencoding.cpp @@ -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) { {