Line data Source code
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 4 : NS_SerializeToString(nsISerializable* obj, nsACString& str)
22 : {
23 8 : RefPtr<nsBase64Encoder> stream(new nsBase64Encoder());
24 4 : if (!stream)
25 0 : return NS_ERROR_OUT_OF_MEMORY;
26 :
27 : nsCOMPtr<nsIObjectOutputStream> objstream =
28 8 : do_CreateInstance("@mozilla.org/binaryoutputstream;1");
29 4 : if (!objstream)
30 0 : return NS_ERROR_OUT_OF_MEMORY;
31 :
32 4 : objstream->SetOutputStream(stream);
33 : nsresult rv =
34 4 : objstream->WriteCompoundObject(obj, NS_GET_IID(nsISupports), true);
35 4 : NS_ENSURE_SUCCESS(rv, rv);
36 4 : return stream->Finish(str);
37 : }
38 :
39 : nsresult
40 2 : NS_DeserializeObject(const nsACString& str, nsISupports** obj)
41 : {
42 4 : nsCString decodedData;
43 2 : nsresult rv = Base64Decode(str, decodedData);
44 2 : NS_ENSURE_SUCCESS(rv, rv);
45 :
46 4 : nsCOMPtr<nsIInputStream> stream;
47 2 : rv = NS_NewCStringInputStream(getter_AddRefs(stream), decodedData);
48 2 : NS_ENSURE_SUCCESS(rv, rv);
49 :
50 : nsCOMPtr<nsIObjectInputStream> objstream =
51 4 : do_CreateInstance("@mozilla.org/binaryinputstream;1");
52 2 : if (!objstream)
53 0 : return NS_ERROR_OUT_OF_MEMORY;
54 :
55 2 : objstream->SetInputStream(stream);
56 2 : return objstream->ReadObject(true, obj);
57 : }
58 :
59 99 : NS_IMPL_ISUPPORTS(nsSerializationHelper, nsISerializationHelper)
60 :
61 : NS_IMETHODIMP
62 4 : nsSerializationHelper::SerializeToString(nsISerializable *serializable,
63 : nsACString & _retval)
64 : {
65 4 : return NS_SerializeToString(serializable, _retval);
66 : }
67 :
68 : NS_IMETHODIMP
69 1 : nsSerializationHelper::DeserializeObject(const nsACString & input,
70 : nsISupports **_retval)
71 : {
72 1 : return NS_DeserializeObject(input, _retval);
73 : }
|