|
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 |
|
8 #include "mozilla/Base64.h" |
|
9 #include "nsISerializable.h" |
|
10 #include "nsIObjectOutputStream.h" |
|
11 #include "nsIObjectInputStream.h" |
|
12 #include "nsString.h" |
|
13 #include "nsBase64Encoder.h" |
|
14 #include "nsAutoPtr.h" |
|
15 #include "nsComponentManagerUtils.h" |
|
16 #include "nsStringStream.h" |
|
17 |
|
18 using namespace mozilla; |
|
19 |
|
20 nsresult |
|
21 NS_SerializeToString(nsISerializable* obj, nsCSubstring& str) |
|
22 { |
|
23 nsRefPtr<nsBase64Encoder> stream(new nsBase64Encoder()); |
|
24 if (!stream) |
|
25 return NS_ERROR_OUT_OF_MEMORY; |
|
26 |
|
27 nsCOMPtr<nsIObjectOutputStream> objstream = |
|
28 do_CreateInstance("@mozilla.org/binaryoutputstream;1"); |
|
29 if (!objstream) |
|
30 return NS_ERROR_OUT_OF_MEMORY; |
|
31 |
|
32 objstream->SetOutputStream(stream); |
|
33 nsresult rv = |
|
34 objstream->WriteCompoundObject(obj, NS_GET_IID(nsISupports), true); |
|
35 NS_ENSURE_SUCCESS(rv, rv); |
|
36 return stream->Finish(str); |
|
37 } |
|
38 |
|
39 nsresult |
|
40 NS_DeserializeObject(const nsCSubstring& str, nsISupports** obj) |
|
41 { |
|
42 nsCString decodedData; |
|
43 nsresult rv = Base64Decode(str, decodedData); |
|
44 NS_ENSURE_SUCCESS(rv, rv); |
|
45 |
|
46 nsCOMPtr<nsIInputStream> stream; |
|
47 rv = NS_NewCStringInputStream(getter_AddRefs(stream), decodedData); |
|
48 NS_ENSURE_SUCCESS(rv, rv); |
|
49 |
|
50 nsCOMPtr<nsIObjectInputStream> objstream = |
|
51 do_CreateInstance("@mozilla.org/binaryinputstream;1"); |
|
52 if (!objstream) |
|
53 return NS_ERROR_OUT_OF_MEMORY; |
|
54 |
|
55 objstream->SetInputStream(stream); |
|
56 return objstream->ReadObject(true, obj); |
|
57 } |
|
58 |
|
59 NS_IMPL_ISUPPORTS(nsSerializationHelper, nsISerializationHelper) |
|
60 |
|
61 NS_IMETHODIMP |
|
62 nsSerializationHelper::SerializeToString(nsISerializable *serializable, |
|
63 nsACString & _retval) |
|
64 { |
|
65 return NS_SerializeToString(serializable, _retval); |
|
66 } |
|
67 |
|
68 NS_IMETHODIMP |
|
69 nsSerializationHelper::DeserializeObject(const nsACString & input, |
|
70 nsISupports **_retval) |
|
71 { |
|
72 return NS_DeserializeObject(input, _retval); |
|
73 } |