[M120 Migration] Set IO|GPU thread type with higher priorites
[platform/framework/web/chromium-efl.git] / gin / data_object_builder.h
1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef GIN_DATA_OBJECT_BUILDER_H_
6 #define GIN_DATA_OBJECT_BUILDER_H_
7
8 #include <utility>
9
10 #include "base/check.h"
11 #include "base/memory/raw_ptr.h"
12 #include "base/strings/string_piece.h"
13 #include "gin/converter.h"
14 #include "gin/gin_export.h"
15 #include "v8/include/v8-forward.h"
16 #include "v8/include/v8-object.h"
17
18 namespace gin {
19
20 // Constructs a JavaScript object with a series of data properties.
21 // (As with default data properties in JavaScript, these properties are
22 // configurable, writable and enumerable.)
23 //
24 // Values are automatically converted using gin::Converter, though if
25 // using a type where the conversion may fail, callers must convert ahead of
26 // time.
27 //
28 // This class avoids the pitfall of using v8::Object::Set, which may invoke
29 // setters on the object prototype.
30 //
31 // Expected usage:
32 // v8::Local<v8::Object> object = gin::DataObjectBuilder(isolate)
33 //     .Set("boolean", true)
34 //     .Set("integer", 42)
35 //     .Build();
36 //
37 // Because this builder class contains local handles, callers must ensure it
38 // does not outlive the scope in which it is created.
39 class GIN_EXPORT DataObjectBuilder {
40  public:
41   explicit DataObjectBuilder(v8::Isolate* isolate);
42   DataObjectBuilder(const DataObjectBuilder&) = delete;
43   DataObjectBuilder& operator=(const DataObjectBuilder&) = delete;
44
45   ~DataObjectBuilder();
46
47   template <typename T>
48   DataObjectBuilder& Set(base::StringPiece key, T&& value) {
49     DCHECK(!object_.IsEmpty());
50     v8::Local<v8::String> v8_key = StringToSymbol(isolate_, key);
51     v8::Local<v8::Value> v8_value =
52         ConvertToV8(isolate_, std::forward<T>(value));
53     CHECK(object_->CreateDataProperty(context_, v8_key, v8_value).ToChecked());
54     return *this;
55   }
56
57   template <typename T>
58   DataObjectBuilder& Set(uint32_t index, T&& value) {
59     DCHECK(!object_.IsEmpty());
60     v8::Local<v8::Value> v8_value =
61         ConvertToV8(isolate_, std::forward<T>(value));
62     CHECK(object_->CreateDataProperty(context_, index, v8_value).ToChecked());
63     return *this;
64   }
65
66   v8::Local<v8::Object> Build() {
67     DCHECK(!object_.IsEmpty());
68     v8::Local<v8::Object> result = object_;
69     object_.Clear();
70     return result;
71   }
72
73  private:
74   raw_ptr<v8::Isolate> isolate_;
75   v8::Local<v8::Context> context_;
76   v8::Local<v8::Object> object_;
77 };
78
79 }  // namespace gin
80
81 #endif  // GIN_DATA_OBJECT_BUILDER_H_