Skip to content

Commit

Permalink
ICU-22696 Add implicit conversion from StringPiece to std::string_view.
Browse files Browse the repository at this point in the history
This will allow ICU4C to seamlessly use std::string_view internally
while continuing to use StringPiece in the public API.
  • Loading branch information
roubert committed Jul 30, 2024
1 parent 5d7cbdb commit 8891c07
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
11 changes: 11 additions & 0 deletions icu4c/source/common/unicode/stringpiece.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#if U_SHOW_CPLUSPLUS_API

#include <cstddef>
#include <string_view>
#include <type_traits>

#include "unicode/uobject.h"
Expand Down Expand Up @@ -176,6 +177,16 @@ class U_COMMON_API StringPiece : public UMemory {
*/
StringPiece(const StringPiece& x, int32_t pos, int32_t len);

#ifndef U_HIDE_INTERNAL_API
/**
* Converts to a std::string_view().
* @internal
*/
inline operator std::string_view() const {
return {data(), static_cast<std::string_view::size_type>(size())};
}
#endif // U_HIDE_INTERNAL_API

/**
* Returns the string pointer. May be nullptr if it is empty.
*
Expand Down
5 changes: 5 additions & 0 deletions icu4c/source/test/intltest/strtest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,11 @@ StringTest::TestStringPieceStringView() {

assertEquals("size()", piece.size(), view.size());
assertEquals("data()", piece.data(), view.data());

std::string_view v2 = piece; // Internal implicit conversion.

assertEquals("size()", piece.size(), v2.size());
assertEquals("data()", piece.data(), v2.data());
}

void
Expand Down

0 comments on commit 8891c07

Please sign in to comment.