From 0cb5bc6707dbf605c2fa2a369233048cefe0ce8b Mon Sep 17 00:00:00 2001 From: Fredrik Roubert Date: Wed, 11 Sep 2024 18:52:52 +0200 Subject: [PATCH] ICU-22843 Disambiguate UnicodeString::readOnlyAlias() for MSVC. Both std::u16string_view and std::wstring_view are possible matches for UnicodeString as a template parameter, but adding an explicit overload avoids both having to make that choice and taking the detour through creating any string view at all. --- icu4c/source/common/unicode/unistr.h | 24 ++++++++++++++++++++++++ icu4c/source/common/unistr.cpp | 10 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/icu4c/source/common/unicode/unistr.h b/icu4c/source/common/unicode/unistr.h index 41743f4f541c..477dea301ab0 100644 --- a/icu4c/source/common/unicode/unistr.h +++ b/icu4c/source/common/unicode/unistr.h @@ -3600,6 +3600,29 @@ class U_COMMON_API UnicodeString : public Replaceable static inline UnicodeString readOnlyAlias(const S &text) { return readOnlyAliasFromU16StringView(internal::toU16StringView(text)); } + + /** + * Readonly-aliasing factory method. + * Aliases the same buffer as the input `text`. + * + * The text will be used for the UnicodeString object, but + * it will not be released when the UnicodeString is destroyed. + * This has copy-on-write semantics: + * When the string is modified, then the buffer is first copied into + * newly allocated memory. + * The aliased buffer is never modified. + * + * In an assignment to another UnicodeString, when using the copy constructor + * or the assignment operator, the text will be copied. + * When using fastCopyFrom(), the text will be aliased again, + * so that both strings then alias the same readonly-text. + * + * @param text The UnicodeString to alias. + * @draft ICU 76 + */ + static inline UnicodeString readOnlyAlias(const UnicodeString &text) { + return readOnlyAliasFromUnicodeString(text); + } #endif // U_HIDE_DRAFT_API /** @@ -3730,6 +3753,7 @@ class U_COMMON_API UnicodeString : public Replaceable private: static UnicodeString readOnlyAliasFromU16StringView(std::u16string_view text); + static UnicodeString readOnlyAliasFromUnicodeString(const UnicodeString &text); // For char* constructors. Could be made public. UnicodeString &setToUTF8(StringPiece utf8); diff --git a/icu4c/source/common/unistr.cpp b/icu4c/source/common/unistr.cpp index ca577ecb1560..a9d5f81cb2f0 100644 --- a/icu4c/source/common/unistr.cpp +++ b/icu4c/source/common/unistr.cpp @@ -308,6 +308,16 @@ UnicodeString UnicodeString::readOnlyAliasFromU16StringView(std::u16string_view return result; } +UnicodeString UnicodeString::readOnlyAliasFromUnicodeString(const UnicodeString &text) { + UnicodeString result; + if (text.isBogus()) { + result.setToBogus(); + } else { + result.setTo(false, text.getBuffer(), text.length()); + } + return result; +} + #if U_CHARSET_IS_UTF8 UnicodeString::UnicodeString(const char *codepageData) {