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/. */
5 #include "nsSerializationHelper.h"
7 #include "mozilla/Base64.h"
8 #include "nsISerializable.h"
9 #include "nsIObjectOutputStream.h"
10 #include "nsIObjectInputStream.h"
12 #include "nsBase64Encoder.h"
13 #include "nsComponentManagerUtils.h"
14 #include "nsStringStream.h"
16 using namespace mozilla
;
18 nsresult
NS_SerializeToString(nsISerializable
* obj
, nsACString
& str
) {
19 RefPtr
<nsBase64Encoder
> stream(new nsBase64Encoder());
20 if (!stream
) return NS_ERROR_OUT_OF_MEMORY
;
22 nsCOMPtr
<nsIObjectOutputStream
> objstream
= NS_NewObjectOutputStream(stream
);
24 objstream
->WriteCompoundObject(obj
, NS_GET_IID(nsISupports
), true);
25 NS_ENSURE_SUCCESS(rv
, rv
);
26 return stream
->Finish(str
);
29 nsresult
NS_DeserializeObject(const nsACString
& str
, nsISupports
** obj
) {
30 nsCString decodedData
;
31 nsresult rv
= Base64Decode(str
, decodedData
);
32 NS_ENSURE_SUCCESS(rv
, rv
);
34 nsCOMPtr
<nsIInputStream
> stream
;
35 rv
= NS_NewCStringInputStream(getter_AddRefs(stream
), std::move(decodedData
));
36 NS_ENSURE_SUCCESS(rv
, rv
);
38 nsCOMPtr
<nsIObjectInputStream
> objstream
= NS_NewObjectInputStream(stream
);
39 return objstream
->ReadObject(true, obj
);
42 NS_IMPL_ISUPPORTS(nsSerializationHelper
, nsISerializationHelper
)
45 nsSerializationHelper::SerializeToString(nsISerializable
* serializable
,
46 nsACString
& _retval
) {
47 return NS_SerializeToString(serializable
, _retval
);
51 nsSerializationHelper::DeserializeObject(const nsACString
& input
,
52 nsISupports
** _retval
) {
53 return NS_DeserializeObject(input
, _retval
);