lib/icu/Util: pass std::string_view

This commit is contained in:
Max Kellermann 2020-04-03 15:06:21 +02:00
parent 2d0798cd4d
commit 9dc530ab51
2 changed files with 10 additions and 14 deletions

View File

@ -31,18 +31,15 @@
#include <string.h> #include <string.h>
AllocatedArray<UChar> AllocatedArray<UChar>
UCharFromUTF8(const char *src) UCharFromUTF8(std::string_view src)
{ {
assert(src != nullptr); const size_t dest_capacity = src.size();
const size_t src_length = strlen(src);
const size_t dest_capacity = src_length;
AllocatedArray<UChar> dest(dest_capacity); AllocatedArray<UChar> dest(dest_capacity);
UErrorCode error_code = U_ZERO_ERROR; UErrorCode error_code = U_ZERO_ERROR;
int32_t dest_length; int32_t dest_length;
u_strFromUTF8(dest.begin(), dest_capacity, &dest_length, u_strFromUTF8(dest.begin(), dest_capacity, &dest_length,
src, src_length, src.data(), src.size(),
&error_code); &error_code);
if (U_FAILURE(error_code)) if (U_FAILURE(error_code))
throw std::runtime_error(u_errorName(error_code)); throw std::runtime_error(u_errorName(error_code));
@ -52,19 +49,17 @@ UCharFromUTF8(const char *src)
} }
AllocatedString<> AllocatedString<>
UCharToUTF8(ConstBuffer<UChar> src) UCharToUTF8(std::basic_string_view<UChar> src)
{ {
assert(!src.IsNull());
/* worst-case estimate */ /* worst-case estimate */
size_t dest_capacity = 4 * src.size; size_t dest_capacity = 4 * src.size();
std::unique_ptr<char[]> dest(new char[dest_capacity + 1]); std::unique_ptr<char[]> dest(new char[dest_capacity + 1]);
UErrorCode error_code = U_ZERO_ERROR; UErrorCode error_code = U_ZERO_ERROR;
int32_t dest_length; int32_t dest_length;
u_strToUTF8(dest.get(), dest_capacity, &dest_length, u_strToUTF8(dest.get(), dest_capacity, &dest_length,
src.data, src.size, src.data(), src.size(),
&error_code); &error_code);
if (U_FAILURE(error_code)) if (U_FAILURE(error_code))
throw std::runtime_error(u_errorName(error_code)); throw std::runtime_error(u_errorName(error_code));

View File

@ -22,7 +22,8 @@
#include <unicode/utypes.h> #include <unicode/utypes.h>
template<typename T> struct ConstBuffer; #include <string_view>
template<typename T> class AllocatedArray; template<typename T> class AllocatedArray;
template<typename T> class AllocatedString; template<typename T> class AllocatedString;
@ -32,7 +33,7 @@ template<typename T> class AllocatedString;
* Throws std::runtime_error on error. * Throws std::runtime_error on error.
*/ */
AllocatedArray<UChar> AllocatedArray<UChar>
UCharFromUTF8(const char *src); UCharFromUTF8(std::string_view src);
/** /**
* Wrapper for u_strToUTF8(). * Wrapper for u_strToUTF8().
@ -40,6 +41,6 @@ UCharFromUTF8(const char *src);
* Throws std::runtime_error on error. * Throws std::runtime_error on error.
*/ */
AllocatedString<char> AllocatedString<char>
UCharToUTF8(ConstBuffer<UChar> src); UCharToUTF8(std::basic_string_view<UChar> src);
#endif #endif