1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #if !defined(MozPromiseInlines_h_)
8 #  define MozPromiseInlines_h_
9 
10 #  include <type_traits>
11 
12 #  include "mozilla/MozPromise.h"
13 #  include "mozilla/dom/PrimitiveConversions.h"
14 #  include "mozilla/dom/PromiseNativeHandler.h"
15 
16 namespace mozilla {
17 
18 // Creates a C++ MozPromise from its JS counterpart, dom::Promise.
19 // FromDomPromise currently only supports primitive types (int8/16/32, float,
20 // double) And the reject value type must be a nsresult.
21 template <typename ResolveValueT, typename RejectValueT, bool IsExclusive>
22 RefPtr<MozPromise<ResolveValueT, RejectValueT, IsExclusive>>
FromDomPromise(dom::Promise * aDOMPromise)23 MozPromise<ResolveValueT, RejectValueT, IsExclusive>::FromDomPromise(
24     dom::Promise* aDOMPromise) {
25   static_assert(std::is_same_v<RejectValueType, nsresult>,
26                 "Reject type must be nsresult");
27   RefPtr<Private> p = new Private(__func__);
28   RefPtr<dom::DomPromiseListener> listener = new dom::DomPromiseListener(
29       aDOMPromise,
30       [p](JSContext* aCx, JS::Handle<JS::Value> aValue) {
31         ResolveValueT value;
32         bool ok = dom::ValueToPrimitive<ResolveValueT,
33                                         dom::ConversionBehavior::eDefault>(
34             aCx, aValue, "Resolution value", &value);
35         if (!ok) {
36           p->Reject(NS_ERROR_FAILURE, __func__);
37           return;
38         }
39         p->Resolve(value, __func__);
40       },
41       [p](nsresult aError) { p->Reject(aError, __func__); });
42   return p;
43 }
44 
45 }  // namespace mozilla
46 
47 #endif
48