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/. */
6 #include "MemoryDownloader.h"
8 #include "mozilla/Assertions.h"
9 #include "nsIInputStream.h"
14 NS_IMPL_ISUPPORTS(MemoryDownloader
, nsIStreamListener
, nsIRequestObserver
)
16 MemoryDownloader::MemoryDownloader(IObserver
* aObserver
)
17 : mObserver(aObserver
), mStatus(NS_ERROR_NOT_INITIALIZED
) {}
20 MemoryDownloader::OnStartRequest(nsIRequest
* aRequest
, nsISupports
* aCtxt
) {
22 mData
.reset(new FallibleTArray
<uint8_t>());
28 MemoryDownloader::OnStopRequest(nsIRequest
* aRequest
, nsISupports
* aCtxt
,
30 MOZ_ASSERT_IF(NS_FAILED(mStatus
), NS_FAILED(aStatus
));
31 MOZ_ASSERT(!mData
== NS_FAILED(mStatus
));
34 RefPtr
<IObserver
> observer
;
35 observer
.swap(mObserver
);
36 observer
->OnDownloadComplete(this, aRequest
, aCtxt
, aStatus
, std::move(data
));
40 nsresult
MemoryDownloader::ConsumeData(nsIInputStream
* aIn
, void* aClosure
,
41 const char* aFromRawSegment
,
42 uint32_t aToOffset
, uint32_t aCount
,
43 uint32_t* aWriteCount
) {
44 MemoryDownloader
* self
= static_cast<MemoryDownloader
*>(aClosure
);
45 if (!self
->mData
->AppendElements(aFromRawSegment
, aCount
, fallible
)) {
46 // The error returned by ConsumeData isn't propagated to the
47 // return of ReadSegments, so it has to be passed as state.
48 self
->mStatus
= NS_ERROR_OUT_OF_MEMORY
;
49 return NS_ERROR_OUT_OF_MEMORY
;
51 *aWriteCount
= aCount
;
56 MemoryDownloader::OnDataAvailable(nsIRequest
* aRequest
, nsISupports
* aCtxt
,
57 nsIInputStream
* aInStr
,
58 uint64_t aSourceOffset
, uint32_t aCount
) {
61 nsresult rv
= aInStr
->ReadSegments(ConsumeData
, this, aCount
, &n
);
62 if (NS_SUCCEEDED(mStatus
) && NS_FAILED(rv
)) {
65 if (NS_WARN_IF(NS_FAILED(mStatus
))) {
73 } // namespace mozilla