[gjs] text-encoding: Factor out UTF-16 codeset into a string constant



commit f4cd224d848b010c7c58648c6d25ce10297acc0d
Author: Evan Welsh <contact evanwelsh com>
Date:   Sun Jun 13 18:17:00 2021 -0700

    text-encoding: Factor out UTF-16 codeset into a string constant
    
    This will be used in more places in the Encoding specification.

 gjs/text-encoding.cpp | 25 +++++++++++++++----------
 1 file changed, 15 insertions(+), 10 deletions(-)
---
diff --git a/gjs/text-encoding.cpp b/gjs/text-encoding.cpp
index 98d3dca9..dddece5b 100644
--- a/gjs/text-encoding.cpp
+++ b/gjs/text-encoding.cpp
@@ -35,22 +35,27 @@
 #include "gjs/jsapi-util.h"
 #include "gjs/text-encoding.h"
 
+// UTF16_CODESET is used to encode and decode UTF-16 buffers with
+// iconv. To ensure the output of iconv is laid out in memory correctly
+// we have to use UTF-16LE on little endian systems and UTF-16BE on big
+// endian systems.
+//
+// This ensures we can simply reinterpret_cast<char16_t> iconv's output.
+#if G_BYTE_ORDER == G_LITTLE_ENDIAN
+static const char* UTF16_CODESET = "UTF-16LE";
+#else
+static const char* UTF16_CODESET = "UTF-16BE";
+#endif
+
 GJS_JSAPI_RETURN_CONVENTION
 static bool to_string_impl_slow(JSContext* cx, uint8_t* data, uint32_t len,
                                 const char* encoding,
                                 JS::MutableHandleValue rval) {
     size_t bytes_written;
     GError* error = nullptr;
-    GjsAutoChar u16_str = g_convert(reinterpret_cast<char*>(data), len,
-    // Make sure the bytes of the UTF-16 string are laid out in memory
-    // such that we can simply reinterpret_cast<char16_t> them.
-#if G_BYTE_ORDER == G_LITTLE_ENDIAN
-                                    "UTF-16LE",
-#else
-                                    "UTF-16BE",
-#endif
-                                    encoding, nullptr, /* bytes read */
-                                    &bytes_written, &error);
+    GjsAutoChar u16_str =
+        g_convert(reinterpret_cast<char*>(data), len, UTF16_CODESET, encoding,
+                  /* bytes_read = */ nullptr, &bytes_written, &error);
     if (!u16_str)
         return gjs_throw_gerror_message(cx, error);  // frees GError
 


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]