diff --git a/src/lib/icu/Util.cxx b/src/lib/icu/Util.cxx index 57cf2f59f..bd276756a 100644 --- a/src/lib/icu/Util.cxx +++ b/src/lib/icu/Util.cxx @@ -27,6 +27,7 @@ #include #include +#include #include #include @@ -73,3 +74,25 @@ UCharToUTF8(ConstBuffer src) dest[dest_length] = 0; return AllocatedString<>::Donate(dest.release()); } + +AllocatedString<> +UCharToUTF8Throw(ConstBuffer src) +{ + assert(!src.IsNull()); + + /* worst-case estimate */ + size_t dest_capacity = 4 * src.size; + + std::unique_ptr dest(new char[dest_capacity + 1]); + + UErrorCode error_code = U_ZERO_ERROR; + int32_t dest_length; + u_strToUTF8(dest.get(), dest_capacity, &dest_length, + src.data, src.size, + &error_code); + if (U_FAILURE(error_code)) + throw std::runtime_error(u_errorName(error_code)); + + dest[dest_length] = 0; + return AllocatedString<>::Donate(dest.release()); +} diff --git a/src/lib/icu/Util.hxx b/src/lib/icu/Util.hxx index e2dd3713c..c72d6330f 100644 --- a/src/lib/icu/Util.hxx +++ b/src/lib/icu/Util.hxx @@ -40,4 +40,12 @@ UCharFromUTF8(const char *src); AllocatedString UCharToUTF8(ConstBuffer src); +/** + * Wrapper for u_strToUTF8(). + * + * Throws std::runtime_error on error. + */ +AllocatedString +UCharToUTF8Throw(ConstBuffer src); + #endif