MemoryDownloader.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* -*- Mode: C++; 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 "MemoryDownloader.h"
  6. #include "mozilla/Assertions.h"
  7. #include "nsIInputStream.h"
  8. namespace mozilla {
  9. namespace net {
  10. NS_IMPL_ISUPPORTS(MemoryDownloader,
  11. nsIStreamListener,
  12. nsIRequestObserver)
  13. MemoryDownloader::MemoryDownloader(IObserver* aObserver)
  14. : mObserver(aObserver)
  15. {
  16. }
  17. MemoryDownloader::~MemoryDownloader()
  18. {
  19. }
  20. NS_IMETHODIMP
  21. MemoryDownloader::OnStartRequest(nsIRequest* aRequest, nsISupports* aCtxt)
  22. {
  23. MOZ_ASSERT(!mData);
  24. mData.reset(new FallibleTArray<uint8_t>());
  25. mStatus = NS_OK;
  26. return NS_OK;
  27. }
  28. NS_IMETHODIMP
  29. MemoryDownloader::OnStopRequest(nsIRequest* aRequest,
  30. nsISupports* aCtxt,
  31. nsresult aStatus)
  32. {
  33. MOZ_ASSERT_IF(NS_FAILED(mStatus), NS_FAILED(aStatus));
  34. MOZ_ASSERT(!mData == NS_FAILED(mStatus));
  35. Data data;
  36. data.swap(mData);
  37. RefPtr<IObserver> observer;
  38. observer.swap(mObserver);
  39. observer->OnDownloadComplete(this, aRequest, aCtxt, aStatus,
  40. mozilla::Move(data));
  41. return NS_OK;
  42. }
  43. nsresult
  44. MemoryDownloader::ConsumeData(nsIInputStream* aIn,
  45. void* aClosure,
  46. const char* aFromRawSegment,
  47. uint32_t aToOffset,
  48. uint32_t aCount,
  49. uint32_t* aWriteCount)
  50. {
  51. MemoryDownloader* self = static_cast<MemoryDownloader*>(aClosure);
  52. if (!self->mData->AppendElements(aFromRawSegment, aCount, fallible)) {
  53. // The error returned by ConsumeData isn't propagated to the
  54. // return of ReadSegments, so it has to be passed as state.
  55. self->mStatus = NS_ERROR_OUT_OF_MEMORY;
  56. return NS_ERROR_OUT_OF_MEMORY;
  57. }
  58. *aWriteCount = aCount;
  59. return NS_OK;
  60. }
  61. NS_IMETHODIMP
  62. MemoryDownloader::OnDataAvailable(nsIRequest* aRequest,
  63. nsISupports* aCtxt,
  64. nsIInputStream* aInStr,
  65. uint64_t aSourceOffset,
  66. uint32_t aCount)
  67. {
  68. uint32_t n;
  69. MOZ_ASSERT(mData);
  70. nsresult rv = aInStr->ReadSegments(ConsumeData, this, aCount, &n);
  71. if (NS_SUCCEEDED(mStatus) && NS_FAILED(rv)) {
  72. mStatus = rv;
  73. }
  74. if (NS_WARN_IF(NS_FAILED(mStatus))) {
  75. mData.reset(nullptr);
  76. return mStatus;
  77. }
  78. return NS_OK;
  79. }
  80. } // namespace net
  81. } // namespace mozilla