* gjs_string_to_ucs4: * @cx: a #JSContext * @str: rooted JSString * @ucs4_string_p: return location for a #gunichar array * @len_p: return location for @ucs4_string_p length * * Returns: true on success, false otherwise in which case a JS error is thrown */
| 315 | * Returns: true on success, false otherwise in which case a JS error is thrown |
| 316 | */ |
| 317 | bool gjs_string_to_ucs4(JSContext* cx, JS::HandleString str, |
| 318 | gunichar** ucs4_string_p, size_t* len_p) { |
| 319 | if (ucs4_string_p == nullptr) |
| 320 | return true; |
| 321 | |
| 322 | size_t len; |
| 323 | Gjs::AutoError error; |
| 324 | |
| 325 | if (JS::StringHasLatin1Chars(str)) |
| 326 | return from_latin1(cx, str, ucs4_string_p, len_p); |
| 327 | |
| 328 | /* From this point on, crash if a GC is triggered while we are using the |
| 329 | * string's chars */ |
| 330 | JS::AutoCheckCannotGC nogc; |
| 331 | |
| 332 | const char16_t* utf16 = |
| 333 | JS_GetTwoByteStringCharsAndLength(cx, nogc, str, &len); |
| 334 | |
| 335 | if (utf16 == nullptr) { |
| 336 | gjs_throw(cx, "Failed to get UTF-16 string data"); |
| 337 | return false; |
| 338 | } |
| 339 | |
| 340 | if (ucs4_string_p != nullptr) { |
| 341 | long length; |
| 342 | *ucs4_string_p = |
| 343 | g_utf16_to_ucs4(reinterpret_cast<const gunichar2*>(utf16), len, |
| 344 | nullptr, &length, &error); |
| 345 | if (*ucs4_string_p == nullptr) { |
| 346 | gjs_throw(cx, "Failed to convert UTF-16 string to UCS-4: %s", |
| 347 | error->message); |
| 348 | return false; |
| 349 | } |
| 350 | if (len_p != nullptr) |
| 351 | *len_p = static_cast<size_t>(length); |
| 352 | } |
| 353 | |
| 354 | return true; |
| 355 | } |
| 356 | |
| 357 | /** |
| 358 | * gjs_string_from_ucs4: |