dictionary.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef GIN_DICTIONARY_H_
  5. #define GIN_DICTIONARY_H_
  6. #include "base/memory/raw_ptr.h"
  7. #include "gin/converter.h"
  8. #include "gin/gin_export.h"
  9. namespace gin {
  10. // Dictionary is useful when writing bindings for a function that either
  11. // receives an arbitrary JavaScript object as an argument or returns an
  12. // arbitrary JavaScript object as a result. For example, Dictionary is useful
  13. // when you might use the |dictionary| type in WebIDL:
  14. //
  15. // https://webidl.spec.whatwg.org/#idl-dictionaries
  16. //
  17. // WARNING: You cannot retain a Dictionary object in the heap. The underlying
  18. // storage for Dictionary is tied to the closest enclosing
  19. // v8::HandleScope. Generally speaking, you should store a Dictionary
  20. // on the stack.
  21. //
  22. class GIN_EXPORT Dictionary {
  23. public:
  24. explicit Dictionary(v8::Isolate* isolate);
  25. Dictionary(v8::Isolate* isolate, v8::Local<v8::Object> object);
  26. Dictionary(const Dictionary& other);
  27. ~Dictionary();
  28. static Dictionary CreateEmpty(v8::Isolate* isolate);
  29. template<typename T>
  30. bool Get(const std::string& key, T* out) {
  31. v8::Local<v8::Value> val;
  32. if (!object_->Get(isolate_->GetCurrentContext(), StringToV8(isolate_, key))
  33. .ToLocal(&val)) {
  34. return false;
  35. }
  36. return ConvertFromV8(isolate_, val, out);
  37. }
  38. template <typename T>
  39. bool Set(const std::string& key, const T& val) {
  40. v8::Local<v8::Value> v8_value;
  41. if (!TryConvertToV8(isolate_, val, &v8_value))
  42. return false;
  43. v8::Maybe<bool> result =
  44. object_->Set(isolate_->GetCurrentContext(), StringToV8(isolate_, key),
  45. v8_value);
  46. return !result.IsNothing() && result.FromJust();
  47. }
  48. v8::Isolate* isolate() const { return isolate_; }
  49. private:
  50. friend struct Converter<Dictionary>;
  51. // TODO(aa): Remove this. Instead, get via FromV8(), Set(), and Get().
  52. raw_ptr<v8::Isolate> isolate_;
  53. v8::Local<v8::Object> object_;
  54. };
  55. template<>
  56. struct GIN_EXPORT Converter<Dictionary> {
  57. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  58. Dictionary val);
  59. static bool FromV8(v8::Isolate* isolate,
  60. v8::Local<v8::Value> val,
  61. Dictionary* out);
  62. };
  63. } // namespace gin
  64. #endif // GIN_DICTIONARY_H_