nsSerializationHelper.cpp (1833B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 #include "nsSerializationHelper.h" 6 7 #include "mozilla/Base64.h" 8 #include "nsISerializable.h" 9 #include "nsIObjectOutputStream.h" 10 #include "nsIObjectInputStream.h" 11 #include "nsString.h" 12 #include "nsBase64Encoder.h" 13 #include "nsComponentManagerUtils.h" 14 #include "nsStringStream.h" 15 16 using namespace mozilla; 17 18 nsresult NS_SerializeToString(nsISerializable* obj, nsACString& str) { 19 RefPtr<nsBase64Encoder> stream(new nsBase64Encoder()); 20 if (!stream) return NS_ERROR_OUT_OF_MEMORY; 21 22 nsCOMPtr<nsIObjectOutputStream> objstream = NS_NewObjectOutputStream(stream); 23 nsresult rv = 24 objstream->WriteCompoundObject(obj, NS_GET_IID(nsISupports), true); 25 NS_ENSURE_SUCCESS(rv, rv); 26 return stream->Finish(str); 27 } 28 29 nsresult NS_DeserializeObject(const nsACString& str, nsISupports** obj) { 30 nsCString decodedData; 31 nsresult rv = Base64Decode(str, decodedData); 32 NS_ENSURE_SUCCESS(rv, rv); 33 34 nsCOMPtr<nsIInputStream> stream; 35 rv = NS_NewCStringInputStream(getter_AddRefs(stream), std::move(decodedData)); 36 NS_ENSURE_SUCCESS(rv, rv); 37 38 nsCOMPtr<nsIObjectInputStream> objstream = NS_NewObjectInputStream(stream); 39 return objstream->ReadObject(true, obj); 40 } 41 42 NS_IMPL_ISUPPORTS(nsSerializationHelper, nsISerializationHelper) 43 44 NS_IMETHODIMP 45 nsSerializationHelper::SerializeToString(nsISerializable* serializable, 46 nsACString& _retval) { 47 return NS_SerializeToString(serializable, _retval); 48 } 49 50 NS_IMETHODIMP 51 nsSerializationHelper::DeserializeObject(const nsACString& input, 52 nsISupports** _retval) { 53 return NS_DeserializeObject(input, _retval); 54 }