PaymentRequestUtils.cpp (2111B)
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 #include "PaymentRequestUtils.h" 8 9 #include "js/JSON.h" 10 #include "nsArrayUtils.h" 11 #include "nsContentUtils.h" 12 #include "nsTString.h" 13 14 namespace mozilla::dom { 15 16 nsresult SerializeFromJSObject(JSContext* aCx, JS::Handle<JSObject*> aObject, 17 nsAString& aSerializedObject) { 18 MOZ_ASSERT(aCx); 19 JS::Rooted<JS::Value> value(aCx, JS::ObjectValue(*aObject)); 20 return SerializeFromJSVal(aCx, value, aSerializedObject); 21 } 22 23 nsresult SerializeFromJSVal(JSContext* aCx, JS::Handle<JS::Value> aValue, 24 nsAString& aSerializedValue) { 25 aSerializedValue.Truncate(); 26 NS_ENSURE_TRUE(nsContentUtils::StringifyJSON(aCx, aValue, aSerializedValue, 27 UndefinedIsNullStringLiteral), 28 NS_ERROR_XPC_BAD_CONVERT_JS); 29 NS_ENSURE_TRUE(!aSerializedValue.IsEmpty(), NS_ERROR_FAILURE); 30 return NS_OK; 31 } 32 33 nsresult DeserializeToJSObject(const nsAString& aSerializedObject, 34 JSContext* aCx, 35 JS::MutableHandle<JSObject*> aObject) { 36 MOZ_ASSERT(aCx); 37 JS::Rooted<JS::Value> value(aCx); 38 nsresult rv = DeserializeToJSValue(aSerializedObject, aCx, &value); 39 if (NS_WARN_IF(NS_FAILED(rv))) { 40 return rv; 41 } 42 if (value.isObject()) { 43 aObject.set(&value.toObject()); 44 } else { 45 aObject.set(nullptr); 46 } 47 return NS_OK; 48 } 49 50 nsresult DeserializeToJSValue(const nsAString& aSerializedObject, 51 JSContext* aCx, 52 JS::MutableHandle<JS::Value> aValue) { 53 MOZ_ASSERT(aCx); 54 if (!JS_ParseJSON(aCx, aSerializedObject.BeginReading(), 55 aSerializedObject.Length(), aValue)) { 56 return NS_ERROR_UNEXPECTED; 57 } 58 return NS_OK; 59 } 60 61 } // namespace mozilla::dom