nsEmbedStream.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "nsIAsyncInputStream.h"
  6. #include "nsIAsyncOutputStream.h"
  7. #include "nsIDocShell.h"
  8. #include "nsIInterfaceRequestorUtils.h"
  9. #include "nsIPipe.h"
  10. #include "nsEmbedStream.h"
  11. #include "nsError.h"
  12. #include "nsString.h"
  13. NS_IMPL_ISUPPORTS0(nsEmbedStream)
  14. nsEmbedStream::nsEmbedStream()
  15. {
  16. mOwner = nullptr;
  17. }
  18. nsEmbedStream::~nsEmbedStream()
  19. {
  20. }
  21. void
  22. nsEmbedStream::InitOwner(nsIWebBrowser* aOwner)
  23. {
  24. mOwner = aOwner;
  25. }
  26. nsresult
  27. nsEmbedStream::Init(void)
  28. {
  29. return NS_OK;
  30. }
  31. nsresult
  32. nsEmbedStream::OpenStream(nsIURI* aBaseURI, const nsACString& aContentType)
  33. {
  34. nsresult rv;
  35. NS_ENSURE_ARG_POINTER(aBaseURI);
  36. NS_ENSURE_TRUE(IsASCII(aContentType), NS_ERROR_INVALID_ARG);
  37. // if we're already doing a stream, return an error
  38. if (mOutputStream) {
  39. return NS_ERROR_IN_PROGRESS;
  40. }
  41. nsCOMPtr<nsIAsyncInputStream> inputStream;
  42. nsCOMPtr<nsIAsyncOutputStream> outputStream;
  43. rv = NS_NewPipe2(getter_AddRefs(inputStream), getter_AddRefs(outputStream),
  44. true, false, 0, UINT32_MAX);
  45. if (NS_FAILED(rv)) {
  46. return rv;
  47. }
  48. nsCOMPtr<nsIDocShell> docShell = do_GetInterface(mOwner);
  49. rv = docShell->LoadStream(inputStream, aBaseURI, aContentType,
  50. EmptyCString(), nullptr);
  51. if (NS_FAILED(rv)) {
  52. return rv;
  53. }
  54. mOutputStream = outputStream;
  55. return rv;
  56. }
  57. nsresult
  58. nsEmbedStream::AppendToStream(const uint8_t* aData, uint32_t aLen)
  59. {
  60. nsresult rv;
  61. NS_ENSURE_STATE(mOutputStream);
  62. uint32_t bytesWritten = 0;
  63. rv = mOutputStream->Write(reinterpret_cast<const char*>(aData),
  64. aLen, &bytesWritten);
  65. if (NS_FAILED(rv)) {
  66. return rv;
  67. }
  68. NS_ASSERTION(bytesWritten == aLen,
  69. "underlying buffer couldn't handle the write");
  70. return rv;
  71. }
  72. nsresult
  73. nsEmbedStream::CloseStream(void)
  74. {
  75. nsresult rv = NS_OK;
  76. // NS_ENSURE_STATE returns NS_ERROR_UNEXPECTED if the condition isn't
  77. // satisfied; this is exactly what we want to return.
  78. NS_ENSURE_STATE(mOutputStream);
  79. mOutputStream->Close();
  80. mOutputStream = nullptr;
  81. return rv;
  82. }