Browse Source

refactor: add ToV8() function for std::span<T>

Charles Kerr 5 months ago
parent
commit
6ae56f1bd1
1 changed files with 27 additions and 0 deletions
  1. 27 0
      shell/common/gin_converters/std_converter.h

+ 27 - 0
shell/common/gin_converters/std_converter.h

@@ -9,6 +9,7 @@
 #include <functional>
 #include <map>
 #include <set>
+#include <span>
 #include <type_traits>
 #include <utility>
 
@@ -93,6 +94,32 @@ struct Converter<v8::Local<v8::String>> {
   }
 };
 
+template <typename T>
+struct Converter<std::span<T>> {
+  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
+                                   const std::span<const T> vals) {
+    const auto n_vals = vals.size();
+    auto result = v8::Array::New(isolate, static_cast<int>(n_vals));
+
+    uint32_t index = 0U;
+    v8::Local<v8::Context> context = isolate->GetCurrentContext();
+    for (const auto& val : vals) {
+      v8::MaybeLocal<v8::Value> maybe = Converter<T>::ToV8(isolate, val);
+      v8::Local<v8::Value> element;
+      if (!maybe.ToLocal(&element))
+        return {};
+
+      bool property_created = false;
+      if (!result->CreateDataProperty(context, index++, element)
+               .To(&property_created) ||
+          !property_created) {
+        NOTREACHED() << "CreateDataProperty should always succeed here.";
+      }
+    }
+    return result;
+  }
+};
+
 template <typename T>
 struct Converter<std::set<T>> {
   static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,