summaryrefslogtreecommitdiff
path: root/base/strings/string_piece.h
diff options
context:
space:
mode:
Diffstat (limited to 'base/strings/string_piece.h')
-rw-r--r--base/strings/string_piece.h25
1 files changed, 21 insertions, 4 deletions
diff --git a/base/strings/string_piece.h b/base/strings/string_piece.h
index a83b7d8f66..31e7596d11 100644
--- a/base/strings/string_piece.h
+++ b/base/strings/string_piece.h
@@ -28,8 +28,8 @@
#include <string>
#include "base/base_export.h"
-#include "base/basictypes.h"
#include "base/containers/hash_tables.h"
+#include "base/logging.h"
#include "base/strings/string16.h"
namespace base {
@@ -143,6 +143,14 @@ BASE_EXPORT StringPiece16 substr(const StringPiece16& self,
size_t pos,
size_t n);
+#if DCHECK_IS_ON()
+// Asserts that begin <= end to catch some errors with iterator usage.
+BASE_EXPORT void AssertIteratorsInOrder(std::string::const_iterator begin,
+ std::string::const_iterator end);
+BASE_EXPORT void AssertIteratorsInOrder(string16::const_iterator begin,
+ string16::const_iterator end);
+#endif
+
} // namespace internal
// BasicStringPiece ------------------------------------------------------------
@@ -180,9 +188,18 @@ template <typename STRING_TYPE> class BasicStringPiece {
BasicStringPiece(const value_type* offset, size_type len)
: ptr_(offset), length_(len) {}
BasicStringPiece(const typename STRING_TYPE::const_iterator& begin,
- const typename STRING_TYPE::const_iterator& end)
- : ptr_((end > begin) ? &(*begin) : NULL),
- length_((end > begin) ? (size_type)(end - begin) : 0) {}
+ const typename STRING_TYPE::const_iterator& end) {
+#if DCHECK_IS_ON()
+ // This assertion is done out-of-line to avoid bringing in logging.h and
+ // instantiating logging macros for every instantiation.
+ internal::AssertIteratorsInOrder(begin, end);
+#endif
+ length_ = static_cast<size_t>(std::distance(begin, end));
+
+ // The length test before assignment is to avoid dereferencing an iterator
+ // that may point to the end() of a string.
+ ptr_ = length_ > 0 ? &*begin : nullptr;
+ }
// data() may return a pointer to a buffer with embedded NULs, and the
// returned buffer may or may not be null terminated. Therefore it is