encode() function implementation
| 385 | |
| 386 | // encode() function implementation |
| 387 | JSObject* gjs_encode_to_uint8array(JSContext* cx, JS::HandleString str, |
| 388 | const char* encoding, |
| 389 | GjsStringTermination string_termination) { |
| 390 | JS::RootedObject array_buffer(cx); |
| 391 | |
| 392 | bool encoding_is_utf8 = is_utf8_label(encoding); |
| 393 | if (encoding_is_utf8) { |
| 394 | JS::UniqueChars utf8; |
| 395 | size_t utf8_len; |
| 396 | |
| 397 | if (!gjs_string_to_utf8_n(cx, str, &utf8, &utf8_len)) |
| 398 | return nullptr; |
| 399 | |
| 400 | if (string_termination == GjsStringTermination::ZERO_TERMINATED) { |
| 401 | // strlen is safe because gjs_string_to_utf8_n returns |
| 402 | // a null-terminated string. |
| 403 | utf8_len = strlen(utf8.get()); |
| 404 | } |
| 405 | |
| 406 | array_buffer = |
| 407 | JS::NewArrayBufferWithContents(cx, utf8_len, std::move(utf8)); |
| 408 | } else { |
| 409 | Gjs::AutoError error; |
| 410 | Gjs::AutoChar encoded; |
| 411 | size_t bytes_written; |
| 412 | |
| 413 | /* Scope for AutoCheckCannotGC, will crash if a GC is triggered while we |
| 414 | * are using the string's chars */ |
| 415 | { |
| 416 | JS::AutoCheckCannotGC nogc; |
| 417 | size_t len; |
| 418 | |
| 419 | if (JS::StringHasLatin1Chars(str)) { |
| 420 | const JS::Latin1Char* chars = |
| 421 | JS_GetLatin1StringCharsAndLength(cx, nogc, str, &len); |
| 422 | if (!chars) |
| 423 | return nullptr; |
| 424 | |
| 425 | encoded = g_convert(reinterpret_cast<const char*>(chars), len, |
| 426 | encoding, // to_encoding |
| 427 | "LATIN1", // from_encoding |
| 428 | nullptr, // bytes_read |
| 429 | &bytes_written, &error); |
| 430 | } else { |
| 431 | const char16_t* chars = |
| 432 | JS_GetTwoByteStringCharsAndLength(cx, nogc, str, &len); |
| 433 | if (!chars) |
| 434 | return nullptr; |
| 435 | |
| 436 | encoded = |
| 437 | g_convert(reinterpret_cast<const char*>(chars), len * 2, |
| 438 | encoding, // to_encoding |
| 439 | "UTF-16", // from_encoding |
| 440 | nullptr, // bytes_read |
| 441 | &bytes_written, &error); |
| 442 | } |
| 443 | } |
| 444 |
no test coverage detected