1 // Copyright 2013 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.
5 #ifndef GIN_DICTIONARY_H_
6 #define GIN_DICTIONARY_H_
8 #include "base/memory/raw_ptr.h"
9 #include "gin/converter.h"
10 #include "gin/gin_export.h"
14 // Dictionary is useful when writing bindings for a function that either
15 // receives an arbitrary JavaScript object as an argument or returns an
16 // arbitrary JavaScript object as a result. For example, Dictionary is useful
17 // when you might use the |dictionary| type in WebIDL:
19 // https://webidl.spec.whatwg.org/#idl-dictionaries
21 // WARNING: You cannot retain a Dictionary object in the heap. The underlying
22 // storage for Dictionary is tied to the closest enclosing
23 // v8::HandleScope. Generally speaking, you should store a Dictionary
26 class GIN_EXPORT Dictionary {
28 explicit Dictionary(v8::Isolate* isolate);
29 Dictionary(v8::Isolate* isolate, v8::Local<v8::Object> object);
30 Dictionary(const Dictionary& other);
33 static Dictionary CreateEmpty(v8::Isolate* isolate);
36 bool Get(const std::string& key, T* out) {
37 v8::Local<v8::Value> val;
38 if (!object_->Get(isolate_->GetCurrentContext(), StringToV8(isolate_, key))
42 return ConvertFromV8(isolate_, val, out);
46 bool Set(const std::string& key, const T& val) {
47 v8::Local<v8::Value> v8_value;
48 if (!TryConvertToV8(isolate_, val, &v8_value))
50 v8::Maybe<bool> result =
51 object_->Set(isolate_->GetCurrentContext(), StringToV8(isolate_, key),
53 return !result.IsNothing() && result.FromJust();
56 v8::Isolate* isolate() const { return isolate_; }
59 friend struct Converter<Dictionary>;
61 // TODO(aa): Remove this. Instead, get via FromV8(), Set(), and Get().
62 raw_ptr<v8::Isolate> isolate_;
63 v8::Local<v8::Object> object_;
67 struct GIN_EXPORT Converter<Dictionary> {
68 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
70 static bool FromV8(v8::Isolate* isolate,
71 v8::Local<v8::Value> val,
77 #endif // GIN_DICTIONARY_H_