Skip to content

Commit 2db67e9

Browse files
committed
[libc++] Fix the return value of max_size()
I assume nobody ever uses std::string_view::max_size() outside of testing. However, we should still return a value that is based on something with a reasonable rationale. Previously, we would forget to take into account the size of the character type stored in the string, and this patch takes that into account. Thanks to @mclow.lists for pointing out this issue. Differential Revision: https://reviews.llvm.org/D114395
1 parent a101a9b commit 2db67e9

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

libcxx/include/string_view

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ public:
356356
size_type length() const _NOEXCEPT { return __size; }
357357

358358
_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
359-
size_type max_size() const _NOEXCEPT { return numeric_limits<size_type>::max(); }
359+
size_type max_size() const _NOEXCEPT { return numeric_limits<size_type>::max() / sizeof(value_type); }
360360

361361
_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
362362
bool empty() const _NOEXCEPT { return __size == 0; }

libcxx/test/std/strings/string.view/string.view.capacity/capacity.pass.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
#include <string_view>
1818
#include <cassert>
19+
#include <limits>
1920

2021
#include "test_macros.h"
2122

@@ -42,6 +43,16 @@ void test1 () {
4243
assert ( sv1.size() == sv1.length());
4344
assert ( sv1.max_size() > sv1.size());
4445
}
46+
47+
// Sanity check max_size() -- a string_view can't store more bytes than a single object
48+
// can contain. Any implementation that fails this check is certainly lying.
49+
{
50+
typedef typename SV::value_type CharT;
51+
typedef typename SV::size_type Size;
52+
SV sv;
53+
assert(sv.max_size() <= std::numeric_limits<Size>::max() / sizeof(CharT));
54+
LIBCPP_ASSERT(sv.max_size() == std::numeric_limits<Size>::max() / sizeof(CharT));
55+
}
4556
}
4657

4758
template<typename CharT>

0 commit comments

Comments
 (0)