Bug 1472338: part 2) Change `clipboard.readText()` to read from the clipboard asynchr...
[gecko.git] / dom / payments / PaymentRequestUtils.cpp
blob073e03f54eb1ab05cf1535bdf67de5f0ed20b81f
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/. */
7 #include "js/JSON.h"
8 #include "nsContentUtils.h"
9 #include "nsArrayUtils.h"
10 #include "nsTString.h"
11 #include "PaymentRequestUtils.h"
13 namespace mozilla::dom {
15 nsresult SerializeFromJSObject(JSContext* aCx, JS::HandleObject aObject,
16 nsAString& aSerializedObject) {
17 MOZ_ASSERT(aCx);
18 JS::RootedValue value(aCx, JS::ObjectValue(*aObject));
19 return SerializeFromJSVal(aCx, value, aSerializedObject);
22 nsresult SerializeFromJSVal(JSContext* aCx, JS::HandleValue aValue,
23 nsAString& aSerializedValue) {
24 aSerializedValue.Truncate();
25 nsAutoString serializedValue;
26 JS::RootedValue value(aCx, aValue.get());
27 NS_ENSURE_TRUE(nsContentUtils::StringifyJSON(aCx, &value, serializedValue),
28 NS_ERROR_XPC_BAD_CONVERT_JS);
29 NS_ENSURE_TRUE(!serializedValue.IsEmpty(), NS_ERROR_FAILURE);
30 aSerializedValue = serializedValue;
31 return NS_OK;
34 nsresult DeserializeToJSObject(const nsAString& aSerializedObject,
35 JSContext* aCx,
36 JS::MutableHandleObject aObject) {
37 MOZ_ASSERT(aCx);
38 JS::RootedValue value(aCx);
39 nsresult rv = DeserializeToJSValue(aSerializedObject, aCx, &value);
40 if (NS_WARN_IF(NS_FAILED(rv))) {
41 return rv;
43 if (value.isObject()) {
44 aObject.set(&value.toObject());
45 } else {
46 aObject.set(nullptr);
48 return NS_OK;
51 nsresult DeserializeToJSValue(const nsAString& aSerializedObject,
52 JSContext* aCx, JS::MutableHandleValue aValue) {
53 MOZ_ASSERT(aCx);
54 if (!JS_ParseJSON(aCx, aSerializedObject.BeginReading(),
55 aSerializedObject.Length(), aValue)) {
56 return NS_ERROR_UNEXPECTED;
58 return NS_OK;
61 } // namespace mozilla::dom