nsSerializationHelper.cpp 2.0 KB

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